Correctly handle a one-word struct passed byval on x86_64.
[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     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN , MVT::f64, Expand);
579     setOperationAction(ISD::FCOS , MVT::f64, Expand);
580     setOperationAction(ISD::FSIN , MVT::f32, Expand);
581     setOperationAction(ISD::FCOS , MVT::f32, Expand);
582
583     // Expand FP immediates into loads from the stack, except for the special
584     // cases we handle.
585     addLegalFPImmediate(APFloat(+0.0)); // xorpd
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587   } else if (!UseSoftFloat && X86ScalarSSEf32) {
588     // Use SSE for f32, x87 for f64.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592
593     // Use ANDPS to simulate FABS.
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600
601     // Use ANDPS and ORPS to simulate FCOPYSIGN.
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604
605     // We don't support sin/cos/fmod
606     setOperationAction(ISD::FSIN , MVT::f32, Expand);
607     setOperationAction(ISD::FCOS , MVT::f32, Expand);
608
609     // Special cases we handle for FP constants.
610     addLegalFPImmediate(APFloat(+0.0f)); // xorps
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615
616     if (!UnsafeFPMath) {
617       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
618       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
619     }
620   } else if (!UseSoftFloat) {
621     // f32 and f64 in x87.
622     // Set up the FP register classes.
623     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625
626     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
627     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
630
631     if (!UnsafeFPMath) {
632       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
633       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
634     }
635     addLegalFPImmediate(APFloat(+0.0)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
643   }
644
645   // Long double always uses X87.
646   if (!UseSoftFloat) {
647     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
649     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
650     {
651       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652       addLegalFPImmediate(TmpFlt);  // FLD0
653       TmpFlt.changeSign();
654       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
655
656       bool ignored;
657       APFloat TmpFlt2(+1.0);
658       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
659                       &ignored);
660       addLegalFPImmediate(TmpFlt2);  // FLD1
661       TmpFlt2.changeSign();
662       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
663     }
664
665     if (!UnsafeFPMath) {
666       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
667       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
668     }
669   }
670
671   // Always use a library call for pow.
672   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
674   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
675
676   setOperationAction(ISD::FLOG, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP, MVT::f80, Expand);
680   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
834     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
835     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
836     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     // i8 and i16 vectors are custom , because the source register and source
932     // source memory operand types are not the same width.  f32 vectors are
933     // custom since the immediate controlling the insert encodes additional
934     // information.
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
944
945     if (Subtarget->is64Bit()) {
946       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
947       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
948     }
949   }
950
951   if (Subtarget->hasSSE2()) {
952     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
953     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
954     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
955
956     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
959
960     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
961     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
962   }
963
964   if (Subtarget->hasSSE42())
965     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
966
967   if (!UseSoftFloat && Subtarget->hasAVX()) {
968     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
969     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
970     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
971     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
972     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
973
974     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
975     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
976     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
977     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
978
979     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
980     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
981     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
982     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
983     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
984     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
985
986     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
987     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
988     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
989     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
990     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
991     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
992
993     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
994     // insert_vector_elt extract_subvector and extract_vector_elt for
995     // 256-bit types.
996     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
997          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
998          ++i) {
999       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1000       // Do not attempt to custom lower non-256-bit vectors
1001       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1002           || (MVT(VT).getSizeInBits() < 256))
1003         continue;
1004       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1005       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1008       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1009     }
1010     // Custom-lower insert_subvector and extract_subvector based on
1011     // the result type.
1012     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1014          ++i) {
1015       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1016       // Do not attempt to custom lower non-256-bit vectors
1017       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1018         continue;
1019
1020       if (MVT(VT).getSizeInBits() == 128) {
1021         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1022       }
1023       else if (MVT(VT).getSizeInBits() == 256) {
1024         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1025       }
1026     }
1027
1028     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1029     // Don't promote loads because we need them for VPERM vector index versions.
1030
1031     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1032          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1033          VT++) {
1034       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1035           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1036         continue;
1037       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1038       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1039       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1040       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1041       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1044       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1047     }
1048   }
1049
1050   // We want to custom lower some of our intrinsics.
1051   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1052
1053
1054   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1055   // handle type legalization for these operations here.
1056   //
1057   // FIXME: We really should do custom legalization for addition and
1058   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1059   // than generic legalization for 64-bit multiplication-with-overflow, though.
1060   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1061     // Add/Sub/Mul with overflow operations are custom lowered.
1062     MVT VT = IntVTs[i];
1063     setOperationAction(ISD::SADDO, VT, Custom);
1064     setOperationAction(ISD::UADDO, VT, Custom);
1065     setOperationAction(ISD::SSUBO, VT, Custom);
1066     setOperationAction(ISD::USUBO, VT, Custom);
1067     setOperationAction(ISD::SMULO, VT, Custom);
1068     setOperationAction(ISD::UMULO, VT, Custom);
1069   }
1070
1071   // There are no 8-bit 3-address imul/mul instructions
1072   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1073   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1074
1075   if (!Subtarget->is64Bit()) {
1076     // These libcalls are not available in 32-bit.
1077     setLibcallName(RTLIB::SHL_I128, 0);
1078     setLibcallName(RTLIB::SRL_I128, 0);
1079     setLibcallName(RTLIB::SRA_I128, 0);
1080   }
1081
1082   // We have target-specific dag combine patterns for the following nodes:
1083   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1084   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1085   setTargetDAGCombine(ISD::BUILD_VECTOR);
1086   setTargetDAGCombine(ISD::SELECT);
1087   setTargetDAGCombine(ISD::SHL);
1088   setTargetDAGCombine(ISD::SRA);
1089   setTargetDAGCombine(ISD::SRL);
1090   setTargetDAGCombine(ISD::OR);
1091   setTargetDAGCombine(ISD::AND);
1092   setTargetDAGCombine(ISD::ADD);
1093   setTargetDAGCombine(ISD::SUB);
1094   setTargetDAGCombine(ISD::STORE);
1095   setTargetDAGCombine(ISD::ZERO_EXTEND);
1096   if (Subtarget->is64Bit())
1097     setTargetDAGCombine(ISD::MUL);
1098
1099   computeRegisterProperties();
1100
1101   // On Darwin, -Os means optimize for size without hurting performance,
1102   // do not reduce the limit.
1103   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1104   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1105   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1106   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1108   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1109   setPrefLoopAlignment(16);
1110   benefitFromCodePlacementOpt = true;
1111
1112   setPrefFunctionAlignment(4);
1113 }
1114
1115
1116 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1117   return MVT::i8;
1118 }
1119
1120
1121 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1122 /// the desired ByVal argument alignment.
1123 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1124   if (MaxAlign == 16)
1125     return;
1126   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127     if (VTy->getBitWidth() == 128)
1128       MaxAlign = 16;
1129   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1130     unsigned EltAlign = 0;
1131     getMaxByValAlign(ATy->getElementType(), EltAlign);
1132     if (EltAlign > MaxAlign)
1133       MaxAlign = EltAlign;
1134   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1135     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136       unsigned EltAlign = 0;
1137       getMaxByValAlign(STy->getElementType(i), EltAlign);
1138       if (EltAlign > MaxAlign)
1139         MaxAlign = EltAlign;
1140       if (MaxAlign == 16)
1141         break;
1142     }
1143   }
1144   return;
1145 }
1146
1147 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1148 /// function arguments in the caller parameter area. For X86, aggregates
1149 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1150 /// are at 4-byte boundaries.
1151 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1152   if (Subtarget->is64Bit()) {
1153     // Max of 8 and alignment of type.
1154     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1155     if (TyAlign > 8)
1156       return TyAlign;
1157     return 8;
1158   }
1159
1160   unsigned Align = 4;
1161   if (Subtarget->hasXMM())
1162     getMaxByValAlign(Ty, Align);
1163   return Align;
1164 }
1165
1166 /// getOptimalMemOpType - Returns the target specific optimal type for load
1167 /// and store operations as a result of memset, memcpy, and memmove
1168 /// lowering. If DstAlign is zero that means it's safe to destination
1169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1170 /// means there isn't a need to check it against alignment requirement,
1171 /// probably because the source does not need to be loaded. If
1172 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1173 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1174 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1175 /// constant so it does not need to be loaded.
1176 /// It returns EVT::Other if the type should be determined using generic
1177 /// target-independent logic.
1178 EVT
1179 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1180                                        unsigned DstAlign, unsigned SrcAlign,
1181                                        bool NonScalarIntSafe,
1182                                        bool MemcpyStrSrc,
1183                                        MachineFunction &MF) const {
1184   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1185   // linux.  This is because the stack realignment code can't handle certain
1186   // cases like PR2962.  This should be removed when PR2962 is fixed.
1187   const Function *F = MF.getFunction();
1188   if (NonScalarIntSafe &&
1189       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1190     if (Size >= 16 &&
1191         (Subtarget->isUnalignedMemAccessFast() ||
1192          ((DstAlign == 0 || DstAlign >= 16) &&
1193           (SrcAlign == 0 || SrcAlign >= 16))) &&
1194         Subtarget->getStackAlignment() >= 16) {
1195       if (Subtarget->hasSSE2())
1196         return MVT::v4i32;
1197       if (Subtarget->hasSSE1())
1198         return MVT::v4f32;
1199     } else if (!MemcpyStrSrc && Size >= 8 &&
1200                !Subtarget->is64Bit() &&
1201                Subtarget->getStackAlignment() >= 8 &&
1202                Subtarget->hasXMMInt()) {
1203       // Do not use f64 to lower memcpy if source is string constant. It's
1204       // better to use i32 to avoid the loads.
1205       return MVT::f64;
1206     }
1207   }
1208   if (Subtarget->is64Bit() && Size >= 8)
1209     return MVT::i64;
1210   return MVT::i32;
1211 }
1212
1213 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1214 /// current function.  The returned value is a member of the
1215 /// MachineJumpTableInfo::JTEntryKind enum.
1216 unsigned X86TargetLowering::getJumpTableEncoding() const {
1217   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1218   // symbol.
1219   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1220       Subtarget->isPICStyleGOT())
1221     return MachineJumpTableInfo::EK_Custom32;
1222
1223   // Otherwise, use the normal jump table encoding heuristics.
1224   return TargetLowering::getJumpTableEncoding();
1225 }
1226
1227 const MCExpr *
1228 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1229                                              const MachineBasicBlock *MBB,
1230                                              unsigned uid,MCContext &Ctx) const{
1231   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1232          Subtarget->isPICStyleGOT());
1233   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1234   // entries.
1235   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1236                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1237 }
1238
1239 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1240 /// jumptable.
1241 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1242                                                     SelectionDAG &DAG) const {
1243   if (!Subtarget->is64Bit())
1244     // This doesn't have DebugLoc associated with it, but is not really the
1245     // same as a Register.
1246     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1247   return Table;
1248 }
1249
1250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1252 /// MCExpr.
1253 const MCExpr *X86TargetLowering::
1254 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1255                              MCContext &Ctx) const {
1256   // X86-64 uses RIP relative addressing based on the jump table label.
1257   if (Subtarget->isPICStyleRIPRel())
1258     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1259
1260   // Otherwise, the reference is relative to the PIC base.
1261   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1262 }
1263
1264 // FIXME: Why this routine is here? Move to RegInfo!
1265 std::pair<const TargetRegisterClass*, uint8_t>
1266 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1267   const TargetRegisterClass *RRC = 0;
1268   uint8_t Cost = 1;
1269   switch (VT.getSimpleVT().SimpleTy) {
1270   default:
1271     return TargetLowering::findRepresentativeClass(VT);
1272   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1273     RRC = (Subtarget->is64Bit()
1274            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1275     break;
1276   case MVT::x86mmx:
1277     RRC = X86::VR64RegisterClass;
1278     break;
1279   case MVT::f32: case MVT::f64:
1280   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1281   case MVT::v4f32: case MVT::v2f64:
1282   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1283   case MVT::v4f64:
1284     RRC = X86::VR128RegisterClass;
1285     break;
1286   }
1287   return std::make_pair(RRC, Cost);
1288 }
1289
1290 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1291                                                unsigned &Offset) const {
1292   if (!Subtarget->isTargetLinux())
1293     return false;
1294
1295   if (Subtarget->is64Bit()) {
1296     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1297     Offset = 0x28;
1298     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1299       AddressSpace = 256;
1300     else
1301       AddressSpace = 257;
1302   } else {
1303     // %gs:0x14 on i386
1304     Offset = 0x14;
1305     AddressSpace = 256;
1306   }
1307   return true;
1308 }
1309
1310
1311 //===----------------------------------------------------------------------===//
1312 //               Return Value Calling Convention Implementation
1313 //===----------------------------------------------------------------------===//
1314
1315 #include "X86GenCallingConv.inc"
1316
1317 bool
1318 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1319                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1320                         LLVMContext &Context) const {
1321   SmallVector<CCValAssign, 16> RVLocs;
1322   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1323                  RVLocs, Context);
1324   return CCInfo.CheckReturn(Outs, RetCC_X86);
1325 }
1326
1327 SDValue
1328 X86TargetLowering::LowerReturn(SDValue Chain,
1329                                CallingConv::ID CallConv, bool isVarArg,
1330                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1331                                const SmallVectorImpl<SDValue> &OutVals,
1332                                DebugLoc dl, SelectionDAG &DAG) const {
1333   MachineFunction &MF = DAG.getMachineFunction();
1334   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1335
1336   SmallVector<CCValAssign, 16> RVLocs;
1337   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1338                  RVLocs, *DAG.getContext());
1339   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1340
1341   // Add the regs to the liveout set for the function.
1342   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1343   for (unsigned i = 0; i != RVLocs.size(); ++i)
1344     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1345       MRI.addLiveOut(RVLocs[i].getLocReg());
1346
1347   SDValue Flag;
1348
1349   SmallVector<SDValue, 6> RetOps;
1350   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1351   // Operand #1 = Bytes To Pop
1352   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1353                    MVT::i16));
1354
1355   // Copy the result values into the output registers.
1356   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1357     CCValAssign &VA = RVLocs[i];
1358     assert(VA.isRegLoc() && "Can only return in registers!");
1359     SDValue ValToCopy = OutVals[i];
1360     EVT ValVT = ValToCopy.getValueType();
1361
1362     // If this is x86-64, and we disabled SSE, we can't return FP values,
1363     // or SSE or MMX vectors.
1364     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1365          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1366           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1367       report_fatal_error("SSE register return with SSE disabled");
1368     }
1369     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1370     // llvm-gcc has never done it right and no one has noticed, so this
1371     // should be OK for now.
1372     if (ValVT == MVT::f64 &&
1373         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1374       report_fatal_error("SSE2 register return with SSE2 disabled");
1375
1376     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1377     // the RET instruction and handled by the FP Stackifier.
1378     if (VA.getLocReg() == X86::ST0 ||
1379         VA.getLocReg() == X86::ST1) {
1380       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1381       // change the value to the FP stack register class.
1382       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1383         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1384       RetOps.push_back(ValToCopy);
1385       // Don't emit a copytoreg.
1386       continue;
1387     }
1388
1389     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1390     // which is returned in RAX / RDX.
1391     if (Subtarget->is64Bit()) {
1392       if (ValVT == MVT::x86mmx) {
1393         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1394           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1395           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1396                                   ValToCopy);
1397           // If we don't have SSE2 available, convert to v4f32 so the generated
1398           // register is legal.
1399           if (!Subtarget->hasSSE2())
1400             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1401         }
1402       }
1403     }
1404
1405     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1406     Flag = Chain.getValue(1);
1407   }
1408
1409   // The x86-64 ABI for returning structs by value requires that we copy
1410   // the sret argument into %rax for the return. We saved the argument into
1411   // a virtual register in the entry block, so now we copy the value out
1412   // and into %rax.
1413   if (Subtarget->is64Bit() &&
1414       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1415     MachineFunction &MF = DAG.getMachineFunction();
1416     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1417     unsigned Reg = FuncInfo->getSRetReturnReg();
1418     assert(Reg &&
1419            "SRetReturnReg should have been set in LowerFormalArguments().");
1420     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1421
1422     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1423     Flag = Chain.getValue(1);
1424
1425     // RAX now acts like a return value.
1426     MRI.addLiveOut(X86::RAX);
1427   }
1428
1429   RetOps[0] = Chain;  // Update chain.
1430
1431   // Add the flag if we have it.
1432   if (Flag.getNode())
1433     RetOps.push_back(Flag);
1434
1435   return DAG.getNode(X86ISD::RET_FLAG, dl,
1436                      MVT::Other, &RetOps[0], RetOps.size());
1437 }
1438
1439 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1440   if (N->getNumValues() != 1)
1441     return false;
1442   if (!N->hasNUsesOfValue(1, 0))
1443     return false;
1444
1445   SDNode *Copy = *N->use_begin();
1446   if (Copy->getOpcode() != ISD::CopyToReg &&
1447       Copy->getOpcode() != ISD::FP_EXTEND)
1448     return false;
1449
1450   bool HasRet = false;
1451   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1452        UI != UE; ++UI) {
1453     if (UI->getOpcode() != X86ISD::RET_FLAG)
1454       return false;
1455     HasRet = true;
1456   }
1457
1458   return HasRet;
1459 }
1460
1461 EVT
1462 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1463                                             ISD::NodeType ExtendKind) const {
1464   MVT ReturnMVT;
1465   // TODO: Is this also valid on 32-bit?
1466   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1467     ReturnMVT = MVT::i8;
1468   else
1469     ReturnMVT = MVT::i32;
1470
1471   EVT MinVT = getRegisterType(Context, ReturnMVT);
1472   return VT.bitsLT(MinVT) ? MinVT : VT;
1473 }
1474
1475 /// LowerCallResult - Lower the result values of a call into the
1476 /// appropriate copies out of appropriate physical registers.
1477 ///
1478 SDValue
1479 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1480                                    CallingConv::ID CallConv, bool isVarArg,
1481                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1482                                    DebugLoc dl, SelectionDAG &DAG,
1483                                    SmallVectorImpl<SDValue> &InVals) const {
1484
1485   // Assign locations to each value returned by this call.
1486   SmallVector<CCValAssign, 16> RVLocs;
1487   bool Is64Bit = Subtarget->is64Bit();
1488   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1489                  RVLocs, *DAG.getContext());
1490   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1491
1492   // Copy all of the result registers out of their specified physreg.
1493   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1494     CCValAssign &VA = RVLocs[i];
1495     EVT CopyVT = VA.getValVT();
1496
1497     // If this is x86-64, and we disabled SSE, we can't return FP values
1498     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1499         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1500       report_fatal_error("SSE register return with SSE disabled");
1501     }
1502
1503     SDValue Val;
1504
1505     // If this is a call to a function that returns an fp value on the floating
1506     // point stack, we must guarantee the the value is popped from the stack, so
1507     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1508     // if the return value is not used. We use the FpGET_ST0 instructions
1509     // instead.
1510     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1511       // If we prefer to use the value in xmm registers, copy it out as f80 and
1512       // use a truncate to move it from fp stack reg to xmm reg.
1513       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1514       bool isST0 = VA.getLocReg() == X86::ST0;
1515       unsigned Opc = 0;
1516       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1517       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1518       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1519       SDValue Ops[] = { Chain, InFlag };
1520       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1521                                          Ops, 2), 1);
1522       Val = Chain.getValue(0);
1523
1524       // Round the f80 to the right size, which also moves it to the appropriate
1525       // xmm register.
1526       if (CopyVT != VA.getValVT())
1527         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1528                           // This truncation won't change the value.
1529                           DAG.getIntPtrConstant(1));
1530     } else {
1531       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1532                                  CopyVT, InFlag).getValue(1);
1533       Val = Chain.getValue(0);
1534     }
1535     InFlag = Chain.getValue(2);
1536     InVals.push_back(Val);
1537   }
1538
1539   return Chain;
1540 }
1541
1542
1543 //===----------------------------------------------------------------------===//
1544 //                C & StdCall & Fast Calling Convention implementation
1545 //===----------------------------------------------------------------------===//
1546 //  StdCall calling convention seems to be standard for many Windows' API
1547 //  routines and around. It differs from C calling convention just a little:
1548 //  callee should clean up the stack, not caller. Symbols should be also
1549 //  decorated in some fancy way :) It doesn't support any vector arguments.
1550 //  For info on fast calling convention see Fast Calling Convention (tail call)
1551 //  implementation LowerX86_32FastCCCallTo.
1552
1553 /// CallIsStructReturn - Determines whether a call uses struct return
1554 /// semantics.
1555 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1556   if (Outs.empty())
1557     return false;
1558
1559   return Outs[0].Flags.isSRet();
1560 }
1561
1562 /// ArgsAreStructReturn - Determines whether a function uses struct
1563 /// return semantics.
1564 static bool
1565 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1566   if (Ins.empty())
1567     return false;
1568
1569   return Ins[0].Flags.isSRet();
1570 }
1571
1572 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1573 /// by "Src" to address "Dst" with size and alignment information specified by
1574 /// the specific parameter attribute. The copy will be passed as a byval
1575 /// function parameter.
1576 static SDValue
1577 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1578                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1579                           DebugLoc dl) {
1580   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1581
1582   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1583                        /*isVolatile*/false, /*AlwaysInline=*/true,
1584                        MachinePointerInfo(), MachinePointerInfo());
1585 }
1586
1587 /// IsTailCallConvention - Return true if the calling convention is one that
1588 /// supports tail call optimization.
1589 static bool IsTailCallConvention(CallingConv::ID CC) {
1590   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1591 }
1592
1593 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1594   if (!CI->isTailCall())
1595     return false;
1596
1597   CallSite CS(CI);
1598   CallingConv::ID CalleeCC = CS.getCallingConv();
1599   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1600     return false;
1601
1602   return true;
1603 }
1604
1605 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1606 /// a tailcall target by changing its ABI.
1607 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1608   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1609 }
1610
1611 SDValue
1612 X86TargetLowering::LowerMemArgument(SDValue Chain,
1613                                     CallingConv::ID CallConv,
1614                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1615                                     DebugLoc dl, SelectionDAG &DAG,
1616                                     const CCValAssign &VA,
1617                                     MachineFrameInfo *MFI,
1618                                     unsigned i) const {
1619   // Create the nodes corresponding to a load from this parameter slot.
1620   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1621   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1622   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1623   EVT ValVT;
1624
1625   // If value is passed by pointer we have address passed instead of the value
1626   // itself.
1627   if (VA.getLocInfo() == CCValAssign::Indirect)
1628     ValVT = VA.getLocVT();
1629   else
1630     ValVT = VA.getValVT();
1631
1632   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1633   // changed with more analysis.
1634   // In case of tail call optimization mark all arguments mutable. Since they
1635   // could be overwritten by lowering of arguments in case of a tail call.
1636   if (Flags.isByVal()) {
1637     unsigned Bytes = Flags.getByValSize();
1638     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1639     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1640     return DAG.getFrameIndex(FI, getPointerTy());
1641   } else {
1642     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1643                                     VA.getLocMemOffset(), isImmutable);
1644     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1645     return DAG.getLoad(ValVT, dl, Chain, FIN,
1646                        MachinePointerInfo::getFixedStack(FI),
1647                        false, false, 0);
1648   }
1649 }
1650
1651 SDValue
1652 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1653                                         CallingConv::ID CallConv,
1654                                         bool isVarArg,
1655                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1656                                         DebugLoc dl,
1657                                         SelectionDAG &DAG,
1658                                         SmallVectorImpl<SDValue> &InVals)
1659                                           const {
1660   MachineFunction &MF = DAG.getMachineFunction();
1661   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1662
1663   const Function* Fn = MF.getFunction();
1664   if (Fn->hasExternalLinkage() &&
1665       Subtarget->isTargetCygMing() &&
1666       Fn->getName() == "main")
1667     FuncInfo->setForceFramePointer(true);
1668
1669   MachineFrameInfo *MFI = MF.getFrameInfo();
1670   bool Is64Bit = Subtarget->is64Bit();
1671   bool IsWin64 = Subtarget->isTargetWin64();
1672
1673   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1674          "Var args not supported with calling convention fastcc or ghc");
1675
1676   // Assign locations to all of the incoming arguments.
1677   SmallVector<CCValAssign, 16> ArgLocs;
1678   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1679                  ArgLocs, *DAG.getContext());
1680
1681   // Allocate shadow area for Win64
1682   if (IsWin64) {
1683     CCInfo.AllocateStack(32, 8);
1684   }
1685
1686   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1687
1688   unsigned LastVal = ~0U;
1689   SDValue ArgValue;
1690   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1691     CCValAssign &VA = ArgLocs[i];
1692     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1693     // places.
1694     assert(VA.getValNo() != LastVal &&
1695            "Don't support value assigned to multiple locs yet");
1696     LastVal = VA.getValNo();
1697
1698     if (VA.isRegLoc()) {
1699       EVT RegVT = VA.getLocVT();
1700       TargetRegisterClass *RC = NULL;
1701       if (RegVT == MVT::i32)
1702         RC = X86::GR32RegisterClass;
1703       else if (Is64Bit && RegVT == MVT::i64)
1704         RC = X86::GR64RegisterClass;
1705       else if (RegVT == MVT::f32)
1706         RC = X86::FR32RegisterClass;
1707       else if (RegVT == MVT::f64)
1708         RC = X86::FR64RegisterClass;
1709       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1710         RC = X86::VR256RegisterClass;
1711       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1712         RC = X86::VR128RegisterClass;
1713       else if (RegVT == MVT::x86mmx)
1714         RC = X86::VR64RegisterClass;
1715       else
1716         llvm_unreachable("Unknown argument type!");
1717
1718       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1719       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1720
1721       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1722       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1723       // right size.
1724       if (VA.getLocInfo() == CCValAssign::SExt)
1725         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1726                                DAG.getValueType(VA.getValVT()));
1727       else if (VA.getLocInfo() == CCValAssign::ZExt)
1728         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1729                                DAG.getValueType(VA.getValVT()));
1730       else if (VA.getLocInfo() == CCValAssign::BCvt)
1731         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1732
1733       if (VA.isExtInLoc()) {
1734         // Handle MMX values passed in XMM regs.
1735         if (RegVT.isVector()) {
1736           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1737                                  ArgValue);
1738         } else
1739           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1740       }
1741     } else {
1742       assert(VA.isMemLoc());
1743       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1744     }
1745
1746     // If value is passed via pointer - do a load.
1747     if (VA.getLocInfo() == CCValAssign::Indirect)
1748       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1749                              MachinePointerInfo(), false, false, 0);
1750
1751     InVals.push_back(ArgValue);
1752   }
1753
1754   // The x86-64 ABI for returning structs by value requires that we copy
1755   // the sret argument into %rax for the return. Save the argument into
1756   // a virtual register so that we can access it from the return points.
1757   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1758     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1759     unsigned Reg = FuncInfo->getSRetReturnReg();
1760     if (!Reg) {
1761       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1762       FuncInfo->setSRetReturnReg(Reg);
1763     }
1764     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1765     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1766   }
1767
1768   unsigned StackSize = CCInfo.getNextStackOffset();
1769   // Align stack specially for tail calls.
1770   if (FuncIsMadeTailCallSafe(CallConv))
1771     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1772
1773   // If the function takes variable number of arguments, make a frame index for
1774   // the start of the first vararg value... for expansion of llvm.va_start.
1775   if (isVarArg) {
1776     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1777                     CallConv != CallingConv::X86_ThisCall)) {
1778       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1779     }
1780     if (Is64Bit) {
1781       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1782
1783       // FIXME: We should really autogenerate these arrays
1784       static const unsigned GPR64ArgRegsWin64[] = {
1785         X86::RCX, X86::RDX, X86::R8,  X86::R9
1786       };
1787       static const unsigned GPR64ArgRegs64Bit[] = {
1788         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1789       };
1790       static const unsigned XMMArgRegs64Bit[] = {
1791         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1792         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1793       };
1794       const unsigned *GPR64ArgRegs;
1795       unsigned NumXMMRegs = 0;
1796
1797       if (IsWin64) {
1798         // The XMM registers which might contain var arg parameters are shadowed
1799         // in their paired GPR.  So we only need to save the GPR to their home
1800         // slots.
1801         TotalNumIntRegs = 4;
1802         GPR64ArgRegs = GPR64ArgRegsWin64;
1803       } else {
1804         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1805         GPR64ArgRegs = GPR64ArgRegs64Bit;
1806
1807         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1808       }
1809       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1810                                                        TotalNumIntRegs);
1811
1812       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1813       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1814              "SSE register cannot be used when SSE is disabled!");
1815       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1816              "SSE register cannot be used when SSE is disabled!");
1817       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1818         // Kernel mode asks for SSE to be disabled, so don't push them
1819         // on the stack.
1820         TotalNumXMMRegs = 0;
1821
1822       if (IsWin64) {
1823         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1824         // Get to the caller-allocated home save location.  Add 8 to account
1825         // for the return address.
1826         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1827         FuncInfo->setRegSaveFrameIndex(
1828           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1829         // Fixup to set vararg frame on shadow area (4 x i64).
1830         if (NumIntRegs < 4)
1831           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1832       } else {
1833         // For X86-64, if there are vararg parameters that are passed via
1834         // registers, then we must store them to their spots on the stack so they
1835         // may be loaded by deferencing the result of va_next.
1836         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1837         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1838         FuncInfo->setRegSaveFrameIndex(
1839           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1840                                false));
1841       }
1842
1843       // Store the integer parameter registers.
1844       SmallVector<SDValue, 8> MemOps;
1845       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1846                                         getPointerTy());
1847       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1848       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1849         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1850                                   DAG.getIntPtrConstant(Offset));
1851         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1852                                      X86::GR64RegisterClass);
1853         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1854         SDValue Store =
1855           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1856                        MachinePointerInfo::getFixedStack(
1857                          FuncInfo->getRegSaveFrameIndex(), Offset),
1858                        false, false, 0);
1859         MemOps.push_back(Store);
1860         Offset += 8;
1861       }
1862
1863       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1864         // Now store the XMM (fp + vector) parameter registers.
1865         SmallVector<SDValue, 11> SaveXMMOps;
1866         SaveXMMOps.push_back(Chain);
1867
1868         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1869         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1870         SaveXMMOps.push_back(ALVal);
1871
1872         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1873                                FuncInfo->getRegSaveFrameIndex()));
1874         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1875                                FuncInfo->getVarArgsFPOffset()));
1876
1877         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1878           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1879                                        X86::VR128RegisterClass);
1880           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1881           SaveXMMOps.push_back(Val);
1882         }
1883         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1884                                      MVT::Other,
1885                                      &SaveXMMOps[0], SaveXMMOps.size()));
1886       }
1887
1888       if (!MemOps.empty())
1889         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1890                             &MemOps[0], MemOps.size());
1891     }
1892   }
1893
1894   // Some CCs need callee pop.
1895   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1896     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1897   } else {
1898     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1899     // If this is an sret function, the return should pop the hidden pointer.
1900     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1901       FuncInfo->setBytesToPopOnReturn(4);
1902   }
1903
1904   if (!Is64Bit) {
1905     // RegSaveFrameIndex is X86-64 only.
1906     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1907     if (CallConv == CallingConv::X86_FastCall ||
1908         CallConv == CallingConv::X86_ThisCall)
1909       // fastcc functions can't have varargs.
1910       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1911   }
1912
1913   return Chain;
1914 }
1915
1916 SDValue
1917 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1918                                     SDValue StackPtr, SDValue Arg,
1919                                     DebugLoc dl, SelectionDAG &DAG,
1920                                     const CCValAssign &VA,
1921                                     ISD::ArgFlagsTy Flags) const {
1922   unsigned LocMemOffset = VA.getLocMemOffset();
1923   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1924   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1925   if (Flags.isByVal())
1926     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1927
1928   return DAG.getStore(Chain, dl, Arg, PtrOff,
1929                       MachinePointerInfo::getStack(LocMemOffset),
1930                       false, false, 0);
1931 }
1932
1933 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1934 /// optimization is performed and it is required.
1935 SDValue
1936 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1937                                            SDValue &OutRetAddr, SDValue Chain,
1938                                            bool IsTailCall, bool Is64Bit,
1939                                            int FPDiff, DebugLoc dl) const {
1940   // Adjust the Return address stack slot.
1941   EVT VT = getPointerTy();
1942   OutRetAddr = getReturnAddressFrameIndex(DAG);
1943
1944   // Load the "old" Return address.
1945   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1946                            false, false, 0);
1947   return SDValue(OutRetAddr.getNode(), 1);
1948 }
1949
1950 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1951 /// optimization is performed and it is required (FPDiff!=0).
1952 static SDValue
1953 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1954                          SDValue Chain, SDValue RetAddrFrIdx,
1955                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1956   // Store the return address to the appropriate stack slot.
1957   if (!FPDiff) return Chain;
1958   // Calculate the new stack slot for the return address.
1959   int SlotSize = Is64Bit ? 8 : 4;
1960   int NewReturnAddrFI =
1961     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1962   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1963   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1964   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1965                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1966                        false, false, 0);
1967   return Chain;
1968 }
1969
1970 SDValue
1971 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1972                              CallingConv::ID CallConv, bool isVarArg,
1973                              bool &isTailCall,
1974                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1975                              const SmallVectorImpl<SDValue> &OutVals,
1976                              const SmallVectorImpl<ISD::InputArg> &Ins,
1977                              DebugLoc dl, SelectionDAG &DAG,
1978                              SmallVectorImpl<SDValue> &InVals) const {
1979   MachineFunction &MF = DAG.getMachineFunction();
1980   bool Is64Bit        = Subtarget->is64Bit();
1981   bool IsWin64        = Subtarget->isTargetWin64();
1982   bool IsStructRet    = CallIsStructReturn(Outs);
1983   bool IsSibcall      = false;
1984
1985   if (isTailCall) {
1986     // Check if it's really possible to do a tail call.
1987     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1988                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1989                                                    Outs, OutVals, Ins, DAG);
1990
1991     // Sibcalls are automatically detected tailcalls which do not require
1992     // ABI changes.
1993     if (!GuaranteedTailCallOpt && isTailCall)
1994       IsSibcall = true;
1995
1996     if (isTailCall)
1997       ++NumTailCalls;
1998   }
1999
2000   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2001          "Var args not supported with calling convention fastcc or ghc");
2002
2003   // Analyze operands of the call, assigning locations to each operand.
2004   SmallVector<CCValAssign, 16> ArgLocs;
2005   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2006                  ArgLocs, *DAG.getContext());
2007
2008   // Allocate shadow area for Win64
2009   if (IsWin64) {
2010     CCInfo.AllocateStack(32, 8);
2011   }
2012
2013   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2014
2015   // Get a count of how many bytes are to be pushed on the stack.
2016   unsigned NumBytes = CCInfo.getNextStackOffset();
2017   if (IsSibcall)
2018     // This is a sibcall. The memory operands are available in caller's
2019     // own caller's stack.
2020     NumBytes = 0;
2021   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2022     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2023
2024   int FPDiff = 0;
2025   if (isTailCall && !IsSibcall) {
2026     // Lower arguments at fp - stackoffset + fpdiff.
2027     unsigned NumBytesCallerPushed =
2028       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2029     FPDiff = NumBytesCallerPushed - NumBytes;
2030
2031     // Set the delta of movement of the returnaddr stackslot.
2032     // But only set if delta is greater than previous delta.
2033     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2034       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2035   }
2036
2037   if (!IsSibcall)
2038     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2039
2040   SDValue RetAddrFrIdx;
2041   // Load return address for tail calls.
2042   if (isTailCall && FPDiff)
2043     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2044                                     Is64Bit, FPDiff, dl);
2045
2046   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2047   SmallVector<SDValue, 8> MemOpChains;
2048   SDValue StackPtr;
2049
2050   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2051   // of tail call optimization arguments are handle later.
2052   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2053     CCValAssign &VA = ArgLocs[i];
2054     EVT RegVT = VA.getLocVT();
2055     SDValue Arg = OutVals[i];
2056     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2057     bool isByVal = Flags.isByVal();
2058
2059     // Promote the value if needed.
2060     switch (VA.getLocInfo()) {
2061     default: llvm_unreachable("Unknown loc info!");
2062     case CCValAssign::Full: break;
2063     case CCValAssign::SExt:
2064       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2065       break;
2066     case CCValAssign::ZExt:
2067       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2068       break;
2069     case CCValAssign::AExt:
2070       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2071         // Special case: passing MMX values in XMM registers.
2072         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2073         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2074         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2075       } else
2076         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2077       break;
2078     case CCValAssign::BCvt:
2079       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2080       break;
2081     case CCValAssign::Indirect: {
2082       // Store the argument.
2083       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2084       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2085       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2086                            MachinePointerInfo::getFixedStack(FI),
2087                            false, false, 0);
2088       Arg = SpillSlot;
2089       break;
2090     }
2091     }
2092
2093     if (VA.isRegLoc()) {
2094       if (isByVal) {
2095         if (CCInfo.isFirstByValRegValid()) {
2096           EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2097           unsigned reg = CCInfo.getFirstByValReg();
2098           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, Arg,
2099                                      MachinePointerInfo(),
2100                                      false, false, 0);
2101           MemOpChains.push_back(Load.getValue(1));
2102           RegsToPass.push_back(std::make_pair(reg, Load));
2103           if (Flags.getByValSize() > 8) {
2104             SDValue Const8 = DAG.getConstant(8, MVT::i32);
2105             SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const8);
2106             SDValue Load2 = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2107                                        MachinePointerInfo(),
2108                                        false, false, 0);
2109             MemOpChains.push_back(Load.getValue(1));
2110             RegsToPass.push_back(std::make_pair(reg+1, Load));
2111           }
2112           CCInfo.clearFirstByValReg();
2113         }
2114       } else {
2115         // Usual case:
2116         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2117         if (isVarArg && IsWin64) {
2118           // Win64 ABI requires argument XMM reg to be copied to the corresponding
2119           // shadow reg if callee is a varargs function.
2120           unsigned ShadowReg = 0;
2121           switch (VA.getLocReg()) {
2122           case X86::XMM0: ShadowReg = X86::RCX; break;
2123           case X86::XMM1: ShadowReg = X86::RDX; break;
2124           case X86::XMM2: ShadowReg = X86::R8; break;
2125           case X86::XMM3: ShadowReg = X86::R9; break;
2126           }
2127           if (ShadowReg)
2128             RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2129         }
2130       }
2131     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2132       if (isByVal) {    // In memory.
2133         // ??
2134       }
2135       assert(VA.isMemLoc());
2136       if (StackPtr.getNode() == 0)
2137         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2138       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2139                                              dl, DAG, VA, Flags));
2140     }
2141   }     // end for (all register/memloc assignments)
2142
2143   if (!MemOpChains.empty())
2144     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2145                         &MemOpChains[0], MemOpChains.size());
2146
2147   // Build a sequence of copy-to-reg nodes chained together with token chain
2148   // and flag operands which copy the outgoing args into registers.
2149   SDValue InFlag;
2150   // Tail call byval lowering might overwrite argument registers so in case of
2151   // tail call optimization the copies to registers are lowered later.
2152   if (!isTailCall)
2153     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2154       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2155                                RegsToPass[i].second, InFlag);
2156       InFlag = Chain.getValue(1);
2157     }
2158
2159   if (Subtarget->isPICStyleGOT()) {
2160     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2161     // GOT pointer.
2162     if (!isTailCall) {
2163       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2164                                DAG.getNode(X86ISD::GlobalBaseReg,
2165                                            DebugLoc(), getPointerTy()),
2166                                InFlag);
2167       InFlag = Chain.getValue(1);
2168     } else {
2169       // If we are tail calling and generating PIC/GOT style code load the
2170       // address of the callee into ECX. The value in ecx is used as target of
2171       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2172       // for tail calls on PIC/GOT architectures. Normally we would just put the
2173       // address of GOT into ebx and then call target@PLT. But for tail calls
2174       // ebx would be restored (since ebx is callee saved) before jumping to the
2175       // target@PLT.
2176
2177       // Note: The actual moving to ECX is done further down.
2178       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2179       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2180           !G->getGlobal()->hasProtectedVisibility())
2181         Callee = LowerGlobalAddress(Callee, DAG);
2182       else if (isa<ExternalSymbolSDNode>(Callee))
2183         Callee = LowerExternalSymbol(Callee, DAG);
2184     }
2185   }
2186
2187   if (Is64Bit && isVarArg && !IsWin64) {
2188     // From AMD64 ABI document:
2189     // For calls that may call functions that use varargs or stdargs
2190     // (prototype-less calls or calls to functions containing ellipsis (...) in
2191     // the declaration) %al is used as hidden argument to specify the number
2192     // of SSE registers used. The contents of %al do not need to match exactly
2193     // the number of registers, but must be an ubound on the number of SSE
2194     // registers used and is in the range 0 - 8 inclusive.
2195
2196     // Count the number of XMM registers allocated.
2197     static const unsigned XMMArgRegs[] = {
2198       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2199       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2200     };
2201     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2202     assert((Subtarget->hasXMM() || !NumXMMRegs)
2203            && "SSE registers cannot be used when SSE is disabled");
2204
2205     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2206                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2207     InFlag = Chain.getValue(1);
2208   }
2209
2210
2211   // For tail calls lower the arguments to the 'real' stack slot.
2212   if (isTailCall) {
2213     // Force all the incoming stack arguments to be loaded from the stack
2214     // before any new outgoing arguments are stored to the stack, because the
2215     // outgoing stack slots may alias the incoming argument stack slots, and
2216     // the alias isn't otherwise explicit. This is slightly more conservative
2217     // than necessary, because it means that each store effectively depends
2218     // on every argument instead of just those arguments it would clobber.
2219     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2220
2221     SmallVector<SDValue, 8> MemOpChains2;
2222     SDValue FIN;
2223     int FI = 0;
2224     // Do not flag preceding copytoreg stuff together with the following stuff.
2225     InFlag = SDValue();
2226     if (GuaranteedTailCallOpt) {
2227       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2228         CCValAssign &VA = ArgLocs[i];
2229         if (VA.isRegLoc())
2230           continue;
2231         assert(VA.isMemLoc());
2232         SDValue Arg = OutVals[i];
2233         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2234         // Create frame index.
2235         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2236         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2237         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2238         FIN = DAG.getFrameIndex(FI, getPointerTy());
2239
2240         if (Flags.isByVal()) {
2241           // Copy relative to framepointer.
2242           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2243           if (StackPtr.getNode() == 0)
2244             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2245                                           getPointerTy());
2246           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2247
2248           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2249                                                            ArgChain,
2250                                                            Flags, DAG, dl));
2251         } else {
2252           // Store relative to framepointer.
2253           MemOpChains2.push_back(
2254             DAG.getStore(ArgChain, dl, Arg, FIN,
2255                          MachinePointerInfo::getFixedStack(FI),
2256                          false, false, 0));
2257         }
2258       }
2259     }
2260
2261     if (!MemOpChains2.empty())
2262       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2263                           &MemOpChains2[0], MemOpChains2.size());
2264
2265     // Copy arguments to their registers.
2266     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2267       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2268                                RegsToPass[i].second, InFlag);
2269       InFlag = Chain.getValue(1);
2270     }
2271     InFlag =SDValue();
2272
2273     // Store the return address to the appropriate stack slot.
2274     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2275                                      FPDiff, dl);
2276   }
2277
2278   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2279     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2280     // In the 64-bit large code model, we have to make all calls
2281     // through a register, since the call instruction's 32-bit
2282     // pc-relative offset may not be large enough to hold the whole
2283     // address.
2284   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2285     // If the callee is a GlobalAddress node (quite common, every direct call
2286     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2287     // it.
2288
2289     // We should use extra load for direct calls to dllimported functions in
2290     // non-JIT mode.
2291     const GlobalValue *GV = G->getGlobal();
2292     if (!GV->hasDLLImportLinkage()) {
2293       unsigned char OpFlags = 0;
2294
2295       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2296       // external symbols most go through the PLT in PIC mode.  If the symbol
2297       // has hidden or protected visibility, or if it is static or local, then
2298       // we don't need to use the PLT - we can directly call it.
2299       if (Subtarget->isTargetELF() &&
2300           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2301           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2302         OpFlags = X86II::MO_PLT;
2303       } else if (Subtarget->isPICStyleStubAny() &&
2304                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2305                  (!Subtarget->getTargetTriple().isMacOSX() ||
2306                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2307         // PC-relative references to external symbols should go through $stub,
2308         // unless we're building with the leopard linker or later, which
2309         // automatically synthesizes these stubs.
2310         OpFlags = X86II::MO_DARWIN_STUB;
2311       }
2312
2313       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2314                                           G->getOffset(), OpFlags);
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 /// HandleByVal - Every parameter *after* a byval parameter is passed
2468 /// on the stack.  Remember the next parameter register to allocate,
2469 /// and then confiscate the rest of the parameter registers to insure
2470 /// this.
2471 void
2472 llvm::X86TargetLowering::HandleByVal(CCState *State, unsigned &size) const {
2473   if (!Subtarget->is64Bit())
2474     return;
2475
2476   if (size == 0 || size > 16)
2477     return;
2478
2479   int RegsRequired = (size > 8) ? 2 : 1;
2480
2481   static const unsigned GPR64ArgRegs64Bit[] = {
2482     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2483   };
2484   unsigned NextRegToAlloc = State->getFirstUnallocated(GPR64ArgRegs64Bit, 6);
2485
2486   // If insufficient registers available
2487   if (NextRegToAlloc + RegsRequired > 6)
2488     return;
2489
2490   size = 0;     // Tell caller not to allocate stack.
2491
2492   unsigned reg = State->AllocateReg(GPR64ArgRegs64Bit, 6);
2493   State->setFirstByValReg(reg);
2494   
2495   if (RegsRequired == 2) {
2496     State->AllocateReg(GPR64ArgRegs64Bit, 6);
2497   }
2498 }
2499
2500 /// MatchingStackOffset - Return true if the given stack call argument is
2501 /// already available in the same position (relatively) of the caller's
2502 /// incoming argument stack.
2503 static
2504 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2505                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2506                          const X86InstrInfo *TII) {
2507   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2508   int FI = INT_MAX;
2509   if (Arg.getOpcode() == ISD::CopyFromReg) {
2510     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2511     if (!TargetRegisterInfo::isVirtualRegister(VR))
2512       return false;
2513     MachineInstr *Def = MRI->getVRegDef(VR);
2514     if (!Def)
2515       return false;
2516     if (!Flags.isByVal()) {
2517       if (!TII->isLoadFromStackSlot(Def, FI))
2518         return false;
2519     } else {
2520       unsigned Opcode = Def->getOpcode();
2521       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2522           Def->getOperand(1).isFI()) {
2523         FI = Def->getOperand(1).getIndex();
2524         Bytes = Flags.getByValSize();
2525       } else
2526         return false;
2527     }
2528   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2529     if (Flags.isByVal())
2530       // ByVal argument is passed in as a pointer but it's now being
2531       // dereferenced. e.g.
2532       // define @foo(%struct.X* %A) {
2533       //   tail call @bar(%struct.X* byval %A)
2534       // }
2535       return false;
2536     SDValue Ptr = Ld->getBasePtr();
2537     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2538     if (!FINode)
2539       return false;
2540     FI = FINode->getIndex();
2541   } else
2542     return false;
2543
2544   assert(FI != INT_MAX);
2545   if (!MFI->isFixedObjectIndex(FI))
2546     return false;
2547   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2548 }
2549
2550 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2551 /// for tail call optimization. Targets which want to do tail call
2552 /// optimization should implement this function.
2553 bool
2554 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2555                                                      CallingConv::ID CalleeCC,
2556                                                      bool isVarArg,
2557                                                      bool isCalleeStructRet,
2558                                                      bool isCallerStructRet,
2559                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2560                                     const SmallVectorImpl<SDValue> &OutVals,
2561                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2562                                                      SelectionDAG& DAG) const {
2563   if (!IsTailCallConvention(CalleeCC) &&
2564       CalleeCC != CallingConv::C)
2565     return false;
2566
2567   // If -tailcallopt is specified, make fastcc functions tail-callable.
2568   const MachineFunction &MF = DAG.getMachineFunction();
2569   const Function *CallerF = DAG.getMachineFunction().getFunction();
2570   CallingConv::ID CallerCC = CallerF->getCallingConv();
2571   bool CCMatch = CallerCC == CalleeCC;
2572
2573   if (GuaranteedTailCallOpt) {
2574     if (IsTailCallConvention(CalleeCC) && CCMatch)
2575       return true;
2576     return false;
2577   }
2578
2579   // Look for obvious safe cases to perform tail call optimization that do not
2580   // require ABI changes. This is what gcc calls sibcall.
2581
2582   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2583   // emit a special epilogue.
2584   if (RegInfo->needsStackRealignment(MF))
2585     return false;
2586
2587   // Also avoid sibcall optimization if either caller or callee uses struct
2588   // return semantics.
2589   if (isCalleeStructRet || isCallerStructRet)
2590     return false;
2591
2592   // Do not sibcall optimize vararg calls unless all arguments are passed via
2593   // registers.
2594   if (isVarArg && !Outs.empty()) {
2595
2596     // Optimizing for varargs on Win64 is unlikely to be safe without
2597     // additional testing.
2598     if (Subtarget->isTargetWin64())
2599       return false;
2600
2601     SmallVector<CCValAssign, 16> ArgLocs;
2602     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2603                    ArgLocs, *DAG.getContext());
2604
2605     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2606     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2607       if (!ArgLocs[i].isRegLoc())
2608         return false;
2609   }
2610
2611   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2612   // Therefore if it's not used by the call it is not safe to optimize this into
2613   // a sibcall.
2614   bool Unused = false;
2615   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2616     if (!Ins[i].Used) {
2617       Unused = true;
2618       break;
2619     }
2620   }
2621   if (Unused) {
2622     SmallVector<CCValAssign, 16> RVLocs;
2623     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2624                    RVLocs, *DAG.getContext());
2625     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2626     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2627       CCValAssign &VA = RVLocs[i];
2628       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2629         return false;
2630     }
2631   }
2632
2633   // If the calling conventions do not match, then we'd better make sure the
2634   // results are returned in the same way as what the caller expects.
2635   if (!CCMatch) {
2636     SmallVector<CCValAssign, 16> RVLocs1;
2637     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2638                     RVLocs1, *DAG.getContext());
2639     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2640
2641     SmallVector<CCValAssign, 16> RVLocs2;
2642     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2643                     RVLocs2, *DAG.getContext());
2644     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2645
2646     if (RVLocs1.size() != RVLocs2.size())
2647       return false;
2648     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2649       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2650         return false;
2651       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2652         return false;
2653       if (RVLocs1[i].isRegLoc()) {
2654         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2655           return false;
2656       } else {
2657         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2658           return false;
2659       }
2660     }
2661   }
2662
2663   // If the callee takes no arguments then go on to check the results of the
2664   // call.
2665   if (!Outs.empty()) {
2666     // Check if stack adjustment is needed. For now, do not do this if any
2667     // argument is passed on the stack.
2668     SmallVector<CCValAssign, 16> ArgLocs;
2669     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2670                    ArgLocs, *DAG.getContext());
2671
2672     // Allocate shadow area for Win64
2673     if (Subtarget->isTargetWin64()) {
2674       CCInfo.AllocateStack(32, 8);
2675     }
2676
2677     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2678     if (CCInfo.getNextStackOffset()) {
2679       MachineFunction &MF = DAG.getMachineFunction();
2680       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2681         return false;
2682
2683       // Check if the arguments are already laid out in the right way as
2684       // the caller's fixed stack objects.
2685       MachineFrameInfo *MFI = MF.getFrameInfo();
2686       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2687       const X86InstrInfo *TII =
2688         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2689       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2690         CCValAssign &VA = ArgLocs[i];
2691         SDValue Arg = OutVals[i];
2692         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2693         if (VA.getLocInfo() == CCValAssign::Indirect)
2694           return false;
2695         if (!VA.isRegLoc()) {
2696           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2697                                    MFI, MRI, TII))
2698             return false;
2699         }
2700       }
2701     }
2702
2703     // If the tailcall address may be in a register, then make sure it's
2704     // possible to register allocate for it. In 32-bit, the call address can
2705     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2706     // callee-saved registers are restored. These happen to be the same
2707     // registers used to pass 'inreg' arguments so watch out for those.
2708     if (!Subtarget->is64Bit() &&
2709         !isa<GlobalAddressSDNode>(Callee) &&
2710         !isa<ExternalSymbolSDNode>(Callee)) {
2711       unsigned NumInRegs = 0;
2712       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2713         CCValAssign &VA = ArgLocs[i];
2714         if (!VA.isRegLoc())
2715           continue;
2716         unsigned Reg = VA.getLocReg();
2717         switch (Reg) {
2718         default: break;
2719         case X86::EAX: case X86::EDX: case X86::ECX:
2720           if (++NumInRegs == 3)
2721             return false;
2722           break;
2723         }
2724       }
2725     }
2726   }
2727
2728   // An stdcall caller is expected to clean up its arguments; the callee
2729   // isn't going to do that.
2730   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2731     return false;
2732
2733   return true;
2734 }
2735
2736 FastISel *
2737 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2738   return X86::createFastISel(funcInfo);
2739 }
2740
2741
2742 //===----------------------------------------------------------------------===//
2743 //                           Other Lowering Hooks
2744 //===----------------------------------------------------------------------===//
2745
2746 static bool MayFoldLoad(SDValue Op) {
2747   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2748 }
2749
2750 static bool MayFoldIntoStore(SDValue Op) {
2751   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2752 }
2753
2754 static bool isTargetShuffle(unsigned Opcode) {
2755   switch(Opcode) {
2756   default: return false;
2757   case X86ISD::PSHUFD:
2758   case X86ISD::PSHUFHW:
2759   case X86ISD::PSHUFLW:
2760   case X86ISD::SHUFPD:
2761   case X86ISD::PALIGN:
2762   case X86ISD::SHUFPS:
2763   case X86ISD::MOVLHPS:
2764   case X86ISD::MOVLHPD:
2765   case X86ISD::MOVHLPS:
2766   case X86ISD::MOVLPS:
2767   case X86ISD::MOVLPD:
2768   case X86ISD::MOVSHDUP:
2769   case X86ISD::MOVSLDUP:
2770   case X86ISD::MOVDDUP:
2771   case X86ISD::MOVSS:
2772   case X86ISD::MOVSD:
2773   case X86ISD::UNPCKLPS:
2774   case X86ISD::UNPCKLPD:
2775   case X86ISD::VUNPCKLPS:
2776   case X86ISD::VUNPCKLPD:
2777   case X86ISD::VUNPCKLPSY:
2778   case X86ISD::VUNPCKLPDY:
2779   case X86ISD::PUNPCKLWD:
2780   case X86ISD::PUNPCKLBW:
2781   case X86ISD::PUNPCKLDQ:
2782   case X86ISD::PUNPCKLQDQ:
2783   case X86ISD::UNPCKHPS:
2784   case X86ISD::UNPCKHPD:
2785   case X86ISD::PUNPCKHWD:
2786   case X86ISD::PUNPCKHBW:
2787   case X86ISD::PUNPCKHDQ:
2788   case X86ISD::PUNPCKHQDQ:
2789     return true;
2790   }
2791   return false;
2792 }
2793
2794 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2795                                                SDValue V1, SelectionDAG &DAG) {
2796   switch(Opc) {
2797   default: llvm_unreachable("Unknown x86 shuffle node");
2798   case X86ISD::MOVSHDUP:
2799   case X86ISD::MOVSLDUP:
2800   case X86ISD::MOVDDUP:
2801     return DAG.getNode(Opc, dl, VT, V1);
2802   }
2803
2804   return SDValue();
2805 }
2806
2807 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2808                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2809   switch(Opc) {
2810   default: llvm_unreachable("Unknown x86 shuffle node");
2811   case X86ISD::PSHUFD:
2812   case X86ISD::PSHUFHW:
2813   case X86ISD::PSHUFLW:
2814     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2815   }
2816
2817   return SDValue();
2818 }
2819
2820 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2821                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2822   switch(Opc) {
2823   default: llvm_unreachable("Unknown x86 shuffle node");
2824   case X86ISD::PALIGN:
2825   case X86ISD::SHUFPD:
2826   case X86ISD::SHUFPS:
2827     return DAG.getNode(Opc, dl, VT, V1, V2,
2828                        DAG.getConstant(TargetMask, MVT::i8));
2829   }
2830   return SDValue();
2831 }
2832
2833 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2834                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2835   switch(Opc) {
2836   default: llvm_unreachable("Unknown x86 shuffle node");
2837   case X86ISD::MOVLHPS:
2838   case X86ISD::MOVLHPD:
2839   case X86ISD::MOVHLPS:
2840   case X86ISD::MOVLPS:
2841   case X86ISD::MOVLPD:
2842   case X86ISD::MOVSS:
2843   case X86ISD::MOVSD:
2844   case X86ISD::UNPCKLPS:
2845   case X86ISD::UNPCKLPD:
2846   case X86ISD::VUNPCKLPS:
2847   case X86ISD::VUNPCKLPD:
2848   case X86ISD::VUNPCKLPSY:
2849   case X86ISD::VUNPCKLPDY:
2850   case X86ISD::PUNPCKLWD:
2851   case X86ISD::PUNPCKLBW:
2852   case X86ISD::PUNPCKLDQ:
2853   case X86ISD::PUNPCKLQDQ:
2854   case X86ISD::UNPCKHPS:
2855   case X86ISD::UNPCKHPD:
2856   case X86ISD::PUNPCKHWD:
2857   case X86ISD::PUNPCKHBW:
2858   case X86ISD::PUNPCKHDQ:
2859   case X86ISD::PUNPCKHQDQ:
2860     return DAG.getNode(Opc, dl, VT, V1, V2);
2861   }
2862   return SDValue();
2863 }
2864
2865 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2868   int ReturnAddrIndex = FuncInfo->getRAIndex();
2869
2870   if (ReturnAddrIndex == 0) {
2871     // Set up a frame object for the return address.
2872     uint64_t SlotSize = TD->getPointerSize();
2873     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2874                                                            false);
2875     FuncInfo->setRAIndex(ReturnAddrIndex);
2876   }
2877
2878   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2879 }
2880
2881
2882 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2883                                        bool hasSymbolicDisplacement) {
2884   // Offset should fit into 32 bit immediate field.
2885   if (!isInt<32>(Offset))
2886     return false;
2887
2888   // If we don't have a symbolic displacement - we don't have any extra
2889   // restrictions.
2890   if (!hasSymbolicDisplacement)
2891     return true;
2892
2893   // FIXME: Some tweaks might be needed for medium code model.
2894   if (M != CodeModel::Small && M != CodeModel::Kernel)
2895     return false;
2896
2897   // For small code model we assume that latest object is 16MB before end of 31
2898   // bits boundary. We may also accept pretty large negative constants knowing
2899   // that all objects are in the positive half of address space.
2900   if (M == CodeModel::Small && Offset < 16*1024*1024)
2901     return true;
2902
2903   // For kernel code model we know that all object resist in the negative half
2904   // of 32bits address space. We may not accept negative offsets, since they may
2905   // be just off and we may accept pretty large positive ones.
2906   if (M == CodeModel::Kernel && Offset > 0)
2907     return true;
2908
2909   return false;
2910 }
2911
2912 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2913 /// specific condition code, returning the condition code and the LHS/RHS of the
2914 /// comparison to make.
2915 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2916                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2917   if (!isFP) {
2918     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2919       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2920         // X > -1   -> X == 0, jump !sign.
2921         RHS = DAG.getConstant(0, RHS.getValueType());
2922         return X86::COND_NS;
2923       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2924         // X < 0   -> X == 0, jump on sign.
2925         return X86::COND_S;
2926       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2927         // X < 1   -> X <= 0
2928         RHS = DAG.getConstant(0, RHS.getValueType());
2929         return X86::COND_LE;
2930       }
2931     }
2932
2933     switch (SetCCOpcode) {
2934     default: llvm_unreachable("Invalid integer condition!");
2935     case ISD::SETEQ:  return X86::COND_E;
2936     case ISD::SETGT:  return X86::COND_G;
2937     case ISD::SETGE:  return X86::COND_GE;
2938     case ISD::SETLT:  return X86::COND_L;
2939     case ISD::SETLE:  return X86::COND_LE;
2940     case ISD::SETNE:  return X86::COND_NE;
2941     case ISD::SETULT: return X86::COND_B;
2942     case ISD::SETUGT: return X86::COND_A;
2943     case ISD::SETULE: return X86::COND_BE;
2944     case ISD::SETUGE: return X86::COND_AE;
2945     }
2946   }
2947
2948   // First determine if it is required or is profitable to flip the operands.
2949
2950   // If LHS is a foldable load, but RHS is not, flip the condition.
2951   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2952       !ISD::isNON_EXTLoad(RHS.getNode())) {
2953     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2954     std::swap(LHS, RHS);
2955   }
2956
2957   switch (SetCCOpcode) {
2958   default: break;
2959   case ISD::SETOLT:
2960   case ISD::SETOLE:
2961   case ISD::SETUGT:
2962   case ISD::SETUGE:
2963     std::swap(LHS, RHS);
2964     break;
2965   }
2966
2967   // On a floating point condition, the flags are set as follows:
2968   // ZF  PF  CF   op
2969   //  0 | 0 | 0 | X > Y
2970   //  0 | 0 | 1 | X < Y
2971   //  1 | 0 | 0 | X == Y
2972   //  1 | 1 | 1 | unordered
2973   switch (SetCCOpcode) {
2974   default: llvm_unreachable("Condcode should be pre-legalized away");
2975   case ISD::SETUEQ:
2976   case ISD::SETEQ:   return X86::COND_E;
2977   case ISD::SETOLT:              // flipped
2978   case ISD::SETOGT:
2979   case ISD::SETGT:   return X86::COND_A;
2980   case ISD::SETOLE:              // flipped
2981   case ISD::SETOGE:
2982   case ISD::SETGE:   return X86::COND_AE;
2983   case ISD::SETUGT:              // flipped
2984   case ISD::SETULT:
2985   case ISD::SETLT:   return X86::COND_B;
2986   case ISD::SETUGE:              // flipped
2987   case ISD::SETULE:
2988   case ISD::SETLE:   return X86::COND_BE;
2989   case ISD::SETONE:
2990   case ISD::SETNE:   return X86::COND_NE;
2991   case ISD::SETUO:   return X86::COND_P;
2992   case ISD::SETO:    return X86::COND_NP;
2993   case ISD::SETOEQ:
2994   case ISD::SETUNE:  return X86::COND_INVALID;
2995   }
2996 }
2997
2998 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2999 /// code. Current x86 isa includes the following FP cmov instructions:
3000 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3001 static bool hasFPCMov(unsigned X86CC) {
3002   switch (X86CC) {
3003   default:
3004     return false;
3005   case X86::COND_B:
3006   case X86::COND_BE:
3007   case X86::COND_E:
3008   case X86::COND_P:
3009   case X86::COND_A:
3010   case X86::COND_AE:
3011   case X86::COND_NE:
3012   case X86::COND_NP:
3013     return true;
3014   }
3015 }
3016
3017 /// isFPImmLegal - Returns true if the target can instruction select the
3018 /// specified FP immediate natively. If false, the legalizer will
3019 /// materialize the FP immediate as a load from a constant pool.
3020 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3021   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3022     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3023       return true;
3024   }
3025   return false;
3026 }
3027
3028 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3029 /// the specified range (L, H].
3030 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3031   return (Val < 0) || (Val >= Low && Val < Hi);
3032 }
3033
3034 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3035 /// specified value.
3036 static bool isUndefOrEqual(int Val, int CmpVal) {
3037   if (Val < 0 || Val == CmpVal)
3038     return true;
3039   return false;
3040 }
3041
3042 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3043 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3044 /// the second operand.
3045 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3046   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3047     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3048   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3049     return (Mask[0] < 2 && Mask[1] < 2);
3050   return false;
3051 }
3052
3053 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3054   SmallVector<int, 8> M;
3055   N->getMask(M);
3056   return ::isPSHUFDMask(M, N->getValueType(0));
3057 }
3058
3059 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3060 /// is suitable for input to PSHUFHW.
3061 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3062   if (VT != MVT::v8i16)
3063     return false;
3064
3065   // Lower quadword copied in order or undef.
3066   for (int i = 0; i != 4; ++i)
3067     if (Mask[i] >= 0 && Mask[i] != i)
3068       return false;
3069
3070   // Upper quadword shuffled.
3071   for (int i = 4; i != 8; ++i)
3072     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3073       return false;
3074
3075   return true;
3076 }
3077
3078 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3079   SmallVector<int, 8> M;
3080   N->getMask(M);
3081   return ::isPSHUFHWMask(M, N->getValueType(0));
3082 }
3083
3084 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3085 /// is suitable for input to PSHUFLW.
3086 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3087   if (VT != MVT::v8i16)
3088     return false;
3089
3090   // Upper quadword copied in order.
3091   for (int i = 4; i != 8; ++i)
3092     if (Mask[i] >= 0 && Mask[i] != i)
3093       return false;
3094
3095   // Lower quadword shuffled.
3096   for (int i = 0; i != 4; ++i)
3097     if (Mask[i] >= 4)
3098       return false;
3099
3100   return true;
3101 }
3102
3103 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3104   SmallVector<int, 8> M;
3105   N->getMask(M);
3106   return ::isPSHUFLWMask(M, N->getValueType(0));
3107 }
3108
3109 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3110 /// is suitable for input to PALIGNR.
3111 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3112                           bool hasSSSE3) {
3113   int i, e = VT.getVectorNumElements();
3114
3115   // Do not handle v2i64 / v2f64 shuffles with palignr.
3116   if (e < 4 || !hasSSSE3)
3117     return false;
3118
3119   for (i = 0; i != e; ++i)
3120     if (Mask[i] >= 0)
3121       break;
3122
3123   // All undef, not a palignr.
3124   if (i == e)
3125     return false;
3126
3127   // Determine if it's ok to perform a palignr with only the LHS, since we
3128   // don't have access to the actual shuffle elements to see if RHS is undef.
3129   bool Unary = Mask[i] < (int)e;
3130   bool NeedsUnary = false;
3131
3132   int s = Mask[i] - i;
3133
3134   // Check the rest of the elements to see if they are consecutive.
3135   for (++i; i != e; ++i) {
3136     int m = Mask[i];
3137     if (m < 0)
3138       continue;
3139
3140     Unary = Unary && (m < (int)e);
3141     NeedsUnary = NeedsUnary || (m < s);
3142
3143     if (NeedsUnary && !Unary)
3144       return false;
3145     if (Unary && m != ((s+i) & (e-1)))
3146       return false;
3147     if (!Unary && m != (s+i))
3148       return false;
3149   }
3150   return true;
3151 }
3152
3153 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3154   SmallVector<int, 8> M;
3155   N->getMask(M);
3156   return ::isPALIGNRMask(M, N->getValueType(0), true);
3157 }
3158
3159 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3160 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3161 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3162   int NumElems = VT.getVectorNumElements();
3163   if (NumElems != 2 && NumElems != 4)
3164     return false;
3165
3166   int Half = NumElems / 2;
3167   for (int i = 0; i < Half; ++i)
3168     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3169       return false;
3170   for (int i = Half; i < NumElems; ++i)
3171     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3172       return false;
3173
3174   return true;
3175 }
3176
3177 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3178   SmallVector<int, 8> M;
3179   N->getMask(M);
3180   return ::isSHUFPMask(M, N->getValueType(0));
3181 }
3182
3183 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3184 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3185 /// half elements to come from vector 1 (which would equal the dest.) and
3186 /// the upper half to come from vector 2.
3187 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3188   int NumElems = VT.getVectorNumElements();
3189
3190   if (NumElems != 2 && NumElems != 4)
3191     return false;
3192
3193   int Half = NumElems / 2;
3194   for (int i = 0; i < Half; ++i)
3195     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3196       return false;
3197   for (int i = Half; i < NumElems; ++i)
3198     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3199       return false;
3200   return true;
3201 }
3202
3203 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3204   SmallVector<int, 8> M;
3205   N->getMask(M);
3206   return isCommutedSHUFPMask(M, N->getValueType(0));
3207 }
3208
3209 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3210 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3211 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3212   if (N->getValueType(0).getVectorNumElements() != 4)
3213     return false;
3214
3215   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3216   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3217          isUndefOrEqual(N->getMaskElt(1), 7) &&
3218          isUndefOrEqual(N->getMaskElt(2), 2) &&
3219          isUndefOrEqual(N->getMaskElt(3), 3);
3220 }
3221
3222 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3223 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3224 /// <2, 3, 2, 3>
3225 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3226   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3227
3228   if (NumElems != 4)
3229     return false;
3230
3231   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3232   isUndefOrEqual(N->getMaskElt(1), 3) &&
3233   isUndefOrEqual(N->getMaskElt(2), 2) &&
3234   isUndefOrEqual(N->getMaskElt(3), 3);
3235 }
3236
3237 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3238 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3239 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3240   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3241
3242   if (NumElems != 2 && NumElems != 4)
3243     return false;
3244
3245   for (unsigned i = 0; i < NumElems/2; ++i)
3246     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3247       return false;
3248
3249   for (unsigned i = NumElems/2; i < NumElems; ++i)
3250     if (!isUndefOrEqual(N->getMaskElt(i), i))
3251       return false;
3252
3253   return true;
3254 }
3255
3256 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3257 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3258 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3259   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3260
3261   if ((NumElems != 2 && NumElems != 4)
3262       || N->getValueType(0).getSizeInBits() > 128)
3263     return false;
3264
3265   for (unsigned i = 0; i < NumElems/2; ++i)
3266     if (!isUndefOrEqual(N->getMaskElt(i), i))
3267       return false;
3268
3269   for (unsigned i = 0; i < NumElems/2; ++i)
3270     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3271       return false;
3272
3273   return true;
3274 }
3275
3276 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3277 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3278 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3279                          bool V2IsSplat = false) {
3280   int NumElts = VT.getVectorNumElements();
3281   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3282     return false;
3283
3284   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3285   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3286   // sections.
3287   unsigned NumSections = VT.getSizeInBits() / 128;
3288   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3289   unsigned NumSectionElts = NumElts / NumSections;
3290
3291   unsigned Start = 0;
3292   unsigned End = NumSectionElts;
3293   for (unsigned s = 0; s < NumSections; ++s) {
3294     for (unsigned i = Start, j = s * NumSectionElts;
3295          i != End;
3296          i += 2, ++j) {
3297       int BitI  = Mask[i];
3298       int BitI1 = Mask[i+1];
3299       if (!isUndefOrEqual(BitI, j))
3300         return false;
3301       if (V2IsSplat) {
3302         if (!isUndefOrEqual(BitI1, NumElts))
3303           return false;
3304       } else {
3305         if (!isUndefOrEqual(BitI1, j + NumElts))
3306           return false;
3307       }
3308     }
3309     // Process the next 128 bits.
3310     Start += NumSectionElts;
3311     End += NumSectionElts;
3312   }
3313
3314   return true;
3315 }
3316
3317 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3318   SmallVector<int, 8> M;
3319   N->getMask(M);
3320   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3321 }
3322
3323 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3324 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3325 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3326                          bool V2IsSplat = false) {
3327   int NumElts = VT.getVectorNumElements();
3328   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3329     return false;
3330
3331   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3332     int BitI  = Mask[i];
3333     int BitI1 = Mask[i+1];
3334     if (!isUndefOrEqual(BitI, j + NumElts/2))
3335       return false;
3336     if (V2IsSplat) {
3337       if (isUndefOrEqual(BitI1, NumElts))
3338         return false;
3339     } else {
3340       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3341         return false;
3342     }
3343   }
3344   return true;
3345 }
3346
3347 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3348   SmallVector<int, 8> M;
3349   N->getMask(M);
3350   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3351 }
3352
3353 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3354 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3355 /// <0, 0, 1, 1>
3356 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3357   int NumElems = VT.getVectorNumElements();
3358   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3359     return false;
3360
3361   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3362   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3363   // sections.
3364   unsigned NumSections = VT.getSizeInBits() / 128;
3365   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3366   unsigned NumSectionElts = NumElems / NumSections;
3367
3368   for (unsigned s = 0; s < NumSections; ++s) {
3369     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3370          i != NumSectionElts * (s + 1);
3371          i += 2, ++j) {
3372       int BitI  = Mask[i];
3373       int BitI1 = Mask[i+1];
3374
3375       if (!isUndefOrEqual(BitI, j))
3376         return false;
3377       if (!isUndefOrEqual(BitI1, j))
3378         return false;
3379     }
3380   }
3381
3382   return true;
3383 }
3384
3385 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3386   SmallVector<int, 8> M;
3387   N->getMask(M);
3388   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3389 }
3390
3391 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3392 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3393 /// <2, 2, 3, 3>
3394 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3395   int NumElems = VT.getVectorNumElements();
3396   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3397     return false;
3398
3399   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3400     int BitI  = Mask[i];
3401     int BitI1 = Mask[i+1];
3402     if (!isUndefOrEqual(BitI, j))
3403       return false;
3404     if (!isUndefOrEqual(BitI1, j))
3405       return false;
3406   }
3407   return true;
3408 }
3409
3410 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3411   SmallVector<int, 8> M;
3412   N->getMask(M);
3413   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3414 }
3415
3416 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3417 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3418 /// MOVSD, and MOVD, i.e. setting the lowest element.
3419 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3420   if (VT.getVectorElementType().getSizeInBits() < 32)
3421     return false;
3422
3423   int NumElts = VT.getVectorNumElements();
3424
3425   if (!isUndefOrEqual(Mask[0], NumElts))
3426     return false;
3427
3428   for (int i = 1; i < NumElts; ++i)
3429     if (!isUndefOrEqual(Mask[i], i))
3430       return false;
3431
3432   return true;
3433 }
3434
3435 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3436   SmallVector<int, 8> M;
3437   N->getMask(M);
3438   return ::isMOVLMask(M, N->getValueType(0));
3439 }
3440
3441 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3442 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3443 /// element of vector 2 and the other elements to come from vector 1 in order.
3444 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3445                                bool V2IsSplat = false, bool V2IsUndef = false) {
3446   int NumOps = VT.getVectorNumElements();
3447   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3448     return false;
3449
3450   if (!isUndefOrEqual(Mask[0], 0))
3451     return false;
3452
3453   for (int i = 1; i < NumOps; ++i)
3454     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3455           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3456           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3457       return false;
3458
3459   return true;
3460 }
3461
3462 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3463                            bool V2IsUndef = false) {
3464   SmallVector<int, 8> M;
3465   N->getMask(M);
3466   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3467 }
3468
3469 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3470 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3471 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3472   if (N->getValueType(0).getVectorNumElements() != 4)
3473     return false;
3474
3475   // Expect 1, 1, 3, 3
3476   for (unsigned i = 0; i < 2; ++i) {
3477     int Elt = N->getMaskElt(i);
3478     if (Elt >= 0 && Elt != 1)
3479       return false;
3480   }
3481
3482   bool HasHi = false;
3483   for (unsigned i = 2; i < 4; ++i) {
3484     int Elt = N->getMaskElt(i);
3485     if (Elt >= 0 && Elt != 3)
3486       return false;
3487     if (Elt == 3)
3488       HasHi = true;
3489   }
3490   // Don't use movshdup if it can be done with a shufps.
3491   // FIXME: verify that matching u, u, 3, 3 is what we want.
3492   return HasHi;
3493 }
3494
3495 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3497 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3498   if (N->getValueType(0).getVectorNumElements() != 4)
3499     return false;
3500
3501   // Expect 0, 0, 2, 2
3502   for (unsigned i = 0; i < 2; ++i)
3503     if (N->getMaskElt(i) > 0)
3504       return false;
3505
3506   bool HasHi = false;
3507   for (unsigned i = 2; i < 4; ++i) {
3508     int Elt = N->getMaskElt(i);
3509     if (Elt >= 0 && Elt != 2)
3510       return false;
3511     if (Elt == 2)
3512       HasHi = true;
3513   }
3514   // Don't use movsldup if it can be done with a shufps.
3515   return HasHi;
3516 }
3517
3518 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3519 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3520 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3521   int e = N->getValueType(0).getVectorNumElements() / 2;
3522
3523   for (int i = 0; i < e; ++i)
3524     if (!isUndefOrEqual(N->getMaskElt(i), i))
3525       return false;
3526   for (int i = 0; i < e; ++i)
3527     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3528       return false;
3529   return true;
3530 }
3531
3532 /// isVEXTRACTF128Index - Return true if the specified
3533 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3534 /// suitable for input to VEXTRACTF128.
3535 bool X86::isVEXTRACTF128Index(SDNode *N) {
3536   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3537     return false;
3538
3539   // The index should be aligned on a 128-bit boundary.
3540   uint64_t Index =
3541     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3542
3543   unsigned VL = N->getValueType(0).getVectorNumElements();
3544   unsigned VBits = N->getValueType(0).getSizeInBits();
3545   unsigned ElSize = VBits / VL;
3546   bool Result = (Index * ElSize) % 128 == 0;
3547
3548   return Result;
3549 }
3550
3551 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3552 /// operand specifies a subvector insert that is suitable for input to
3553 /// VINSERTF128.
3554 bool X86::isVINSERTF128Index(SDNode *N) {
3555   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3556     return false;
3557
3558   // The index should be aligned on a 128-bit boundary.
3559   uint64_t Index =
3560     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3561
3562   unsigned VL = N->getValueType(0).getVectorNumElements();
3563   unsigned VBits = N->getValueType(0).getSizeInBits();
3564   unsigned ElSize = VBits / VL;
3565   bool Result = (Index * ElSize) % 128 == 0;
3566
3567   return Result;
3568 }
3569
3570 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3571 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3572 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3573   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3574   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3575
3576   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3577   unsigned Mask = 0;
3578   for (int i = 0; i < NumOperands; ++i) {
3579     int Val = SVOp->getMaskElt(NumOperands-i-1);
3580     if (Val < 0) Val = 0;
3581     if (Val >= NumOperands) Val -= NumOperands;
3582     Mask |= Val;
3583     if (i != NumOperands - 1)
3584       Mask <<= Shift;
3585   }
3586   return Mask;
3587 }
3588
3589 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3590 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3591 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3593   unsigned Mask = 0;
3594   // 8 nodes, but we only care about the last 4.
3595   for (unsigned i = 7; i >= 4; --i) {
3596     int Val = SVOp->getMaskElt(i);
3597     if (Val >= 0)
3598       Mask |= (Val - 4);
3599     if (i != 4)
3600       Mask <<= 2;
3601   }
3602   return Mask;
3603 }
3604
3605 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3606 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3607 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3609   unsigned Mask = 0;
3610   // 8 nodes, but we only care about the first 4.
3611   for (int i = 3; i >= 0; --i) {
3612     int Val = SVOp->getMaskElt(i);
3613     if (Val >= 0)
3614       Mask |= Val;
3615     if (i != 0)
3616       Mask <<= 2;
3617   }
3618   return Mask;
3619 }
3620
3621 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3622 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3623 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3624   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3625   EVT VVT = N->getValueType(0);
3626   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3627   int Val = 0;
3628
3629   unsigned i, e;
3630   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3631     Val = SVOp->getMaskElt(i);
3632     if (Val >= 0)
3633       break;
3634   }
3635   return (Val - i) * EltSize;
3636 }
3637
3638 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3639 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3640 /// instructions.
3641 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3642   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3643     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3644
3645   uint64_t Index =
3646     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3647
3648   EVT VecVT = N->getOperand(0).getValueType();
3649   EVT ElVT = VecVT.getVectorElementType();
3650
3651   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3652
3653   return Index / NumElemsPerChunk;
3654 }
3655
3656 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3657 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3658 /// instructions.
3659 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3660   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3661     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3662
3663   uint64_t Index =
3664     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3665
3666   EVT VecVT = N->getValueType(0);
3667   EVT ElVT = VecVT.getVectorElementType();
3668
3669   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3670
3671   return Index / NumElemsPerChunk;
3672 }
3673
3674 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3675 /// constant +0.0.
3676 bool X86::isZeroNode(SDValue Elt) {
3677   return ((isa<ConstantSDNode>(Elt) &&
3678            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3679           (isa<ConstantFPSDNode>(Elt) &&
3680            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3681 }
3682
3683 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3684 /// their permute mask.
3685 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3686                                     SelectionDAG &DAG) {
3687   EVT VT = SVOp->getValueType(0);
3688   unsigned NumElems = VT.getVectorNumElements();
3689   SmallVector<int, 8> MaskVec;
3690
3691   for (unsigned i = 0; i != NumElems; ++i) {
3692     int idx = SVOp->getMaskElt(i);
3693     if (idx < 0)
3694       MaskVec.push_back(idx);
3695     else if (idx < (int)NumElems)
3696       MaskVec.push_back(idx + NumElems);
3697     else
3698       MaskVec.push_back(idx - NumElems);
3699   }
3700   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3701                               SVOp->getOperand(0), &MaskVec[0]);
3702 }
3703
3704 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3705 /// the two vector operands have swapped position.
3706 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3707   unsigned NumElems = VT.getVectorNumElements();
3708   for (unsigned i = 0; i != NumElems; ++i) {
3709     int idx = Mask[i];
3710     if (idx < 0)
3711       continue;
3712     else if (idx < (int)NumElems)
3713       Mask[i] = idx + NumElems;
3714     else
3715       Mask[i] = idx - NumElems;
3716   }
3717 }
3718
3719 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3720 /// match movhlps. The lower half elements should come from upper half of
3721 /// V1 (and in order), and the upper half elements should come from the upper
3722 /// half of V2 (and in order).
3723 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3724   if (Op->getValueType(0).getVectorNumElements() != 4)
3725     return false;
3726   for (unsigned i = 0, e = 2; i != e; ++i)
3727     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3728       return false;
3729   for (unsigned i = 2; i != 4; ++i)
3730     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3731       return false;
3732   return true;
3733 }
3734
3735 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3736 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3737 /// required.
3738 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3739   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3740     return false;
3741   N = N->getOperand(0).getNode();
3742   if (!ISD::isNON_EXTLoad(N))
3743     return false;
3744   if (LD)
3745     *LD = cast<LoadSDNode>(N);
3746   return true;
3747 }
3748
3749 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3750 /// match movlp{s|d}. The lower half elements should come from lower half of
3751 /// V1 (and in order), and the upper half elements should come from the upper
3752 /// half of V2 (and in order). And since V1 will become the source of the
3753 /// MOVLP, it must be either a vector load or a scalar load to vector.
3754 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3755                                ShuffleVectorSDNode *Op) {
3756   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3757     return false;
3758   // Is V2 is a vector load, don't do this transformation. We will try to use
3759   // load folding shufps op.
3760   if (ISD::isNON_EXTLoad(V2))
3761     return false;
3762
3763   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3764
3765   if (NumElems != 2 && NumElems != 4)
3766     return false;
3767   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3768     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3769       return false;
3770   for (unsigned i = NumElems/2; i != NumElems; ++i)
3771     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3772       return false;
3773   return true;
3774 }
3775
3776 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3777 /// all the same.
3778 static bool isSplatVector(SDNode *N) {
3779   if (N->getOpcode() != ISD::BUILD_VECTOR)
3780     return false;
3781
3782   SDValue SplatValue = N->getOperand(0);
3783   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3784     if (N->getOperand(i) != SplatValue)
3785       return false;
3786   return true;
3787 }
3788
3789 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3790 /// to an zero vector.
3791 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3792 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3793   SDValue V1 = N->getOperand(0);
3794   SDValue V2 = N->getOperand(1);
3795   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3796   for (unsigned i = 0; i != NumElems; ++i) {
3797     int Idx = N->getMaskElt(i);
3798     if (Idx >= (int)NumElems) {
3799       unsigned Opc = V2.getOpcode();
3800       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3801         continue;
3802       if (Opc != ISD::BUILD_VECTOR ||
3803           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3804         return false;
3805     } else if (Idx >= 0) {
3806       unsigned Opc = V1.getOpcode();
3807       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3808         continue;
3809       if (Opc != ISD::BUILD_VECTOR ||
3810           !X86::isZeroNode(V1.getOperand(Idx)))
3811         return false;
3812     }
3813   }
3814   return true;
3815 }
3816
3817 /// getZeroVector - Returns a vector of specified type with all zero elements.
3818 ///
3819 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3820                              DebugLoc dl) {
3821   assert(VT.isVector() && "Expected a vector type");
3822
3823   // Always build SSE zero vectors as <4 x i32> bitcasted
3824   // to their dest type. This ensures they get CSE'd.
3825   SDValue Vec;
3826   if (VT.getSizeInBits() == 128) {  // SSE
3827     if (HasSSE2) {  // SSE2
3828       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3829       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3830     } else { // SSE1
3831       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3832       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3833     }
3834   } else if (VT.getSizeInBits() == 256) { // AVX
3835     // 256-bit logic and arithmetic instructions in AVX are
3836     // all floating-point, no support for integer ops. Default
3837     // to emitting fp zeroed vectors then.
3838     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3839     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3840     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3841   }
3842   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3843 }
3844
3845 /// getOnesVector - Returns a vector of specified type with all bits set.
3846 ///
3847 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3848   assert(VT.isVector() && "Expected a vector type");
3849
3850   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3851   // type.  This ensures they get CSE'd.
3852   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3853   SDValue Vec;
3854   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3855   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3856 }
3857
3858
3859 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3860 /// that point to V2 points to its first element.
3861 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3862   EVT VT = SVOp->getValueType(0);
3863   unsigned NumElems = VT.getVectorNumElements();
3864
3865   bool Changed = false;
3866   SmallVector<int, 8> MaskVec;
3867   SVOp->getMask(MaskVec);
3868
3869   for (unsigned i = 0; i != NumElems; ++i) {
3870     if (MaskVec[i] > (int)NumElems) {
3871       MaskVec[i] = NumElems;
3872       Changed = true;
3873     }
3874   }
3875   if (Changed)
3876     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3877                                 SVOp->getOperand(1), &MaskVec[0]);
3878   return SDValue(SVOp, 0);
3879 }
3880
3881 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3882 /// operation of specified width.
3883 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3884                        SDValue V2) {
3885   unsigned NumElems = VT.getVectorNumElements();
3886   SmallVector<int, 8> Mask;
3887   Mask.push_back(NumElems);
3888   for (unsigned i = 1; i != NumElems; ++i)
3889     Mask.push_back(i);
3890   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3891 }
3892
3893 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3894 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3895                           SDValue V2) {
3896   unsigned NumElems = VT.getVectorNumElements();
3897   SmallVector<int, 8> Mask;
3898   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3899     Mask.push_back(i);
3900     Mask.push_back(i + NumElems);
3901   }
3902   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3903 }
3904
3905 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3906 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3907                           SDValue V2) {
3908   unsigned NumElems = VT.getVectorNumElements();
3909   unsigned Half = NumElems/2;
3910   SmallVector<int, 8> Mask;
3911   for (unsigned i = 0; i != Half; ++i) {
3912     Mask.push_back(i + Half);
3913     Mask.push_back(i + NumElems + Half);
3914   }
3915   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3916 }
3917
3918 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3919 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3920   EVT PVT = MVT::v4f32;
3921   EVT VT = SV->getValueType(0);
3922   DebugLoc dl = SV->getDebugLoc();
3923   SDValue V1 = SV->getOperand(0);
3924   int NumElems = VT.getVectorNumElements();
3925   int EltNo = SV->getSplatIndex();
3926
3927   // unpack elements to the correct location
3928   while (NumElems > 4) {
3929     if (EltNo < NumElems/2) {
3930       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3931     } else {
3932       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3933       EltNo -= NumElems/2;
3934     }
3935     NumElems >>= 1;
3936   }
3937
3938   // Perform the splat.
3939   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3940   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3941   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3942   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3943 }
3944
3945 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3946 /// vector of zero or undef vector.  This produces a shuffle where the low
3947 /// element of V2 is swizzled into the zero/undef vector, landing at element
3948 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3949 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3950                                              bool isZero, bool HasSSE2,
3951                                              SelectionDAG &DAG) {
3952   EVT VT = V2.getValueType();
3953   SDValue V1 = isZero
3954     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3955   unsigned NumElems = VT.getVectorNumElements();
3956   SmallVector<int, 16> MaskVec;
3957   for (unsigned i = 0; i != NumElems; ++i)
3958     // If this is the insertion idx, put the low elt of V2 here.
3959     MaskVec.push_back(i == Idx ? NumElems : i);
3960   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3961 }
3962
3963 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3964 /// element of the result of the vector shuffle.
3965 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3966                                    unsigned Depth) {
3967   if (Depth == 6)
3968     return SDValue();  // Limit search depth.
3969
3970   SDValue V = SDValue(N, 0);
3971   EVT VT = V.getValueType();
3972   unsigned Opcode = V.getOpcode();
3973
3974   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3975   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3976     Index = SV->getMaskElt(Index);
3977
3978     if (Index < 0)
3979       return DAG.getUNDEF(VT.getVectorElementType());
3980
3981     int NumElems = VT.getVectorNumElements();
3982     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3983     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3984   }
3985
3986   // Recurse into target specific vector shuffles to find scalars.
3987   if (isTargetShuffle(Opcode)) {
3988     int NumElems = VT.getVectorNumElements();
3989     SmallVector<unsigned, 16> ShuffleMask;
3990     SDValue ImmN;
3991
3992     switch(Opcode) {
3993     case X86ISD::SHUFPS:
3994     case X86ISD::SHUFPD:
3995       ImmN = N->getOperand(N->getNumOperands()-1);
3996       DecodeSHUFPSMask(NumElems,
3997                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3998                        ShuffleMask);
3999       break;
4000     case X86ISD::PUNPCKHBW:
4001     case X86ISD::PUNPCKHWD:
4002     case X86ISD::PUNPCKHDQ:
4003     case X86ISD::PUNPCKHQDQ:
4004       DecodePUNPCKHMask(NumElems, ShuffleMask);
4005       break;
4006     case X86ISD::UNPCKHPS:
4007     case X86ISD::UNPCKHPD:
4008       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4009       break;
4010     case X86ISD::PUNPCKLBW:
4011     case X86ISD::PUNPCKLWD:
4012     case X86ISD::PUNPCKLDQ:
4013     case X86ISD::PUNPCKLQDQ:
4014       DecodePUNPCKLMask(VT, ShuffleMask);
4015       break;
4016     case X86ISD::UNPCKLPS:
4017     case X86ISD::UNPCKLPD:
4018     case X86ISD::VUNPCKLPS:
4019     case X86ISD::VUNPCKLPD:
4020     case X86ISD::VUNPCKLPSY:
4021     case X86ISD::VUNPCKLPDY:
4022       DecodeUNPCKLPMask(VT, ShuffleMask);
4023       break;
4024     case X86ISD::MOVHLPS:
4025       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4026       break;
4027     case X86ISD::MOVLHPS:
4028       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4029       break;
4030     case X86ISD::PSHUFD:
4031       ImmN = N->getOperand(N->getNumOperands()-1);
4032       DecodePSHUFMask(NumElems,
4033                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4034                       ShuffleMask);
4035       break;
4036     case X86ISD::PSHUFHW:
4037       ImmN = N->getOperand(N->getNumOperands()-1);
4038       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4039                         ShuffleMask);
4040       break;
4041     case X86ISD::PSHUFLW:
4042       ImmN = N->getOperand(N->getNumOperands()-1);
4043       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4044                         ShuffleMask);
4045       break;
4046     case X86ISD::MOVSS:
4047     case X86ISD::MOVSD: {
4048       // The index 0 always comes from the first element of the second source,
4049       // this is why MOVSS and MOVSD are used in the first place. The other
4050       // elements come from the other positions of the first source vector.
4051       unsigned OpNum = (Index == 0) ? 1 : 0;
4052       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4053                                  Depth+1);
4054     }
4055     default:
4056       assert("not implemented for target shuffle node");
4057       return SDValue();
4058     }
4059
4060     Index = ShuffleMask[Index];
4061     if (Index < 0)
4062       return DAG.getUNDEF(VT.getVectorElementType());
4063
4064     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4065     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4066                                Depth+1);
4067   }
4068
4069   // Actual nodes that may contain scalar elements
4070   if (Opcode == ISD::BITCAST) {
4071     V = V.getOperand(0);
4072     EVT SrcVT = V.getValueType();
4073     unsigned NumElems = VT.getVectorNumElements();
4074
4075     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4076       return SDValue();
4077   }
4078
4079   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4080     return (Index == 0) ? V.getOperand(0)
4081                           : DAG.getUNDEF(VT.getVectorElementType());
4082
4083   if (V.getOpcode() == ISD::BUILD_VECTOR)
4084     return V.getOperand(Index);
4085
4086   return SDValue();
4087 }
4088
4089 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4090 /// shuffle operation which come from a consecutively from a zero. The
4091 /// search can start in two different directions, from left or right.
4092 static
4093 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4094                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4095   int i = 0;
4096
4097   while (i < NumElems) {
4098     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4099     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4100     if (!(Elt.getNode() &&
4101          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4102       break;
4103     ++i;
4104   }
4105
4106   return i;
4107 }
4108
4109 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4110 /// MaskE correspond consecutively to elements from one of the vector operands,
4111 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4112 static
4113 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4114                               int OpIdx, int NumElems, unsigned &OpNum) {
4115   bool SeenV1 = false;
4116   bool SeenV2 = false;
4117
4118   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4119     int Idx = SVOp->getMaskElt(i);
4120     // Ignore undef indicies
4121     if (Idx < 0)
4122       continue;
4123
4124     if (Idx < NumElems)
4125       SeenV1 = true;
4126     else
4127       SeenV2 = true;
4128
4129     // Only accept consecutive elements from the same vector
4130     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4131       return false;
4132   }
4133
4134   OpNum = SeenV1 ? 0 : 1;
4135   return true;
4136 }
4137
4138 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4139 /// logical left shift of a vector.
4140 static bool isVectorShiftRight(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               false /* check zeros from right */, 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   //               V1 = {X, A, B, C}     0
4154   //                         \  \  \    /
4155   //   vector_shuffle V1, V2 <1, 2, 3, X>
4156   //
4157   if (!isShuffleMaskConsecutive(SVOp,
4158             0,                   // Mask Start Index
4159             NumElems-NumZeros-1, // Mask End Index
4160             NumZeros,            // 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 = false;
4166   ShAmt = NumZeros;
4167   ShVal = SVOp->getOperand(OpSrc);
4168   return true;
4169 }
4170
4171 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4172 /// logical left shift of a vector.
4173 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4174                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4175   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4176   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4177               true /* check zeros from left */, DAG);
4178   unsigned OpSrc;
4179
4180   if (!NumZeros)
4181     return false;
4182
4183   // Considering the elements in the mask that are not consecutive zeros,
4184   // check if they consecutively come from only one of the source vectors.
4185   //
4186   //                           0    { A, B, X, X } = V2
4187   //                          / \    /  /
4188   //   vector_shuffle V1, V2 <X, X, 4, 5>
4189   //
4190   if (!isShuffleMaskConsecutive(SVOp,
4191             NumZeros,     // Mask Start Index
4192             NumElems-1,   // Mask End Index
4193             0,            // Where to start looking in the src vector
4194             NumElems,     // Number of elements in vector
4195             OpSrc))       // Which source operand ?
4196     return false;
4197
4198   isLeft = true;
4199   ShAmt = NumZeros;
4200   ShVal = SVOp->getOperand(OpSrc);
4201   return true;
4202 }
4203
4204 /// isVectorShift - Returns true if the shuffle can be implemented as a
4205 /// logical left or right shift of a vector.
4206 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4207                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4208   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4209       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4210     return true;
4211
4212   return false;
4213 }
4214
4215 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4216 ///
4217 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4218                                        unsigned NumNonZero, unsigned NumZero,
4219                                        SelectionDAG &DAG,
4220                                        const TargetLowering &TLI) {
4221   if (NumNonZero > 8)
4222     return SDValue();
4223
4224   DebugLoc dl = Op.getDebugLoc();
4225   SDValue V(0, 0);
4226   bool First = true;
4227   for (unsigned i = 0; i < 16; ++i) {
4228     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4229     if (ThisIsNonZero && First) {
4230       if (NumZero)
4231         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4232       else
4233         V = DAG.getUNDEF(MVT::v8i16);
4234       First = false;
4235     }
4236
4237     if ((i & 1) != 0) {
4238       SDValue ThisElt(0, 0), LastElt(0, 0);
4239       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4240       if (LastIsNonZero) {
4241         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4242                               MVT::i16, Op.getOperand(i-1));
4243       }
4244       if (ThisIsNonZero) {
4245         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4246         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4247                               ThisElt, DAG.getConstant(8, MVT::i8));
4248         if (LastIsNonZero)
4249           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4250       } else
4251         ThisElt = LastElt;
4252
4253       if (ThisElt.getNode())
4254         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4255                         DAG.getIntPtrConstant(i/2));
4256     }
4257   }
4258
4259   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4260 }
4261
4262 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4263 ///
4264 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4265                                      unsigned NumNonZero, unsigned NumZero,
4266                                      SelectionDAG &DAG,
4267                                      const TargetLowering &TLI) {
4268   if (NumNonZero > 4)
4269     return SDValue();
4270
4271   DebugLoc dl = Op.getDebugLoc();
4272   SDValue V(0, 0);
4273   bool First = true;
4274   for (unsigned i = 0; i < 8; ++i) {
4275     bool isNonZero = (NonZeros & (1 << i)) != 0;
4276     if (isNonZero) {
4277       if (First) {
4278         if (NumZero)
4279           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4280         else
4281           V = DAG.getUNDEF(MVT::v8i16);
4282         First = false;
4283       }
4284       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4285                       MVT::v8i16, V, Op.getOperand(i),
4286                       DAG.getIntPtrConstant(i));
4287     }
4288   }
4289
4290   return V;
4291 }
4292
4293 /// getVShift - Return a vector logical shift node.
4294 ///
4295 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4296                          unsigned NumBits, SelectionDAG &DAG,
4297                          const TargetLowering &TLI, DebugLoc dl) {
4298   EVT ShVT = MVT::v2i64;
4299   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4300   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4301   return DAG.getNode(ISD::BITCAST, dl, VT,
4302                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4303                              DAG.getConstant(NumBits,
4304                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4305 }
4306
4307 SDValue
4308 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4309                                           SelectionDAG &DAG) const {
4310
4311   // Check if the scalar load can be widened into a vector load. And if
4312   // the address is "base + cst" see if the cst can be "absorbed" into
4313   // the shuffle mask.
4314   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4315     SDValue Ptr = LD->getBasePtr();
4316     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4317       return SDValue();
4318     EVT PVT = LD->getValueType(0);
4319     if (PVT != MVT::i32 && PVT != MVT::f32)
4320       return SDValue();
4321
4322     int FI = -1;
4323     int64_t Offset = 0;
4324     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4325       FI = FINode->getIndex();
4326       Offset = 0;
4327     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4328                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4329       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4330       Offset = Ptr.getConstantOperandVal(1);
4331       Ptr = Ptr.getOperand(0);
4332     } else {
4333       return SDValue();
4334     }
4335
4336     SDValue Chain = LD->getChain();
4337     // Make sure the stack object alignment is at least 16.
4338     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4339     if (DAG.InferPtrAlignment(Ptr) < 16) {
4340       if (MFI->isFixedObjectIndex(FI)) {
4341         // Can't change the alignment. FIXME: It's possible to compute
4342         // the exact stack offset and reference FI + adjust offset instead.
4343         // If someone *really* cares about this. That's the way to implement it.
4344         return SDValue();
4345       } else {
4346         MFI->setObjectAlignment(FI, 16);
4347       }
4348     }
4349
4350     // (Offset % 16) must be multiple of 4. Then address is then
4351     // Ptr + (Offset & ~15).
4352     if (Offset < 0)
4353       return SDValue();
4354     if ((Offset % 16) & 3)
4355       return SDValue();
4356     int64_t StartOffset = Offset & ~15;
4357     if (StartOffset)
4358       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4359                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4360
4361     int EltNo = (Offset - StartOffset) >> 2;
4362     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4363     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4364     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4365                              LD->getPointerInfo().getWithOffset(StartOffset),
4366                              false, false, 0);
4367     // Canonicalize it to a v4i32 shuffle.
4368     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4369     return DAG.getNode(ISD::BITCAST, dl, VT,
4370                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4371                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4372   }
4373
4374   return SDValue();
4375 }
4376
4377 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4378 /// vector of type 'VT', see if the elements can be replaced by a single large
4379 /// load which has the same value as a build_vector whose operands are 'elts'.
4380 ///
4381 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4382 ///
4383 /// FIXME: we'd also like to handle the case where the last elements are zero
4384 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4385 /// There's even a handy isZeroNode for that purpose.
4386 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4387                                         DebugLoc &DL, SelectionDAG &DAG) {
4388   EVT EltVT = VT.getVectorElementType();
4389   unsigned NumElems = Elts.size();
4390
4391   LoadSDNode *LDBase = NULL;
4392   unsigned LastLoadedElt = -1U;
4393
4394   // For each element in the initializer, see if we've found a load or an undef.
4395   // If we don't find an initial load element, or later load elements are
4396   // non-consecutive, bail out.
4397   for (unsigned i = 0; i < NumElems; ++i) {
4398     SDValue Elt = Elts[i];
4399
4400     if (!Elt.getNode() ||
4401         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4402       return SDValue();
4403     if (!LDBase) {
4404       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4405         return SDValue();
4406       LDBase = cast<LoadSDNode>(Elt.getNode());
4407       LastLoadedElt = i;
4408       continue;
4409     }
4410     if (Elt.getOpcode() == ISD::UNDEF)
4411       continue;
4412
4413     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4414     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4415       return SDValue();
4416     LastLoadedElt = i;
4417   }
4418
4419   // If we have found an entire vector of loads and undefs, then return a large
4420   // load of the entire vector width starting at the base pointer.  If we found
4421   // consecutive loads for the low half, generate a vzext_load node.
4422   if (LastLoadedElt == NumElems - 1) {
4423     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4424       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4425                          LDBase->getPointerInfo(),
4426                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4427     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4428                        LDBase->getPointerInfo(),
4429                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4430                        LDBase->getAlignment());
4431   } else if (NumElems == 4 && LastLoadedElt == 1) {
4432     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4433     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4434     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4435                                               Ops, 2, MVT::i32,
4436                                               LDBase->getMemOperand());
4437     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4438   }
4439   return SDValue();
4440 }
4441
4442 SDValue
4443 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4444   DebugLoc dl = Op.getDebugLoc();
4445
4446   EVT VT = Op.getValueType();
4447   EVT ExtVT = VT.getVectorElementType();
4448
4449   unsigned NumElems = Op.getNumOperands();
4450
4451   // For AVX-length vectors, build the individual 128-bit pieces and
4452   // use shuffles to put them in place.
4453   if (VT.getSizeInBits() > 256 &&
4454       Subtarget->hasAVX() &&
4455       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4456     SmallVector<SDValue, 8> V;
4457     V.resize(NumElems);
4458     for (unsigned i = 0; i < NumElems; ++i) {
4459       V[i] = Op.getOperand(i);
4460     }
4461
4462     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4463
4464     // Build the lower subvector.
4465     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4466     // Build the upper subvector.
4467     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4468                                 NumElems/2);
4469
4470     return ConcatVectors(Lower, Upper, DAG);
4471   }
4472
4473   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4474   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4475   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4476   // is present, so AllOnes is ignored.
4477   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4478       (Op.getValueType().getSizeInBits() != 256 &&
4479        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4480     // Canonicalize this to <4 x i32> (SSE) to
4481     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4482     // eliminated on x86-32 hosts.
4483     if (Op.getValueType() == MVT::v4i32)
4484       return Op;
4485
4486     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4487       return getOnesVector(Op.getValueType(), DAG, dl);
4488     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4489   }
4490
4491   unsigned EVTBits = ExtVT.getSizeInBits();
4492
4493   unsigned NumZero  = 0;
4494   unsigned NumNonZero = 0;
4495   unsigned NonZeros = 0;
4496   bool IsAllConstants = true;
4497   SmallSet<SDValue, 8> Values;
4498   for (unsigned i = 0; i < NumElems; ++i) {
4499     SDValue Elt = Op.getOperand(i);
4500     if (Elt.getOpcode() == ISD::UNDEF)
4501       continue;
4502     Values.insert(Elt);
4503     if (Elt.getOpcode() != ISD::Constant &&
4504         Elt.getOpcode() != ISD::ConstantFP)
4505       IsAllConstants = false;
4506     if (X86::isZeroNode(Elt))
4507       NumZero++;
4508     else {
4509       NonZeros |= (1 << i);
4510       NumNonZero++;
4511     }
4512   }
4513
4514   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4515   if (NumNonZero == 0)
4516     return DAG.getUNDEF(VT);
4517
4518   // Special case for single non-zero, non-undef, element.
4519   if (NumNonZero == 1) {
4520     unsigned Idx = CountTrailingZeros_32(NonZeros);
4521     SDValue Item = Op.getOperand(Idx);
4522
4523     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4524     // the value are obviously zero, truncate the value to i32 and do the
4525     // insertion that way.  Only do this if the value is non-constant or if the
4526     // value is a constant being inserted into element 0.  It is cheaper to do
4527     // a constant pool load than it is to do a movd + shuffle.
4528     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4529         (!IsAllConstants || Idx == 0)) {
4530       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4531         // Handle SSE only.
4532         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4533         EVT VecVT = MVT::v4i32;
4534         unsigned VecElts = 4;
4535
4536         // Truncate the value (which may itself be a constant) to i32, and
4537         // convert it to a vector with movd (S2V+shuffle to zero extend).
4538         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4539         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4540         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4541                                            Subtarget->hasSSE2(), DAG);
4542
4543         // Now we have our 32-bit value zero extended in the low element of
4544         // a vector.  If Idx != 0, swizzle it into place.
4545         if (Idx != 0) {
4546           SmallVector<int, 4> Mask;
4547           Mask.push_back(Idx);
4548           for (unsigned i = 1; i != VecElts; ++i)
4549             Mask.push_back(i);
4550           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4551                                       DAG.getUNDEF(Item.getValueType()),
4552                                       &Mask[0]);
4553         }
4554         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4555       }
4556     }
4557
4558     // If we have a constant or non-constant insertion into the low element of
4559     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4560     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4561     // depending on what the source datatype is.
4562     if (Idx == 0) {
4563       if (NumZero == 0) {
4564         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4565       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4566           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4567         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4568         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4569         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4570                                            DAG);
4571       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4572         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4573         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4574         EVT MiddleVT = MVT::v4i32;
4575         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4576         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4577                                            Subtarget->hasSSE2(), DAG);
4578         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4579       }
4580     }
4581
4582     // Is it a vector logical left shift?
4583     if (NumElems == 2 && Idx == 1 &&
4584         X86::isZeroNode(Op.getOperand(0)) &&
4585         !X86::isZeroNode(Op.getOperand(1))) {
4586       unsigned NumBits = VT.getSizeInBits();
4587       return getVShift(true, VT,
4588                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4589                                    VT, Op.getOperand(1)),
4590                        NumBits/2, DAG, *this, dl);
4591     }
4592
4593     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4594       return SDValue();
4595
4596     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4597     // is a non-constant being inserted into an element other than the low one,
4598     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4599     // movd/movss) to move this into the low element, then shuffle it into
4600     // place.
4601     if (EVTBits == 32) {
4602       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4603
4604       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4605       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4606                                          Subtarget->hasSSE2(), DAG);
4607       SmallVector<int, 8> MaskVec;
4608       for (unsigned i = 0; i < NumElems; i++)
4609         MaskVec.push_back(i == Idx ? 0 : 1);
4610       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4611     }
4612   }
4613
4614   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4615   if (Values.size() == 1) {
4616     if (EVTBits == 32) {
4617       // Instead of a shuffle like this:
4618       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4619       // Check if it's possible to issue this instead.
4620       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4621       unsigned Idx = CountTrailingZeros_32(NonZeros);
4622       SDValue Item = Op.getOperand(Idx);
4623       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4624         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4625     }
4626     return SDValue();
4627   }
4628
4629   // A vector full of immediates; various special cases are already
4630   // handled, so this is best done with a single constant-pool load.
4631   if (IsAllConstants)
4632     return SDValue();
4633
4634   // Let legalizer expand 2-wide build_vectors.
4635   if (EVTBits == 64) {
4636     if (NumNonZero == 1) {
4637       // One half is zero or undef.
4638       unsigned Idx = CountTrailingZeros_32(NonZeros);
4639       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4640                                  Op.getOperand(Idx));
4641       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4642                                          Subtarget->hasSSE2(), DAG);
4643     }
4644     return SDValue();
4645   }
4646
4647   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4648   if (EVTBits == 8 && NumElems == 16) {
4649     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4650                                         *this);
4651     if (V.getNode()) return V;
4652   }
4653
4654   if (EVTBits == 16 && NumElems == 8) {
4655     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4656                                       *this);
4657     if (V.getNode()) return V;
4658   }
4659
4660   // If element VT is == 32 bits, turn it into a number of shuffles.
4661   SmallVector<SDValue, 8> V;
4662   V.resize(NumElems);
4663   if (NumElems == 4 && NumZero > 0) {
4664     for (unsigned i = 0; i < 4; ++i) {
4665       bool isZero = !(NonZeros & (1 << i));
4666       if (isZero)
4667         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4668       else
4669         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4670     }
4671
4672     for (unsigned i = 0; i < 2; ++i) {
4673       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4674         default: break;
4675         case 0:
4676           V[i] = V[i*2];  // Must be a zero vector.
4677           break;
4678         case 1:
4679           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4680           break;
4681         case 2:
4682           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4683           break;
4684         case 3:
4685           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4686           break;
4687       }
4688     }
4689
4690     SmallVector<int, 8> MaskVec;
4691     bool Reverse = (NonZeros & 0x3) == 2;
4692     for (unsigned i = 0; i < 2; ++i)
4693       MaskVec.push_back(Reverse ? 1-i : i);
4694     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4695     for (unsigned i = 0; i < 2; ++i)
4696       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4697     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4698   }
4699
4700   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4701     // Check for a build vector of consecutive loads.
4702     for (unsigned i = 0; i < NumElems; ++i)
4703       V[i] = Op.getOperand(i);
4704
4705     // Check for elements which are consecutive loads.
4706     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4707     if (LD.getNode())
4708       return LD;
4709
4710     // For SSE 4.1, use insertps to put the high elements into the low element.
4711     if (getSubtarget()->hasSSE41()) {
4712       SDValue Result;
4713       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4714         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4715       else
4716         Result = DAG.getUNDEF(VT);
4717
4718       for (unsigned i = 1; i < NumElems; ++i) {
4719         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4720         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4721                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4722       }
4723       return Result;
4724     }
4725
4726     // Otherwise, expand into a number of unpckl*, start by extending each of
4727     // our (non-undef) elements to the full vector width with the element in the
4728     // bottom slot of the vector (which generates no code for SSE).
4729     for (unsigned i = 0; i < NumElems; ++i) {
4730       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4731         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4732       else
4733         V[i] = DAG.getUNDEF(VT);
4734     }
4735
4736     // Next, we iteratively mix elements, e.g. for v4f32:
4737     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4738     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4739     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4740     unsigned EltStride = NumElems >> 1;
4741     while (EltStride != 0) {
4742       for (unsigned i = 0; i < EltStride; ++i) {
4743         // If V[i+EltStride] is undef and this is the first round of mixing,
4744         // then it is safe to just drop this shuffle: V[i] is already in the
4745         // right place, the one element (since it's the first round) being
4746         // inserted as undef can be dropped.  This isn't safe for successive
4747         // rounds because they will permute elements within both vectors.
4748         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4749             EltStride == NumElems/2)
4750           continue;
4751
4752         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4753       }
4754       EltStride >>= 1;
4755     }
4756     return V[0];
4757   }
4758   return SDValue();
4759 }
4760
4761 SDValue
4762 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4763   // We support concatenate two MMX registers and place them in a MMX
4764   // register.  This is better than doing a stack convert.
4765   DebugLoc dl = Op.getDebugLoc();
4766   EVT ResVT = Op.getValueType();
4767   assert(Op.getNumOperands() == 2);
4768   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4769          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4770   int Mask[2];
4771   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4772   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4773   InVec = Op.getOperand(1);
4774   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4775     unsigned NumElts = ResVT.getVectorNumElements();
4776     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4777     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4778                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4779   } else {
4780     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4781     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4782     Mask[0] = 0; Mask[1] = 2;
4783     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4784   }
4785   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4786 }
4787
4788 // v8i16 shuffles - Prefer shuffles in the following order:
4789 // 1. [all]   pshuflw, pshufhw, optional move
4790 // 2. [ssse3] 1 x pshufb
4791 // 3. [ssse3] 2 x pshufb + 1 x por
4792 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4793 SDValue
4794 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4795                                             SelectionDAG &DAG) const {
4796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4797   SDValue V1 = SVOp->getOperand(0);
4798   SDValue V2 = SVOp->getOperand(1);
4799   DebugLoc dl = SVOp->getDebugLoc();
4800   SmallVector<int, 8> MaskVals;
4801
4802   // Determine if more than 1 of the words in each of the low and high quadwords
4803   // of the result come from the same quadword of one of the two inputs.  Undef
4804   // mask values count as coming from any quadword, for better codegen.
4805   SmallVector<unsigned, 4> LoQuad(4);
4806   SmallVector<unsigned, 4> HiQuad(4);
4807   BitVector InputQuads(4);
4808   for (unsigned i = 0; i < 8; ++i) {
4809     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4810     int EltIdx = SVOp->getMaskElt(i);
4811     MaskVals.push_back(EltIdx);
4812     if (EltIdx < 0) {
4813       ++Quad[0];
4814       ++Quad[1];
4815       ++Quad[2];
4816       ++Quad[3];
4817       continue;
4818     }
4819     ++Quad[EltIdx / 4];
4820     InputQuads.set(EltIdx / 4);
4821   }
4822
4823   int BestLoQuad = -1;
4824   unsigned MaxQuad = 1;
4825   for (unsigned i = 0; i < 4; ++i) {
4826     if (LoQuad[i] > MaxQuad) {
4827       BestLoQuad = i;
4828       MaxQuad = LoQuad[i];
4829     }
4830   }
4831
4832   int BestHiQuad = -1;
4833   MaxQuad = 1;
4834   for (unsigned i = 0; i < 4; ++i) {
4835     if (HiQuad[i] > MaxQuad) {
4836       BestHiQuad = i;
4837       MaxQuad = HiQuad[i];
4838     }
4839   }
4840
4841   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4842   // of the two input vectors, shuffle them into one input vector so only a
4843   // single pshufb instruction is necessary. If There are more than 2 input
4844   // quads, disable the next transformation since it does not help SSSE3.
4845   bool V1Used = InputQuads[0] || InputQuads[1];
4846   bool V2Used = InputQuads[2] || InputQuads[3];
4847   if (Subtarget->hasSSSE3()) {
4848     if (InputQuads.count() == 2 && V1Used && V2Used) {
4849       BestLoQuad = InputQuads.find_first();
4850       BestHiQuad = InputQuads.find_next(BestLoQuad);
4851     }
4852     if (InputQuads.count() > 2) {
4853       BestLoQuad = -1;
4854       BestHiQuad = -1;
4855     }
4856   }
4857
4858   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4859   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4860   // words from all 4 input quadwords.
4861   SDValue NewV;
4862   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4863     SmallVector<int, 8> MaskV;
4864     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4865     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4866     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4867                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4868                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4869     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4870
4871     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4872     // source words for the shuffle, to aid later transformations.
4873     bool AllWordsInNewV = true;
4874     bool InOrder[2] = { true, true };
4875     for (unsigned i = 0; i != 8; ++i) {
4876       int idx = MaskVals[i];
4877       if (idx != (int)i)
4878         InOrder[i/4] = false;
4879       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4880         continue;
4881       AllWordsInNewV = false;
4882       break;
4883     }
4884
4885     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4886     if (AllWordsInNewV) {
4887       for (int i = 0; i != 8; ++i) {
4888         int idx = MaskVals[i];
4889         if (idx < 0)
4890           continue;
4891         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4892         if ((idx != i) && idx < 4)
4893           pshufhw = false;
4894         if ((idx != i) && idx > 3)
4895           pshuflw = false;
4896       }
4897       V1 = NewV;
4898       V2Used = false;
4899       BestLoQuad = 0;
4900       BestHiQuad = 1;
4901     }
4902
4903     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4904     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4905     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4906       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4907       unsigned TargetMask = 0;
4908       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4909                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4910       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4911                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4912       V1 = NewV.getOperand(0);
4913       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4914     }
4915   }
4916
4917   // If we have SSSE3, and all words of the result are from 1 input vector,
4918   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4919   // is present, fall back to case 4.
4920   if (Subtarget->hasSSSE3()) {
4921     SmallVector<SDValue,16> pshufbMask;
4922
4923     // If we have elements from both input vectors, set the high bit of the
4924     // shuffle mask element to zero out elements that come from V2 in the V1
4925     // mask, and elements that come from V1 in the V2 mask, so that the two
4926     // results can be OR'd together.
4927     bool TwoInputs = V1Used && V2Used;
4928     for (unsigned i = 0; i != 8; ++i) {
4929       int EltIdx = MaskVals[i] * 2;
4930       if (TwoInputs && (EltIdx >= 16)) {
4931         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4932         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4933         continue;
4934       }
4935       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4936       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4937     }
4938     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4939     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4940                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4941                                  MVT::v16i8, &pshufbMask[0], 16));
4942     if (!TwoInputs)
4943       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4944
4945     // Calculate the shuffle mask for the second input, shuffle it, and
4946     // OR it with the first shuffled input.
4947     pshufbMask.clear();
4948     for (unsigned i = 0; i != 8; ++i) {
4949       int EltIdx = MaskVals[i] * 2;
4950       if (EltIdx < 16) {
4951         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4952         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4953         continue;
4954       }
4955       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4956       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4957     }
4958     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4959     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4960                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4961                                  MVT::v16i8, &pshufbMask[0], 16));
4962     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4963     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4964   }
4965
4966   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4967   // and update MaskVals with new element order.
4968   BitVector InOrder(8);
4969   if (BestLoQuad >= 0) {
4970     SmallVector<int, 8> MaskV;
4971     for (int i = 0; i != 4; ++i) {
4972       int idx = MaskVals[i];
4973       if (idx < 0) {
4974         MaskV.push_back(-1);
4975         InOrder.set(i);
4976       } else if ((idx / 4) == BestLoQuad) {
4977         MaskV.push_back(idx & 3);
4978         InOrder.set(i);
4979       } else {
4980         MaskV.push_back(-1);
4981       }
4982     }
4983     for (unsigned i = 4; i != 8; ++i)
4984       MaskV.push_back(i);
4985     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4986                                 &MaskV[0]);
4987
4988     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4989       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4990                                NewV.getOperand(0),
4991                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4992                                DAG);
4993   }
4994
4995   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4996   // and update MaskVals with the new element order.
4997   if (BestHiQuad >= 0) {
4998     SmallVector<int, 8> MaskV;
4999     for (unsigned i = 0; i != 4; ++i)
5000       MaskV.push_back(i);
5001     for (unsigned i = 4; i != 8; ++i) {
5002       int idx = MaskVals[i];
5003       if (idx < 0) {
5004         MaskV.push_back(-1);
5005         InOrder.set(i);
5006       } else if ((idx / 4) == BestHiQuad) {
5007         MaskV.push_back((idx & 3) + 4);
5008         InOrder.set(i);
5009       } else {
5010         MaskV.push_back(-1);
5011       }
5012     }
5013     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5014                                 &MaskV[0]);
5015
5016     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5017       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5018                               NewV.getOperand(0),
5019                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5020                               DAG);
5021   }
5022
5023   // In case BestHi & BestLo were both -1, which means each quadword has a word
5024   // from each of the four input quadwords, calculate the InOrder bitvector now
5025   // before falling through to the insert/extract cleanup.
5026   if (BestLoQuad == -1 && BestHiQuad == -1) {
5027     NewV = V1;
5028     for (int i = 0; i != 8; ++i)
5029       if (MaskVals[i] < 0 || MaskVals[i] == i)
5030         InOrder.set(i);
5031   }
5032
5033   // The other elements are put in the right place using pextrw and pinsrw.
5034   for (unsigned i = 0; i != 8; ++i) {
5035     if (InOrder[i])
5036       continue;
5037     int EltIdx = MaskVals[i];
5038     if (EltIdx < 0)
5039       continue;
5040     SDValue ExtOp = (EltIdx < 8)
5041     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5042                   DAG.getIntPtrConstant(EltIdx))
5043     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5044                   DAG.getIntPtrConstant(EltIdx - 8));
5045     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5046                        DAG.getIntPtrConstant(i));
5047   }
5048   return NewV;
5049 }
5050
5051 // v16i8 shuffles - Prefer shuffles in the following order:
5052 // 1. [ssse3] 1 x pshufb
5053 // 2. [ssse3] 2 x pshufb + 1 x por
5054 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5055 static
5056 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5057                                  SelectionDAG &DAG,
5058                                  const X86TargetLowering &TLI) {
5059   SDValue V1 = SVOp->getOperand(0);
5060   SDValue V2 = SVOp->getOperand(1);
5061   DebugLoc dl = SVOp->getDebugLoc();
5062   SmallVector<int, 16> MaskVals;
5063   SVOp->getMask(MaskVals);
5064
5065   // If we have SSSE3, case 1 is generated when all result bytes come from
5066   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5067   // present, fall back to case 3.
5068   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5069   bool V1Only = true;
5070   bool V2Only = true;
5071   for (unsigned i = 0; i < 16; ++i) {
5072     int EltIdx = MaskVals[i];
5073     if (EltIdx < 0)
5074       continue;
5075     if (EltIdx < 16)
5076       V2Only = false;
5077     else
5078       V1Only = false;
5079   }
5080
5081   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5082   if (TLI.getSubtarget()->hasSSSE3()) {
5083     SmallVector<SDValue,16> pshufbMask;
5084
5085     // If all result elements are from one input vector, then only translate
5086     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5087     //
5088     // Otherwise, we have elements from both input vectors, and must zero out
5089     // elements that come from V2 in the first mask, and V1 in the second mask
5090     // so that we can OR them together.
5091     bool TwoInputs = !(V1Only || V2Only);
5092     for (unsigned i = 0; i != 16; ++i) {
5093       int EltIdx = MaskVals[i];
5094       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5095         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5096         continue;
5097       }
5098       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5099     }
5100     // If all the elements are from V2, assign it to V1 and return after
5101     // building the first pshufb.
5102     if (V2Only)
5103       V1 = V2;
5104     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5105                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5106                                  MVT::v16i8, &pshufbMask[0], 16));
5107     if (!TwoInputs)
5108       return V1;
5109
5110     // Calculate the shuffle mask for the second input, shuffle it, and
5111     // OR it with the first shuffled input.
5112     pshufbMask.clear();
5113     for (unsigned i = 0; i != 16; ++i) {
5114       int EltIdx = MaskVals[i];
5115       if (EltIdx < 16) {
5116         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5117         continue;
5118       }
5119       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5120     }
5121     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5122                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5123                                  MVT::v16i8, &pshufbMask[0], 16));
5124     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5125   }
5126
5127   // No SSSE3 - Calculate in place words and then fix all out of place words
5128   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5129   // the 16 different words that comprise the two doublequadword input vectors.
5130   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5131   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5132   SDValue NewV = V2Only ? V2 : V1;
5133   for (int i = 0; i != 8; ++i) {
5134     int Elt0 = MaskVals[i*2];
5135     int Elt1 = MaskVals[i*2+1];
5136
5137     // This word of the result is all undef, skip it.
5138     if (Elt0 < 0 && Elt1 < 0)
5139       continue;
5140
5141     // This word of the result is already in the correct place, skip it.
5142     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5143       continue;
5144     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5145       continue;
5146
5147     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5148     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5149     SDValue InsElt;
5150
5151     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5152     // using a single extract together, load it and store it.
5153     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5154       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5155                            DAG.getIntPtrConstant(Elt1 / 2));
5156       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5157                         DAG.getIntPtrConstant(i));
5158       continue;
5159     }
5160
5161     // If Elt1 is defined, extract it from the appropriate source.  If the
5162     // source byte is not also odd, shift the extracted word left 8 bits
5163     // otherwise clear the bottom 8 bits if we need to do an or.
5164     if (Elt1 >= 0) {
5165       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5166                            DAG.getIntPtrConstant(Elt1 / 2));
5167       if ((Elt1 & 1) == 0)
5168         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5169                              DAG.getConstant(8,
5170                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5171       else if (Elt0 >= 0)
5172         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5173                              DAG.getConstant(0xFF00, MVT::i16));
5174     }
5175     // If Elt0 is defined, extract it from the appropriate source.  If the
5176     // source byte is not also even, shift the extracted word right 8 bits. If
5177     // Elt1 was also defined, OR the extracted values together before
5178     // inserting them in the result.
5179     if (Elt0 >= 0) {
5180       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5181                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5182       if ((Elt0 & 1) != 0)
5183         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5184                               DAG.getConstant(8,
5185                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5186       else if (Elt1 >= 0)
5187         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5188                              DAG.getConstant(0x00FF, MVT::i16));
5189       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5190                          : InsElt0;
5191     }
5192     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5193                        DAG.getIntPtrConstant(i));
5194   }
5195   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5196 }
5197
5198 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5199 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5200 /// done when every pair / quad of shuffle mask elements point to elements in
5201 /// the right sequence. e.g.
5202 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5203 static
5204 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5205                                  SelectionDAG &DAG, DebugLoc dl) {
5206   EVT VT = SVOp->getValueType(0);
5207   SDValue V1 = SVOp->getOperand(0);
5208   SDValue V2 = SVOp->getOperand(1);
5209   unsigned NumElems = VT.getVectorNumElements();
5210   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5211   EVT NewVT;
5212   switch (VT.getSimpleVT().SimpleTy) {
5213   default: assert(false && "Unexpected!");
5214   case MVT::v4f32: NewVT = MVT::v2f64; break;
5215   case MVT::v4i32: NewVT = MVT::v2i64; break;
5216   case MVT::v8i16: NewVT = MVT::v4i32; break;
5217   case MVT::v16i8: NewVT = MVT::v4i32; break;
5218   }
5219
5220   int Scale = NumElems / NewWidth;
5221   SmallVector<int, 8> MaskVec;
5222   for (unsigned i = 0; i < NumElems; i += Scale) {
5223     int StartIdx = -1;
5224     for (int j = 0; j < Scale; ++j) {
5225       int EltIdx = SVOp->getMaskElt(i+j);
5226       if (EltIdx < 0)
5227         continue;
5228       if (StartIdx == -1)
5229         StartIdx = EltIdx - (EltIdx % Scale);
5230       if (EltIdx != StartIdx + j)
5231         return SDValue();
5232     }
5233     if (StartIdx == -1)
5234       MaskVec.push_back(-1);
5235     else
5236       MaskVec.push_back(StartIdx / Scale);
5237   }
5238
5239   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5240   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5241   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5242 }
5243
5244 /// getVZextMovL - Return a zero-extending vector move low node.
5245 ///
5246 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5247                             SDValue SrcOp, SelectionDAG &DAG,
5248                             const X86Subtarget *Subtarget, DebugLoc dl) {
5249   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5250     LoadSDNode *LD = NULL;
5251     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5252       LD = dyn_cast<LoadSDNode>(SrcOp);
5253     if (!LD) {
5254       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5255       // instead.
5256       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5257       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5258           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5259           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5260           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5261         // PR2108
5262         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5263         return DAG.getNode(ISD::BITCAST, dl, VT,
5264                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5265                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5266                                                    OpVT,
5267                                                    SrcOp.getOperand(0)
5268                                                           .getOperand(0))));
5269       }
5270     }
5271   }
5272
5273   return DAG.getNode(ISD::BITCAST, dl, VT,
5274                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5275                                  DAG.getNode(ISD::BITCAST, dl,
5276                                              OpVT, SrcOp)));
5277 }
5278
5279 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5280 /// shuffles.
5281 static SDValue
5282 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5283   SDValue V1 = SVOp->getOperand(0);
5284   SDValue V2 = SVOp->getOperand(1);
5285   DebugLoc dl = SVOp->getDebugLoc();
5286   EVT VT = SVOp->getValueType(0);
5287
5288   SmallVector<std::pair<int, int>, 8> Locs;
5289   Locs.resize(4);
5290   SmallVector<int, 8> Mask1(4U, -1);
5291   SmallVector<int, 8> PermMask;
5292   SVOp->getMask(PermMask);
5293
5294   unsigned NumHi = 0;
5295   unsigned NumLo = 0;
5296   for (unsigned i = 0; i != 4; ++i) {
5297     int Idx = PermMask[i];
5298     if (Idx < 0) {
5299       Locs[i] = std::make_pair(-1, -1);
5300     } else {
5301       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5302       if (Idx < 4) {
5303         Locs[i] = std::make_pair(0, NumLo);
5304         Mask1[NumLo] = Idx;
5305         NumLo++;
5306       } else {
5307         Locs[i] = std::make_pair(1, NumHi);
5308         if (2+NumHi < 4)
5309           Mask1[2+NumHi] = Idx;
5310         NumHi++;
5311       }
5312     }
5313   }
5314
5315   if (NumLo <= 2 && NumHi <= 2) {
5316     // If no more than two elements come from either vector. This can be
5317     // implemented with two shuffles. First shuffle gather the elements.
5318     // The second shuffle, which takes the first shuffle as both of its
5319     // vector operands, put the elements into the right order.
5320     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5321
5322     SmallVector<int, 8> Mask2(4U, -1);
5323
5324     for (unsigned i = 0; i != 4; ++i) {
5325       if (Locs[i].first == -1)
5326         continue;
5327       else {
5328         unsigned Idx = (i < 2) ? 0 : 4;
5329         Idx += Locs[i].first * 2 + Locs[i].second;
5330         Mask2[i] = Idx;
5331       }
5332     }
5333
5334     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5335   } else if (NumLo == 3 || NumHi == 3) {
5336     // Otherwise, we must have three elements from one vector, call it X, and
5337     // one element from the other, call it Y.  First, use a shufps to build an
5338     // intermediate vector with the one element from Y and the element from X
5339     // that will be in the same half in the final destination (the indexes don't
5340     // matter). Then, use a shufps to build the final vector, taking the half
5341     // containing the element from Y from the intermediate, and the other half
5342     // from X.
5343     if (NumHi == 3) {
5344       // Normalize it so the 3 elements come from V1.
5345       CommuteVectorShuffleMask(PermMask, VT);
5346       std::swap(V1, V2);
5347     }
5348
5349     // Find the element from V2.
5350     unsigned HiIndex;
5351     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5352       int Val = PermMask[HiIndex];
5353       if (Val < 0)
5354         continue;
5355       if (Val >= 4)
5356         break;
5357     }
5358
5359     Mask1[0] = PermMask[HiIndex];
5360     Mask1[1] = -1;
5361     Mask1[2] = PermMask[HiIndex^1];
5362     Mask1[3] = -1;
5363     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5364
5365     if (HiIndex >= 2) {
5366       Mask1[0] = PermMask[0];
5367       Mask1[1] = PermMask[1];
5368       Mask1[2] = HiIndex & 1 ? 6 : 4;
5369       Mask1[3] = HiIndex & 1 ? 4 : 6;
5370       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5371     } else {
5372       Mask1[0] = HiIndex & 1 ? 2 : 0;
5373       Mask1[1] = HiIndex & 1 ? 0 : 2;
5374       Mask1[2] = PermMask[2];
5375       Mask1[3] = PermMask[3];
5376       if (Mask1[2] >= 0)
5377         Mask1[2] += 4;
5378       if (Mask1[3] >= 0)
5379         Mask1[3] += 4;
5380       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5381     }
5382   }
5383
5384   // Break it into (shuffle shuffle_hi, shuffle_lo).
5385   Locs.clear();
5386   Locs.resize(4);
5387   SmallVector<int,8> LoMask(4U, -1);
5388   SmallVector<int,8> HiMask(4U, -1);
5389
5390   SmallVector<int,8> *MaskPtr = &LoMask;
5391   unsigned MaskIdx = 0;
5392   unsigned LoIdx = 0;
5393   unsigned HiIdx = 2;
5394   for (unsigned i = 0; i != 4; ++i) {
5395     if (i == 2) {
5396       MaskPtr = &HiMask;
5397       MaskIdx = 1;
5398       LoIdx = 0;
5399       HiIdx = 2;
5400     }
5401     int Idx = PermMask[i];
5402     if (Idx < 0) {
5403       Locs[i] = std::make_pair(-1, -1);
5404     } else if (Idx < 4) {
5405       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5406       (*MaskPtr)[LoIdx] = Idx;
5407       LoIdx++;
5408     } else {
5409       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5410       (*MaskPtr)[HiIdx] = Idx;
5411       HiIdx++;
5412     }
5413   }
5414
5415   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5416   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5417   SmallVector<int, 8> MaskOps;
5418   for (unsigned i = 0; i != 4; ++i) {
5419     if (Locs[i].first == -1) {
5420       MaskOps.push_back(-1);
5421     } else {
5422       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5423       MaskOps.push_back(Idx);
5424     }
5425   }
5426   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5427 }
5428
5429 static bool MayFoldVectorLoad(SDValue V) {
5430   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5431     V = V.getOperand(0);
5432   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5433     V = V.getOperand(0);
5434   if (MayFoldLoad(V))
5435     return true;
5436   return false;
5437 }
5438
5439 // FIXME: the version above should always be used. Since there's
5440 // a bug where several vector shuffles can't be folded because the
5441 // DAG is not updated during lowering and a node claims to have two
5442 // uses while it only has one, use this version, and let isel match
5443 // another instruction if the load really happens to have more than
5444 // one use. Remove this version after this bug get fixed.
5445 // rdar://8434668, PR8156
5446 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5447   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5448     V = V.getOperand(0);
5449   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5450     V = V.getOperand(0);
5451   if (ISD::isNormalLoad(V.getNode()))
5452     return true;
5453   return false;
5454 }
5455
5456 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5457 /// a vector extract, and if both can be later optimized into a single load.
5458 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5459 /// here because otherwise a target specific shuffle node is going to be
5460 /// emitted for this shuffle, and the optimization not done.
5461 /// FIXME: This is probably not the best approach, but fix the problem
5462 /// until the right path is decided.
5463 static
5464 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5465                                          const TargetLowering &TLI) {
5466   EVT VT = V.getValueType();
5467   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5468
5469   // Be sure that the vector shuffle is present in a pattern like this:
5470   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5471   if (!V.hasOneUse())
5472     return false;
5473
5474   SDNode *N = *V.getNode()->use_begin();
5475   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5476     return false;
5477
5478   SDValue EltNo = N->getOperand(1);
5479   if (!isa<ConstantSDNode>(EltNo))
5480     return false;
5481
5482   // If the bit convert changed the number of elements, it is unsafe
5483   // to examine the mask.
5484   bool HasShuffleIntoBitcast = false;
5485   if (V.getOpcode() == ISD::BITCAST) {
5486     EVT SrcVT = V.getOperand(0).getValueType();
5487     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5488       return false;
5489     V = V.getOperand(0);
5490     HasShuffleIntoBitcast = true;
5491   }
5492
5493   // Select the input vector, guarding against out of range extract vector.
5494   unsigned NumElems = VT.getVectorNumElements();
5495   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5496   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5497   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5498
5499   // Skip one more bit_convert if necessary
5500   if (V.getOpcode() == ISD::BITCAST)
5501     V = V.getOperand(0);
5502
5503   if (ISD::isNormalLoad(V.getNode())) {
5504     // Is the original load suitable?
5505     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5506
5507     // FIXME: avoid the multi-use bug that is preventing lots of
5508     // of foldings to be detected, this is still wrong of course, but
5509     // give the temporary desired behavior, and if it happens that
5510     // the load has real more uses, during isel it will not fold, and
5511     // will generate poor code.
5512     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5513       return false;
5514
5515     if (!HasShuffleIntoBitcast)
5516       return true;
5517
5518     // If there's a bitcast before the shuffle, check if the load type and
5519     // alignment is valid.
5520     unsigned Align = LN0->getAlignment();
5521     unsigned NewAlign =
5522       TLI.getTargetData()->getABITypeAlignment(
5523                                     VT.getTypeForEVT(*DAG.getContext()));
5524
5525     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5526       return false;
5527   }
5528
5529   return true;
5530 }
5531
5532 static
5533 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5534   EVT VT = Op.getValueType();
5535
5536   // Canonizalize to v2f64.
5537   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5538   return DAG.getNode(ISD::BITCAST, dl, VT,
5539                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5540                                           V1, DAG));
5541 }
5542
5543 static
5544 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5545                         bool HasSSE2) {
5546   SDValue V1 = Op.getOperand(0);
5547   SDValue V2 = Op.getOperand(1);
5548   EVT VT = Op.getValueType();
5549
5550   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5551
5552   if (HasSSE2 && VT == MVT::v2f64)
5553     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5554
5555   // v4f32 or v4i32
5556   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5557 }
5558
5559 static
5560 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5561   SDValue V1 = Op.getOperand(0);
5562   SDValue V2 = Op.getOperand(1);
5563   EVT VT = Op.getValueType();
5564
5565   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5566          "unsupported shuffle type");
5567
5568   if (V2.getOpcode() == ISD::UNDEF)
5569     V2 = V1;
5570
5571   // v4i32 or v4f32
5572   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5573 }
5574
5575 static
5576 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5577   SDValue V1 = Op.getOperand(0);
5578   SDValue V2 = Op.getOperand(1);
5579   EVT VT = Op.getValueType();
5580   unsigned NumElems = VT.getVectorNumElements();
5581
5582   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5583   // operand of these instructions is only memory, so check if there's a
5584   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5585   // same masks.
5586   bool CanFoldLoad = false;
5587
5588   // Trivial case, when V2 comes from a load.
5589   if (MayFoldVectorLoad(V2))
5590     CanFoldLoad = true;
5591
5592   // When V1 is a load, it can be folded later into a store in isel, example:
5593   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5594   //    turns into:
5595   //  (MOVLPSmr addr:$src1, VR128:$src2)
5596   // So, recognize this potential and also use MOVLPS or MOVLPD
5597   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5598     CanFoldLoad = true;
5599
5600   // Both of them can't be memory operations though.
5601   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5602     CanFoldLoad = false;
5603
5604   if (CanFoldLoad) {
5605     if (HasSSE2 && NumElems == 2)
5606       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5607
5608     if (NumElems == 4)
5609       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5610   }
5611
5612   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5613   // movl and movlp will both match v2i64, but v2i64 is never matched by
5614   // movl earlier because we make it strict to avoid messing with the movlp load
5615   // folding logic (see the code above getMOVLP call). Match it here then,
5616   // this is horrible, but will stay like this until we move all shuffle
5617   // matching to x86 specific nodes. Note that for the 1st condition all
5618   // types are matched with movsd.
5619   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5620     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5621   else if (HasSSE2)
5622     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5623
5624
5625   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5626
5627   // Invert the operand order and use SHUFPS to match it.
5628   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5629                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5630 }
5631
5632 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5633   switch(VT.getSimpleVT().SimpleTy) {
5634   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5635   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5636   case MVT::v4f32:
5637     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5638   case MVT::v2f64:
5639     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5640   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5641   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5642   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5643   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5644   default:
5645     llvm_unreachable("Unknown type for unpckl");
5646   }
5647   return 0;
5648 }
5649
5650 static inline unsigned getUNPCKHOpcode(EVT VT) {
5651   switch(VT.getSimpleVT().SimpleTy) {
5652   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5653   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5654   case MVT::v4f32: return X86ISD::UNPCKHPS;
5655   case MVT::v2f64: return X86ISD::UNPCKHPD;
5656   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5657   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5658   default:
5659     llvm_unreachable("Unknown type for unpckh");
5660   }
5661   return 0;
5662 }
5663
5664 static
5665 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5666                                const TargetLowering &TLI,
5667                                const X86Subtarget *Subtarget) {
5668   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5669   EVT VT = Op.getValueType();
5670   DebugLoc dl = Op.getDebugLoc();
5671   SDValue V1 = Op.getOperand(0);
5672   SDValue V2 = Op.getOperand(1);
5673
5674   if (isZeroShuffle(SVOp))
5675     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5676
5677   // Handle splat operations
5678   if (SVOp->isSplat()) {
5679     // Special case, this is the only place now where it's
5680     // allowed to return a vector_shuffle operation without
5681     // using a target specific node, because *hopefully* it
5682     // will be optimized away by the dag combiner.
5683     if (VT.getVectorNumElements() <= 4 &&
5684         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5685       return Op;
5686
5687     // Handle splats by matching through known masks
5688     if (VT.getVectorNumElements() <= 4)
5689       return SDValue();
5690
5691     // Canonicalize all of the remaining to v4f32.
5692     return PromoteSplat(SVOp, DAG);
5693   }
5694
5695   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5696   // do it!
5697   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5698     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5699     if (NewOp.getNode())
5700       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5701   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5702     // FIXME: Figure out a cleaner way to do this.
5703     // Try to make use of movq to zero out the top part.
5704     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5705       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5706       if (NewOp.getNode()) {
5707         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5708           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5709                               DAG, Subtarget, dl);
5710       }
5711     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5712       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5713       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5714         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5715                             DAG, Subtarget, dl);
5716     }
5717   }
5718   return SDValue();
5719 }
5720
5721 SDValue
5722 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5723   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5724   SDValue V1 = Op.getOperand(0);
5725   SDValue V2 = Op.getOperand(1);
5726   EVT VT = Op.getValueType();
5727   DebugLoc dl = Op.getDebugLoc();
5728   unsigned NumElems = VT.getVectorNumElements();
5729   bool isMMX = VT.getSizeInBits() == 64;
5730   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5731   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5732   bool V1IsSplat = false;
5733   bool V2IsSplat = false;
5734   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5735   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5736   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5737   MachineFunction &MF = DAG.getMachineFunction();
5738   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5739
5740   // Shuffle operations on MMX not supported.
5741   if (isMMX)
5742     return Op;
5743
5744   // Vector shuffle lowering takes 3 steps:
5745   //
5746   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5747   //    narrowing and commutation of operands should be handled.
5748   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5749   //    shuffle nodes.
5750   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5751   //    so the shuffle can be broken into other shuffles and the legalizer can
5752   //    try the lowering again.
5753   //
5754   // The general ideia is that no vector_shuffle operation should be left to
5755   // be matched during isel, all of them must be converted to a target specific
5756   // node here.
5757
5758   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5759   // narrowing and commutation of operands should be handled. The actual code
5760   // doesn't include all of those, work in progress...
5761   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5762   if (NewOp.getNode())
5763     return NewOp;
5764
5765   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5766   // unpckh_undef). Only use pshufd if speed is more important than size.
5767   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5768     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5769       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5770   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5771     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5772       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5773
5774   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5775       RelaxedMayFoldVectorLoad(V1))
5776     return getMOVDDup(Op, dl, V1, DAG);
5777
5778   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5779     return getMOVHighToLow(Op, dl, DAG);
5780
5781   // Use to match splats
5782   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5783       (VT == MVT::v2f64 || VT == MVT::v2i64))
5784     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5785
5786   if (X86::isPSHUFDMask(SVOp)) {
5787     // The actual implementation will match the mask in the if above and then
5788     // during isel it can match several different instructions, not only pshufd
5789     // as its name says, sad but true, emulate the behavior for now...
5790     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5791         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5792
5793     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5794
5795     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5796       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5797
5798     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5799       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5800                                   TargetMask, DAG);
5801
5802     if (VT == MVT::v4f32)
5803       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5804                                   TargetMask, DAG);
5805   }
5806
5807   // Check if this can be converted into a logical shift.
5808   bool isLeft = false;
5809   unsigned ShAmt = 0;
5810   SDValue ShVal;
5811   bool isShift = getSubtarget()->hasSSE2() &&
5812     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5813   if (isShift && ShVal.hasOneUse()) {
5814     // If the shifted value has multiple uses, it may be cheaper to use
5815     // v_set0 + movlhps or movhlps, etc.
5816     EVT EltVT = VT.getVectorElementType();
5817     ShAmt *= EltVT.getSizeInBits();
5818     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5819   }
5820
5821   if (X86::isMOVLMask(SVOp)) {
5822     if (V1IsUndef)
5823       return V2;
5824     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5825       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5826     if (!X86::isMOVLPMask(SVOp)) {
5827       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5828         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5829
5830       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5831         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5832     }
5833   }
5834
5835   // FIXME: fold these into legal mask.
5836   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5837     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5838
5839   if (X86::isMOVHLPSMask(SVOp))
5840     return getMOVHighToLow(Op, dl, DAG);
5841
5842   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5843     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5844
5845   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5846     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5847
5848   if (X86::isMOVLPMask(SVOp))
5849     return getMOVLP(Op, dl, DAG, HasSSE2);
5850
5851   if (ShouldXformToMOVHLPS(SVOp) ||
5852       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5853     return CommuteVectorShuffle(SVOp, DAG);
5854
5855   if (isShift) {
5856     // No better options. Use a vshl / vsrl.
5857     EVT EltVT = VT.getVectorElementType();
5858     ShAmt *= EltVT.getSizeInBits();
5859     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5860   }
5861
5862   bool Commuted = false;
5863   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5864   // 1,1,1,1 -> v8i16 though.
5865   V1IsSplat = isSplatVector(V1.getNode());
5866   V2IsSplat = isSplatVector(V2.getNode());
5867
5868   // Canonicalize the splat or undef, if present, to be on the RHS.
5869   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5870     Op = CommuteVectorShuffle(SVOp, DAG);
5871     SVOp = cast<ShuffleVectorSDNode>(Op);
5872     V1 = SVOp->getOperand(0);
5873     V2 = SVOp->getOperand(1);
5874     std::swap(V1IsSplat, V2IsSplat);
5875     std::swap(V1IsUndef, V2IsUndef);
5876     Commuted = true;
5877   }
5878
5879   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5880     // Shuffling low element of v1 into undef, just return v1.
5881     if (V2IsUndef)
5882       return V1;
5883     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5884     // the instruction selector will not match, so get a canonical MOVL with
5885     // swapped operands to undo the commute.
5886     return getMOVL(DAG, dl, VT, V2, V1);
5887   }
5888
5889   if (X86::isUNPCKLMask(SVOp))
5890     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5891                                 dl, VT, V1, V2, DAG);
5892
5893   if (X86::isUNPCKHMask(SVOp))
5894     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5895
5896   if (V2IsSplat) {
5897     // Normalize mask so all entries that point to V2 points to its first
5898     // element then try to match unpck{h|l} again. If match, return a
5899     // new vector_shuffle with the corrected mask.
5900     SDValue NewMask = NormalizeMask(SVOp, DAG);
5901     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5902     if (NSVOp != SVOp) {
5903       if (X86::isUNPCKLMask(NSVOp, true)) {
5904         return NewMask;
5905       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5906         return NewMask;
5907       }
5908     }
5909   }
5910
5911   if (Commuted) {
5912     // Commute is back and try unpck* again.
5913     // FIXME: this seems wrong.
5914     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5915     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5916
5917     if (X86::isUNPCKLMask(NewSVOp))
5918       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5919                                   dl, VT, V2, V1, DAG);
5920
5921     if (X86::isUNPCKHMask(NewSVOp))
5922       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5923   }
5924
5925   // Normalize the node to match x86 shuffle ops if needed
5926   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5927     return CommuteVectorShuffle(SVOp, DAG);
5928
5929   // The checks below are all present in isShuffleMaskLegal, but they are
5930   // inlined here right now to enable us to directly emit target specific
5931   // nodes, and remove one by one until they don't return Op anymore.
5932   SmallVector<int, 16> M;
5933   SVOp->getMask(M);
5934
5935   if (isPALIGNRMask(M, VT, HasSSSE3))
5936     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5937                                 X86::getShufflePALIGNRImmediate(SVOp),
5938                                 DAG);
5939
5940   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5941       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5942     if (VT == MVT::v2f64) {
5943       X86ISD::NodeType Opcode =
5944         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5945       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5946     }
5947     if (VT == MVT::v2i64)
5948       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5949   }
5950
5951   if (isPSHUFHWMask(M, VT))
5952     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5953                                 X86::getShufflePSHUFHWImmediate(SVOp),
5954                                 DAG);
5955
5956   if (isPSHUFLWMask(M, VT))
5957     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5958                                 X86::getShufflePSHUFLWImmediate(SVOp),
5959                                 DAG);
5960
5961   if (isSHUFPMask(M, VT)) {
5962     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5963     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5964       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5965                                   TargetMask, DAG);
5966     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5967       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5968                                   TargetMask, DAG);
5969   }
5970
5971   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5972     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5973       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5974                                   dl, VT, V1, V1, DAG);
5975   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5976     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5977       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5978
5979   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5980   if (VT == MVT::v8i16) {
5981     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5982     if (NewOp.getNode())
5983       return NewOp;
5984   }
5985
5986   if (VT == MVT::v16i8) {
5987     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5988     if (NewOp.getNode())
5989       return NewOp;
5990   }
5991
5992   // Handle all 4 wide cases with a number of shuffles.
5993   if (NumElems == 4)
5994     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5995
5996   return SDValue();
5997 }
5998
5999 SDValue
6000 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6001                                                 SelectionDAG &DAG) const {
6002   EVT VT = Op.getValueType();
6003   DebugLoc dl = Op.getDebugLoc();
6004   if (VT.getSizeInBits() == 8) {
6005     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6006                                     Op.getOperand(0), Op.getOperand(1));
6007     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6008                                     DAG.getValueType(VT));
6009     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6010   } else if (VT.getSizeInBits() == 16) {
6011     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6012     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6013     if (Idx == 0)
6014       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6015                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6016                                      DAG.getNode(ISD::BITCAST, dl,
6017                                                  MVT::v4i32,
6018                                                  Op.getOperand(0)),
6019                                      Op.getOperand(1)));
6020     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6021                                     Op.getOperand(0), Op.getOperand(1));
6022     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6023                                     DAG.getValueType(VT));
6024     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6025   } else if (VT == MVT::f32) {
6026     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6027     // the result back to FR32 register. It's only worth matching if the
6028     // result has a single use which is a store or a bitcast to i32.  And in
6029     // the case of a store, it's not worth it if the index is a constant 0,
6030     // because a MOVSSmr can be used instead, which is smaller and faster.
6031     if (!Op.hasOneUse())
6032       return SDValue();
6033     SDNode *User = *Op.getNode()->use_begin();
6034     if ((User->getOpcode() != ISD::STORE ||
6035          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6036           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6037         (User->getOpcode() != ISD::BITCAST ||
6038          User->getValueType(0) != MVT::i32))
6039       return SDValue();
6040     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6041                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6042                                               Op.getOperand(0)),
6043                                               Op.getOperand(1));
6044     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6045   } else if (VT == MVT::i32) {
6046     // ExtractPS works with constant index.
6047     if (isa<ConstantSDNode>(Op.getOperand(1)))
6048       return Op;
6049   }
6050   return SDValue();
6051 }
6052
6053
6054 SDValue
6055 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6056                                            SelectionDAG &DAG) const {
6057   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6058     return SDValue();
6059
6060   SDValue Vec = Op.getOperand(0);
6061   EVT VecVT = Vec.getValueType();
6062
6063   // If this is a 256-bit vector result, first extract the 128-bit
6064   // vector and then extract from the 128-bit vector.
6065   if (VecVT.getSizeInBits() > 128) {
6066     DebugLoc dl = Op.getNode()->getDebugLoc();
6067     unsigned NumElems = VecVT.getVectorNumElements();
6068     SDValue Idx = Op.getOperand(1);
6069
6070     if (!isa<ConstantSDNode>(Idx))
6071       return SDValue();
6072
6073     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6074     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6075
6076     // Get the 128-bit vector.
6077     bool Upper = IdxVal >= ExtractNumElems;
6078     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6079
6080     // Extract from it.
6081     SDValue ScaledIdx = Idx;
6082     if (Upper)
6083       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6084                               DAG.getConstant(ExtractNumElems,
6085                                               Idx.getValueType()));
6086     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6087                        ScaledIdx);
6088   }
6089
6090   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6091
6092   if (Subtarget->hasSSE41()) {
6093     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6094     if (Res.getNode())
6095       return Res;
6096   }
6097
6098   EVT VT = Op.getValueType();
6099   DebugLoc dl = Op.getDebugLoc();
6100   // TODO: handle v16i8.
6101   if (VT.getSizeInBits() == 16) {
6102     SDValue Vec = Op.getOperand(0);
6103     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6104     if (Idx == 0)
6105       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6106                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6107                                      DAG.getNode(ISD::BITCAST, dl,
6108                                                  MVT::v4i32, Vec),
6109                                      Op.getOperand(1)));
6110     // Transform it so it match pextrw which produces a 32-bit result.
6111     EVT EltVT = MVT::i32;
6112     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6113                                     Op.getOperand(0), Op.getOperand(1));
6114     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6115                                     DAG.getValueType(VT));
6116     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6117   } else if (VT.getSizeInBits() == 32) {
6118     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6119     if (Idx == 0)
6120       return Op;
6121
6122     // SHUFPS the element to the lowest double word, then movss.
6123     int Mask[4] = { Idx, -1, -1, -1 };
6124     EVT VVT = Op.getOperand(0).getValueType();
6125     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6126                                        DAG.getUNDEF(VVT), Mask);
6127     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6128                        DAG.getIntPtrConstant(0));
6129   } else if (VT.getSizeInBits() == 64) {
6130     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6131     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6132     //        to match extract_elt for f64.
6133     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6134     if (Idx == 0)
6135       return Op;
6136
6137     // UNPCKHPD the element to the lowest double word, then movsd.
6138     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6139     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6140     int Mask[2] = { 1, -1 };
6141     EVT VVT = Op.getOperand(0).getValueType();
6142     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6143                                        DAG.getUNDEF(VVT), Mask);
6144     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6145                        DAG.getIntPtrConstant(0));
6146   }
6147
6148   return SDValue();
6149 }
6150
6151 SDValue
6152 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6153                                                SelectionDAG &DAG) const {
6154   EVT VT = Op.getValueType();
6155   EVT EltVT = VT.getVectorElementType();
6156   DebugLoc dl = Op.getDebugLoc();
6157
6158   SDValue N0 = Op.getOperand(0);
6159   SDValue N1 = Op.getOperand(1);
6160   SDValue N2 = Op.getOperand(2);
6161
6162   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6163       isa<ConstantSDNode>(N2)) {
6164     unsigned Opc;
6165     if (VT == MVT::v8i16)
6166       Opc = X86ISD::PINSRW;
6167     else if (VT == MVT::v16i8)
6168       Opc = X86ISD::PINSRB;
6169     else
6170       Opc = X86ISD::PINSRB;
6171
6172     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6173     // argument.
6174     if (N1.getValueType() != MVT::i32)
6175       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6176     if (N2.getValueType() != MVT::i32)
6177       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6178     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6179   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6180     // Bits [7:6] of the constant are the source select.  This will always be
6181     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6182     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6183     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6184     // Bits [5:4] of the constant are the destination select.  This is the
6185     //  value of the incoming immediate.
6186     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6187     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6188     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6189     // Create this as a scalar to vector..
6190     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6191     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6192   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6193     // PINSR* works with constant index.
6194     return Op;
6195   }
6196   return SDValue();
6197 }
6198
6199 SDValue
6200 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6201   EVT VT = Op.getValueType();
6202   EVT EltVT = VT.getVectorElementType();
6203
6204   DebugLoc dl = Op.getDebugLoc();
6205   SDValue N0 = Op.getOperand(0);
6206   SDValue N1 = Op.getOperand(1);
6207   SDValue N2 = Op.getOperand(2);
6208
6209   // If this is a 256-bit vector result, first insert into a 128-bit
6210   // vector and then insert into the 256-bit vector.
6211   if (VT.getSizeInBits() > 128) {
6212     if (!isa<ConstantSDNode>(N2))
6213       return SDValue();
6214
6215     // Get the 128-bit vector.
6216     unsigned NumElems = VT.getVectorNumElements();
6217     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6218     bool Upper = IdxVal >= NumElems / 2;
6219
6220     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6221
6222     // Insert into it.
6223     SDValue ScaledN2 = N2;
6224     if (Upper)
6225       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6226                              DAG.getConstant(NumElems /
6227                                              (VT.getSizeInBits() / 128),
6228                                              N2.getValueType()));
6229     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6230                      N1, ScaledN2);
6231
6232     // Insert the 128-bit vector
6233     // FIXME: Why UNDEF?
6234     return Insert128BitVector(N0, Op, N2, DAG, dl);
6235   }
6236
6237   if (Subtarget->hasSSE41())
6238     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6239
6240   if (EltVT == MVT::i8)
6241     return SDValue();
6242
6243   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6244     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6245     // as its second argument.
6246     if (N1.getValueType() != MVT::i32)
6247       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6248     if (N2.getValueType() != MVT::i32)
6249       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6250     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6251   }
6252   return SDValue();
6253 }
6254
6255 SDValue
6256 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6257   LLVMContext *Context = DAG.getContext();
6258   DebugLoc dl = Op.getDebugLoc();
6259   EVT OpVT = Op.getValueType();
6260
6261   // If this is a 256-bit vector result, first insert into a 128-bit
6262   // vector and then insert into the 256-bit vector.
6263   if (OpVT.getSizeInBits() > 128) {
6264     // Insert into a 128-bit vector.
6265     EVT VT128 = EVT::getVectorVT(*Context,
6266                                  OpVT.getVectorElementType(),
6267                                  OpVT.getVectorNumElements() / 2);
6268
6269     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6270
6271     // Insert the 128-bit vector.
6272     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6273                               DAG.getConstant(0, MVT::i32),
6274                               DAG, dl);
6275   }
6276
6277   if (Op.getValueType() == MVT::v1i64 &&
6278       Op.getOperand(0).getValueType() == MVT::i64)
6279     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6280
6281   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6282   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6283          "Expected an SSE type!");
6284   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6285                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6286 }
6287
6288 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6289 // a simple subregister reference or explicit instructions to grab
6290 // upper bits of a vector.
6291 SDValue
6292 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6293   if (Subtarget->hasAVX()) {
6294     DebugLoc dl = Op.getNode()->getDebugLoc();
6295     SDValue Vec = Op.getNode()->getOperand(0);
6296     SDValue Idx = Op.getNode()->getOperand(1);
6297
6298     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6299         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6300         return Extract128BitVector(Vec, Idx, DAG, dl);
6301     }
6302   }
6303   return SDValue();
6304 }
6305
6306 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6307 // simple superregister reference or explicit instructions to insert
6308 // the upper bits of a vector.
6309 SDValue
6310 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6311   if (Subtarget->hasAVX()) {
6312     DebugLoc dl = Op.getNode()->getDebugLoc();
6313     SDValue Vec = Op.getNode()->getOperand(0);
6314     SDValue SubVec = Op.getNode()->getOperand(1);
6315     SDValue Idx = Op.getNode()->getOperand(2);
6316
6317     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6318         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6319       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6320     }
6321   }
6322   return SDValue();
6323 }
6324
6325 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6326 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6327 // one of the above mentioned nodes. It has to be wrapped because otherwise
6328 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6329 // be used to form addressing mode. These wrapped nodes will be selected
6330 // into MOV32ri.
6331 SDValue
6332 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6333   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(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.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6350                                              CP->getAlignment(),
6351                                              CP->getOffset(), OpFlag);
6352   DebugLoc DL = CP->getDebugLoc();
6353   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
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
6362   return Result;
6363 }
6364
6365 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6366   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
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.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6383                                           OpFlag);
6384   DebugLoc DL = JT->getDebugLoc();
6385   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6386
6387   // With PIC, the address is actually $g + Offset.
6388   if (OpFlag)
6389     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6390                          DAG.getNode(X86ISD::GlobalBaseReg,
6391                                      DebugLoc(), getPointerTy()),
6392                          Result);
6393
6394   return Result;
6395 }
6396
6397 SDValue
6398 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6399   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6400
6401   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6402   // global base reg.
6403   unsigned char OpFlag = 0;
6404   unsigned WrapperKind = X86ISD::Wrapper;
6405   CodeModel::Model M = getTargetMachine().getCodeModel();
6406
6407   if (Subtarget->isPICStyleRIPRel() &&
6408       (M == CodeModel::Small || M == CodeModel::Kernel))
6409     WrapperKind = X86ISD::WrapperRIP;
6410   else if (Subtarget->isPICStyleGOT())
6411     OpFlag = X86II::MO_GOTOFF;
6412   else if (Subtarget->isPICStyleStubPIC())
6413     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6414
6415   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6416
6417   DebugLoc DL = Op.getDebugLoc();
6418   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6419
6420
6421   // With PIC, the address is actually $g + Offset.
6422   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6423       !Subtarget->is64Bit()) {
6424     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6425                          DAG.getNode(X86ISD::GlobalBaseReg,
6426                                      DebugLoc(), getPointerTy()),
6427                          Result);
6428   }
6429
6430   return Result;
6431 }
6432
6433 SDValue
6434 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6435   // Create the TargetBlockAddressAddress node.
6436   unsigned char OpFlags =
6437     Subtarget->ClassifyBlockAddressReference();
6438   CodeModel::Model M = getTargetMachine().getCodeModel();
6439   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6440   DebugLoc dl = Op.getDebugLoc();
6441   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6442                                        /*isTarget=*/true, OpFlags);
6443
6444   if (Subtarget->isPICStyleRIPRel() &&
6445       (M == CodeModel::Small || M == CodeModel::Kernel))
6446     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6447   else
6448     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6449
6450   // With PIC, the address is actually $g + Offset.
6451   if (isGlobalRelativeToPICBase(OpFlags)) {
6452     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6453                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6454                          Result);
6455   }
6456
6457   return Result;
6458 }
6459
6460 SDValue
6461 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6462                                       int64_t Offset,
6463                                       SelectionDAG &DAG) const {
6464   // Create the TargetGlobalAddress node, folding in the constant
6465   // offset if it is legal.
6466   unsigned char OpFlags =
6467     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6468   CodeModel::Model M = getTargetMachine().getCodeModel();
6469   SDValue Result;
6470   if (OpFlags == X86II::MO_NO_FLAG &&
6471       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6472     // A direct static reference to a global.
6473     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6474     Offset = 0;
6475   } else {
6476     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6477   }
6478
6479   if (Subtarget->isPICStyleRIPRel() &&
6480       (M == CodeModel::Small || M == CodeModel::Kernel))
6481     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6482   else
6483     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6484
6485   // With PIC, the address is actually $g + Offset.
6486   if (isGlobalRelativeToPICBase(OpFlags)) {
6487     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6488                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6489                          Result);
6490   }
6491
6492   // For globals that require a load from a stub to get the address, emit the
6493   // load.
6494   if (isGlobalStubReference(OpFlags))
6495     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6496                          MachinePointerInfo::getGOT(), false, false, 0);
6497
6498   // If there was a non-zero offset that we didn't fold, create an explicit
6499   // addition for it.
6500   if (Offset != 0)
6501     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6502                          DAG.getConstant(Offset, getPointerTy()));
6503
6504   return Result;
6505 }
6506
6507 SDValue
6508 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6509   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6510   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6511   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6512 }
6513
6514 static SDValue
6515 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6516            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6517            unsigned char OperandFlags) {
6518   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6519   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6520   DebugLoc dl = GA->getDebugLoc();
6521   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6522                                            GA->getValueType(0),
6523                                            GA->getOffset(),
6524                                            OperandFlags);
6525   if (InFlag) {
6526     SDValue Ops[] = { Chain,  TGA, *InFlag };
6527     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6528   } else {
6529     SDValue Ops[]  = { Chain, TGA };
6530     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6531   }
6532
6533   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6534   MFI->setAdjustsStack(true);
6535
6536   SDValue Flag = Chain.getValue(1);
6537   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6538 }
6539
6540 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6541 static SDValue
6542 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6543                                 const EVT PtrVT) {
6544   SDValue InFlag;
6545   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6546   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6547                                      DAG.getNode(X86ISD::GlobalBaseReg,
6548                                                  DebugLoc(), PtrVT), InFlag);
6549   InFlag = Chain.getValue(1);
6550
6551   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6552 }
6553
6554 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6555 static SDValue
6556 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6557                                 const EVT PtrVT) {
6558   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6559                     X86::RAX, X86II::MO_TLSGD);
6560 }
6561
6562 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6563 // "local exec" model.
6564 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6565                                    const EVT PtrVT, TLSModel::Model model,
6566                                    bool is64Bit) {
6567   DebugLoc dl = GA->getDebugLoc();
6568
6569   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6570   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6571                                                          is64Bit ? 257 : 256));
6572
6573   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6574                                       DAG.getIntPtrConstant(0),
6575                                       MachinePointerInfo(Ptr), false, false, 0);
6576
6577   unsigned char OperandFlags = 0;
6578   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6579   // initialexec.
6580   unsigned WrapperKind = X86ISD::Wrapper;
6581   if (model == TLSModel::LocalExec) {
6582     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6583   } else if (is64Bit) {
6584     assert(model == TLSModel::InitialExec);
6585     OperandFlags = X86II::MO_GOTTPOFF;
6586     WrapperKind = X86ISD::WrapperRIP;
6587   } else {
6588     assert(model == TLSModel::InitialExec);
6589     OperandFlags = X86II::MO_INDNTPOFF;
6590   }
6591
6592   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6593   // exec)
6594   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6595                                            GA->getValueType(0),
6596                                            GA->getOffset(), OperandFlags);
6597   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6598
6599   if (model == TLSModel::InitialExec)
6600     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6601                          MachinePointerInfo::getGOT(), false, false, 0);
6602
6603   // The address of the thread local variable is the add of the thread
6604   // pointer with the offset of the variable.
6605   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6606 }
6607
6608 SDValue
6609 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6610
6611   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6612   const GlobalValue *GV = GA->getGlobal();
6613
6614   if (Subtarget->isTargetELF()) {
6615     // TODO: implement the "local dynamic" model
6616     // TODO: implement the "initial exec"model for pic executables
6617
6618     // If GV is an alias then use the aliasee for determining
6619     // thread-localness.
6620     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6621       GV = GA->resolveAliasedGlobal(false);
6622
6623     TLSModel::Model model
6624       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6625
6626     switch (model) {
6627       case TLSModel::GeneralDynamic:
6628       case TLSModel::LocalDynamic: // not implemented
6629         if (Subtarget->is64Bit())
6630           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6631         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6632
6633       case TLSModel::InitialExec:
6634       case TLSModel::LocalExec:
6635         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6636                                    Subtarget->is64Bit());
6637     }
6638   } else if (Subtarget->isTargetDarwin()) {
6639     // Darwin only has one model of TLS.  Lower to that.
6640     unsigned char OpFlag = 0;
6641     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6642                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6643
6644     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6645     // global base reg.
6646     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6647                   !Subtarget->is64Bit();
6648     if (PIC32)
6649       OpFlag = X86II::MO_TLVP_PIC_BASE;
6650     else
6651       OpFlag = X86II::MO_TLVP;
6652     DebugLoc DL = Op.getDebugLoc();
6653     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6654                                                 GA->getValueType(0),
6655                                                 GA->getOffset(), OpFlag);
6656     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6657
6658     // With PIC32, the address is actually $g + Offset.
6659     if (PIC32)
6660       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6661                            DAG.getNode(X86ISD::GlobalBaseReg,
6662                                        DebugLoc(), getPointerTy()),
6663                            Offset);
6664
6665     // Lowering the machine isd will make sure everything is in the right
6666     // location.
6667     SDValue Chain = DAG.getEntryNode();
6668     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6669     SDValue Args[] = { Chain, Offset };
6670     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6671
6672     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6673     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6674     MFI->setAdjustsStack(true);
6675
6676     // And our return value (tls address) is in the standard call return value
6677     // location.
6678     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6679     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6680   }
6681
6682   assert(false &&
6683          "TLS not implemented for this target.");
6684
6685   llvm_unreachable("Unreachable");
6686   return SDValue();
6687 }
6688
6689
6690 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6691 /// take a 2 x i32 value to shift plus a shift amount.
6692 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6693   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6694   EVT VT = Op.getValueType();
6695   unsigned VTBits = VT.getSizeInBits();
6696   DebugLoc dl = Op.getDebugLoc();
6697   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6698   SDValue ShOpLo = Op.getOperand(0);
6699   SDValue ShOpHi = Op.getOperand(1);
6700   SDValue ShAmt  = Op.getOperand(2);
6701   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6702                                      DAG.getConstant(VTBits - 1, MVT::i8))
6703                        : DAG.getConstant(0, VT);
6704
6705   SDValue Tmp2, Tmp3;
6706   if (Op.getOpcode() == ISD::SHL_PARTS) {
6707     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6708     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6709   } else {
6710     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6711     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6712   }
6713
6714   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6715                                 DAG.getConstant(VTBits, MVT::i8));
6716   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6717                              AndNode, DAG.getConstant(0, MVT::i8));
6718
6719   SDValue Hi, Lo;
6720   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6721   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6722   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6723
6724   if (Op.getOpcode() == ISD::SHL_PARTS) {
6725     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6726     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6727   } else {
6728     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6729     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6730   }
6731
6732   SDValue Ops[2] = { Lo, Hi };
6733   return DAG.getMergeValues(Ops, 2, dl);
6734 }
6735
6736 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6737                                            SelectionDAG &DAG) const {
6738   EVT SrcVT = Op.getOperand(0).getValueType();
6739
6740   if (SrcVT.isVector())
6741     return SDValue();
6742
6743   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6744          "Unknown SINT_TO_FP to lower!");
6745
6746   // These are really Legal; return the operand so the caller accepts it as
6747   // Legal.
6748   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6749     return Op;
6750   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6751       Subtarget->is64Bit()) {
6752     return Op;
6753   }
6754
6755   DebugLoc dl = Op.getDebugLoc();
6756   unsigned Size = SrcVT.getSizeInBits()/8;
6757   MachineFunction &MF = DAG.getMachineFunction();
6758   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6759   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6760   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6761                                StackSlot,
6762                                MachinePointerInfo::getFixedStack(SSFI),
6763                                false, false, 0);
6764   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6765 }
6766
6767 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6768                                      SDValue StackSlot,
6769                                      SelectionDAG &DAG) const {
6770   // Build the FILD
6771   DebugLoc DL = Op.getDebugLoc();
6772   SDVTList Tys;
6773   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6774   if (useSSE)
6775     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6776   else
6777     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6778
6779   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6780
6781   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6782   MachineMemOperand *MMO =
6783     DAG.getMachineFunction()
6784     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6785                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6786
6787   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6788   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6789                                            X86ISD::FILD, DL,
6790                                            Tys, Ops, array_lengthof(Ops),
6791                                            SrcVT, MMO);
6792
6793   if (useSSE) {
6794     Chain = Result.getValue(1);
6795     SDValue InFlag = Result.getValue(2);
6796
6797     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6798     // shouldn't be necessary except that RFP cannot be live across
6799     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6800     MachineFunction &MF = DAG.getMachineFunction();
6801     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6802     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6803     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6804     Tys = DAG.getVTList(MVT::Other);
6805     SDValue Ops[] = {
6806       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6807     };
6808     MachineMemOperand *MMO =
6809       DAG.getMachineFunction()
6810       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6811                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6812
6813     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6814                                     Ops, array_lengthof(Ops),
6815                                     Op.getValueType(), MMO);
6816     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6817                          MachinePointerInfo::getFixedStack(SSFI),
6818                          false, false, 0);
6819   }
6820
6821   return Result;
6822 }
6823
6824 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6825 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6826                                                SelectionDAG &DAG) const {
6827   // This algorithm is not obvious. Here it is in C code, more or less:
6828   /*
6829     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6830       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6831       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6832
6833       // Copy ints to xmm registers.
6834       __m128i xh = _mm_cvtsi32_si128( hi );
6835       __m128i xl = _mm_cvtsi32_si128( lo );
6836
6837       // Combine into low half of a single xmm register.
6838       __m128i x = _mm_unpacklo_epi32( xh, xl );
6839       __m128d d;
6840       double sd;
6841
6842       // Merge in appropriate exponents to give the integer bits the right
6843       // magnitude.
6844       x = _mm_unpacklo_epi32( x, exp );
6845
6846       // Subtract away the biases to deal with the IEEE-754 double precision
6847       // implicit 1.
6848       d = _mm_sub_pd( (__m128d) x, bias );
6849
6850       // All conversions up to here are exact. The correctly rounded result is
6851       // calculated using the current rounding mode using the following
6852       // horizontal add.
6853       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6854       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6855                                 // store doesn't really need to be here (except
6856                                 // maybe to zero the other double)
6857       return sd;
6858     }
6859   */
6860
6861   DebugLoc dl = Op.getDebugLoc();
6862   LLVMContext *Context = DAG.getContext();
6863
6864   // Build some magic constants.
6865   std::vector<Constant*> CV0;
6866   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6867   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6868   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6869   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6870   Constant *C0 = ConstantVector::get(CV0);
6871   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6872
6873   std::vector<Constant*> CV1;
6874   CV1.push_back(
6875     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6876   CV1.push_back(
6877     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6878   Constant *C1 = ConstantVector::get(CV1);
6879   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6880
6881   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6882                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6883                                         Op.getOperand(0),
6884                                         DAG.getIntPtrConstant(1)));
6885   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6886                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6887                                         Op.getOperand(0),
6888                                         DAG.getIntPtrConstant(0)));
6889   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6890   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6891                               MachinePointerInfo::getConstantPool(),
6892                               false, false, 16);
6893   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6894   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6895   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6896                               MachinePointerInfo::getConstantPool(),
6897                               false, false, 16);
6898   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6899
6900   // Add the halves; easiest way is to swap them into another reg first.
6901   int ShufMask[2] = { 1, -1 };
6902   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6903                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6904   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6905   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6906                      DAG.getIntPtrConstant(0));
6907 }
6908
6909 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6910 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6911                                                SelectionDAG &DAG) const {
6912   DebugLoc dl = Op.getDebugLoc();
6913   // FP constant to bias correct the final result.
6914   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6915                                    MVT::f64);
6916
6917   // Load the 32-bit value into an XMM register.
6918   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6919                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6920                                          Op.getOperand(0),
6921                                          DAG.getIntPtrConstant(0)));
6922
6923   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6924                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6925                      DAG.getIntPtrConstant(0));
6926
6927   // Or the load with the bias.
6928   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6929                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6930                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6931                                                    MVT::v2f64, Load)),
6932                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6933                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6934                                                    MVT::v2f64, Bias)));
6935   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6936                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6937                    DAG.getIntPtrConstant(0));
6938
6939   // Subtract the bias.
6940   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6941
6942   // Handle final rounding.
6943   EVT DestVT = Op.getValueType();
6944
6945   if (DestVT.bitsLT(MVT::f64)) {
6946     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6947                        DAG.getIntPtrConstant(0));
6948   } else if (DestVT.bitsGT(MVT::f64)) {
6949     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6950   }
6951
6952   // Handle final rounding.
6953   return Sub;
6954 }
6955
6956 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6957                                            SelectionDAG &DAG) const {
6958   SDValue N0 = Op.getOperand(0);
6959   DebugLoc dl = Op.getDebugLoc();
6960
6961   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6962   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6963   // the optimization here.
6964   if (DAG.SignBitIsZero(N0))
6965     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6966
6967   EVT SrcVT = N0.getValueType();
6968   EVT DstVT = Op.getValueType();
6969   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6970     return LowerUINT_TO_FP_i64(Op, DAG);
6971   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6972     return LowerUINT_TO_FP_i32(Op, DAG);
6973
6974   // Make a 64-bit buffer, and use it to build an FILD.
6975   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6976   if (SrcVT == MVT::i32) {
6977     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6978     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6979                                      getPointerTy(), StackSlot, WordOff);
6980     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6981                                   StackSlot, MachinePointerInfo(),
6982                                   false, false, 0);
6983     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6984                                   OffsetSlot, MachinePointerInfo(),
6985                                   false, false, 0);
6986     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6987     return Fild;
6988   }
6989
6990   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6991   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6992                                 StackSlot, MachinePointerInfo(),
6993                                false, false, 0);
6994   // For i64 source, we need to add the appropriate power of 2 if the input
6995   // was negative.  This is the same as the optimization in
6996   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6997   // we must be careful to do the computation in x87 extended precision, not
6998   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6999   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7000   MachineMemOperand *MMO =
7001     DAG.getMachineFunction()
7002     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7003                           MachineMemOperand::MOLoad, 8, 8);
7004
7005   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7006   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7007   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7008                                          MVT::i64, MMO);
7009
7010   APInt FF(32, 0x5F800000ULL);
7011
7012   // Check whether the sign bit is set.
7013   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7014                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7015                                  ISD::SETLT);
7016
7017   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7018   SDValue FudgePtr = DAG.getConstantPool(
7019                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7020                                          getPointerTy());
7021
7022   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7023   SDValue Zero = DAG.getIntPtrConstant(0);
7024   SDValue Four = DAG.getIntPtrConstant(4);
7025   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7026                                Zero, Four);
7027   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7028
7029   // Load the value out, extending it from f32 to f80.
7030   // FIXME: Avoid the extend by constructing the right constant pool?
7031   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7032                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7033                                  MVT::f32, false, false, 4);
7034   // Extend everything to 80 bits to force it to be done on x87.
7035   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7036   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7037 }
7038
7039 std::pair<SDValue,SDValue> X86TargetLowering::
7040 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7041   DebugLoc DL = Op.getDebugLoc();
7042
7043   EVT DstTy = Op.getValueType();
7044
7045   if (!IsSigned) {
7046     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7047     DstTy = MVT::i64;
7048   }
7049
7050   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7051          DstTy.getSimpleVT() >= MVT::i16 &&
7052          "Unknown FP_TO_SINT to lower!");
7053
7054   // These are really Legal.
7055   if (DstTy == MVT::i32 &&
7056       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7057     return std::make_pair(SDValue(), SDValue());
7058   if (Subtarget->is64Bit() &&
7059       DstTy == MVT::i64 &&
7060       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7061     return std::make_pair(SDValue(), SDValue());
7062
7063   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7064   // stack slot.
7065   MachineFunction &MF = DAG.getMachineFunction();
7066   unsigned MemSize = DstTy.getSizeInBits()/8;
7067   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7068   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7069
7070
7071
7072   unsigned Opc;
7073   switch (DstTy.getSimpleVT().SimpleTy) {
7074   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7075   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7076   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7077   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7078   }
7079
7080   SDValue Chain = DAG.getEntryNode();
7081   SDValue Value = Op.getOperand(0);
7082   EVT TheVT = Op.getOperand(0).getValueType();
7083   if (isScalarFPTypeInSSEReg(TheVT)) {
7084     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7085     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7086                          MachinePointerInfo::getFixedStack(SSFI),
7087                          false, false, 0);
7088     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7089     SDValue Ops[] = {
7090       Chain, StackSlot, DAG.getValueType(TheVT)
7091     };
7092
7093     MachineMemOperand *MMO =
7094       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7095                               MachineMemOperand::MOLoad, MemSize, MemSize);
7096     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7097                                     DstTy, MMO);
7098     Chain = Value.getValue(1);
7099     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7100     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7101   }
7102
7103   MachineMemOperand *MMO =
7104     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7105                             MachineMemOperand::MOStore, MemSize, MemSize);
7106
7107   // Build the FP_TO_INT*_IN_MEM
7108   SDValue Ops[] = { Chain, Value, StackSlot };
7109   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7110                                          Ops, 3, DstTy, MMO);
7111
7112   return std::make_pair(FIST, StackSlot);
7113 }
7114
7115 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7116                                            SelectionDAG &DAG) const {
7117   if (Op.getValueType().isVector())
7118     return SDValue();
7119
7120   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7121   SDValue FIST = Vals.first, StackSlot = Vals.second;
7122   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7123   if (FIST.getNode() == 0) return Op;
7124
7125   // Load the result.
7126   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7127                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7128 }
7129
7130 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7131                                            SelectionDAG &DAG) const {
7132   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7133   SDValue FIST = Vals.first, StackSlot = Vals.second;
7134   assert(FIST.getNode() && "Unexpected failure");
7135
7136   // Load the result.
7137   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7138                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7139 }
7140
7141 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7142                                      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   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7167 }
7168
7169 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7170   LLVMContext *Context = DAG.getContext();
7171   DebugLoc dl = Op.getDebugLoc();
7172   EVT VT = Op.getValueType();
7173   EVT EltVT = VT;
7174   if (VT.isVector())
7175     EltVT = VT.getVectorElementType();
7176   std::vector<Constant*> CV;
7177   if (EltVT == MVT::f64) {
7178     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7179     CV.push_back(C);
7180     CV.push_back(C);
7181   } else {
7182     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7183     CV.push_back(C);
7184     CV.push_back(C);
7185     CV.push_back(C);
7186     CV.push_back(C);
7187   }
7188   Constant *C = ConstantVector::get(CV);
7189   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7190   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7191                              MachinePointerInfo::getConstantPool(),
7192                              false, false, 16);
7193   if (VT.isVector()) {
7194     return DAG.getNode(ISD::BITCAST, dl, VT,
7195                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7196                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7197                                 Op.getOperand(0)),
7198                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7199   } else {
7200     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7201   }
7202 }
7203
7204 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7205   LLVMContext *Context = DAG.getContext();
7206   SDValue Op0 = Op.getOperand(0);
7207   SDValue Op1 = Op.getOperand(1);
7208   DebugLoc dl = Op.getDebugLoc();
7209   EVT VT = Op.getValueType();
7210   EVT SrcVT = Op1.getValueType();
7211
7212   // If second operand is smaller, extend it first.
7213   if (SrcVT.bitsLT(VT)) {
7214     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7215     SrcVT = VT;
7216   }
7217   // And if it is bigger, shrink it first.
7218   if (SrcVT.bitsGT(VT)) {
7219     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7220     SrcVT = VT;
7221   }
7222
7223   // At this point the operands and the result should have the same
7224   // type, and that won't be f80 since that is not custom lowered.
7225
7226   // First get the sign bit of second operand.
7227   std::vector<Constant*> CV;
7228   if (SrcVT == MVT::f64) {
7229     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7230     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7231   } else {
7232     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7233     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7234     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7235     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7236   }
7237   Constant *C = ConstantVector::get(CV);
7238   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7239   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7240                               MachinePointerInfo::getConstantPool(),
7241                               false, false, 16);
7242   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7243
7244   // Shift sign bit right or left if the two operands have different types.
7245   if (SrcVT.bitsGT(VT)) {
7246     // Op0 is MVT::f32, Op1 is MVT::f64.
7247     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7248     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7249                           DAG.getConstant(32, MVT::i32));
7250     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7251     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7252                           DAG.getIntPtrConstant(0));
7253   }
7254
7255   // Clear first operand sign bit.
7256   CV.clear();
7257   if (VT == MVT::f64) {
7258     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7259     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7260   } else {
7261     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7262     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7263     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7264     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7265   }
7266   C = ConstantVector::get(CV);
7267   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7268   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7269                               MachinePointerInfo::getConstantPool(),
7270                               false, false, 16);
7271   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7272
7273   // Or the value with the sign bit.
7274   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7275 }
7276
7277 /// Emit nodes that will be selected as "test Op0,Op0", or something
7278 /// equivalent.
7279 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7280                                     SelectionDAG &DAG) const {
7281   DebugLoc dl = Op.getDebugLoc();
7282
7283   // CF and OF aren't always set the way we want. Determine which
7284   // of these we need.
7285   bool NeedCF = false;
7286   bool NeedOF = false;
7287   switch (X86CC) {
7288   default: break;
7289   case X86::COND_A: case X86::COND_AE:
7290   case X86::COND_B: case X86::COND_BE:
7291     NeedCF = true;
7292     break;
7293   case X86::COND_G: case X86::COND_GE:
7294   case X86::COND_L: case X86::COND_LE:
7295   case X86::COND_O: case X86::COND_NO:
7296     NeedOF = true;
7297     break;
7298   }
7299
7300   // See if we can use the EFLAGS value from the operand instead of
7301   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7302   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7303   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7304     // Emit a CMP with 0, which is the TEST pattern.
7305     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7306                        DAG.getConstant(0, Op.getValueType()));
7307
7308   unsigned Opcode = 0;
7309   unsigned NumOperands = 0;
7310   switch (Op.getNode()->getOpcode()) {
7311   case ISD::ADD:
7312     // Due to an isel shortcoming, be conservative if this add is likely to be
7313     // selected as part of a load-modify-store instruction. When the root node
7314     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7315     // uses of other nodes in the match, such as the ADD in this case. This
7316     // leads to the ADD being left around and reselected, with the result being
7317     // two adds in the output.  Alas, even if none our users are stores, that
7318     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7319     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7320     // climbing the DAG back to the root, and it doesn't seem to be worth the
7321     // effort.
7322     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7323            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7324       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7325         goto default_case;
7326
7327     if (ConstantSDNode *C =
7328         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7329       // An add of one will be selected as an INC.
7330       if (C->getAPIntValue() == 1) {
7331         Opcode = X86ISD::INC;
7332         NumOperands = 1;
7333         break;
7334       }
7335
7336       // An add of negative one (subtract of one) will be selected as a DEC.
7337       if (C->getAPIntValue().isAllOnesValue()) {
7338         Opcode = X86ISD::DEC;
7339         NumOperands = 1;
7340         break;
7341       }
7342     }
7343
7344     // Otherwise use a regular EFLAGS-setting add.
7345     Opcode = X86ISD::ADD;
7346     NumOperands = 2;
7347     break;
7348   case ISD::AND: {
7349     // If the primary and result isn't used, don't bother using X86ISD::AND,
7350     // because a TEST instruction will be better.
7351     bool NonFlagUse = false;
7352     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7353            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7354       SDNode *User = *UI;
7355       unsigned UOpNo = UI.getOperandNo();
7356       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7357         // Look pass truncate.
7358         UOpNo = User->use_begin().getOperandNo();
7359         User = *User->use_begin();
7360       }
7361
7362       if (User->getOpcode() != ISD::BRCOND &&
7363           User->getOpcode() != ISD::SETCC &&
7364           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7365         NonFlagUse = true;
7366         break;
7367       }
7368     }
7369
7370     if (!NonFlagUse)
7371       break;
7372   }
7373     // FALL THROUGH
7374   case ISD::SUB:
7375   case ISD::OR:
7376   case ISD::XOR:
7377     // Due to the ISEL shortcoming noted above, be conservative if this op is
7378     // likely to be selected as part of a load-modify-store instruction.
7379     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7380            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7381       if (UI->getOpcode() == ISD::STORE)
7382         goto default_case;
7383
7384     // Otherwise use a regular EFLAGS-setting instruction.
7385     switch (Op.getNode()->getOpcode()) {
7386     default: llvm_unreachable("unexpected operator!");
7387     case ISD::SUB: Opcode = X86ISD::SUB; break;
7388     case ISD::OR:  Opcode = X86ISD::OR;  break;
7389     case ISD::XOR: Opcode = X86ISD::XOR; break;
7390     case ISD::AND: Opcode = X86ISD::AND; break;
7391     }
7392
7393     NumOperands = 2;
7394     break;
7395   case X86ISD::ADD:
7396   case X86ISD::SUB:
7397   case X86ISD::INC:
7398   case X86ISD::DEC:
7399   case X86ISD::OR:
7400   case X86ISD::XOR:
7401   case X86ISD::AND:
7402     return SDValue(Op.getNode(), 1);
7403   default:
7404   default_case:
7405     break;
7406   }
7407
7408   if (Opcode == 0)
7409     // Emit a CMP with 0, which is the TEST pattern.
7410     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7411                        DAG.getConstant(0, Op.getValueType()));
7412
7413   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7414   SmallVector<SDValue, 4> Ops;
7415   for (unsigned i = 0; i != NumOperands; ++i)
7416     Ops.push_back(Op.getOperand(i));
7417
7418   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7419   DAG.ReplaceAllUsesWith(Op, New);
7420   return SDValue(New.getNode(), 1);
7421 }
7422
7423 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7424 /// equivalent.
7425 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7426                                    SelectionDAG &DAG) const {
7427   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7428     if (C->getAPIntValue() == 0)
7429       return EmitTest(Op0, X86CC, DAG);
7430
7431   DebugLoc dl = Op0.getDebugLoc();
7432   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7433 }
7434
7435 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7436 /// if it's possible.
7437 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7438                                      DebugLoc dl, SelectionDAG &DAG) const {
7439   SDValue Op0 = And.getOperand(0);
7440   SDValue Op1 = And.getOperand(1);
7441   if (Op0.getOpcode() == ISD::TRUNCATE)
7442     Op0 = Op0.getOperand(0);
7443   if (Op1.getOpcode() == ISD::TRUNCATE)
7444     Op1 = Op1.getOperand(0);
7445
7446   SDValue LHS, RHS;
7447   if (Op1.getOpcode() == ISD::SHL)
7448     std::swap(Op0, Op1);
7449   if (Op0.getOpcode() == ISD::SHL) {
7450     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7451       if (And00C->getZExtValue() == 1) {
7452         // If we looked past a truncate, check that it's only truncating away
7453         // known zeros.
7454         unsigned BitWidth = Op0.getValueSizeInBits();
7455         unsigned AndBitWidth = And.getValueSizeInBits();
7456         if (BitWidth > AndBitWidth) {
7457           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7458           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7459           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7460             return SDValue();
7461         }
7462         LHS = Op1;
7463         RHS = Op0.getOperand(1);
7464       }
7465   } else if (Op1.getOpcode() == ISD::Constant) {
7466     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7467     SDValue AndLHS = Op0;
7468     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7469       LHS = AndLHS.getOperand(0);
7470       RHS = AndLHS.getOperand(1);
7471     }
7472   }
7473
7474   if (LHS.getNode()) {
7475     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7476     // instruction.  Since the shift amount is in-range-or-undefined, we know
7477     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7478     // the encoding for the i16 version is larger than the i32 version.
7479     // Also promote i16 to i32 for performance / code size reason.
7480     if (LHS.getValueType() == MVT::i8 ||
7481         LHS.getValueType() == MVT::i16)
7482       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7483
7484     // If the operand types disagree, extend the shift amount to match.  Since
7485     // BT ignores high bits (like shifts) we can use anyextend.
7486     if (LHS.getValueType() != RHS.getValueType())
7487       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7488
7489     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7490     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7491     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7492                        DAG.getConstant(Cond, MVT::i8), BT);
7493   }
7494
7495   return SDValue();
7496 }
7497
7498 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7499   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7500   SDValue Op0 = Op.getOperand(0);
7501   SDValue Op1 = Op.getOperand(1);
7502   DebugLoc dl = Op.getDebugLoc();
7503   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7504
7505   // Optimize to BT if possible.
7506   // Lower (X & (1 << N)) == 0 to BT(X, N).
7507   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7508   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7509   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7510       Op1.getOpcode() == ISD::Constant &&
7511       cast<ConstantSDNode>(Op1)->isNullValue() &&
7512       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7513     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7514     if (NewSetCC.getNode())
7515       return NewSetCC;
7516   }
7517
7518   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7519   // these.
7520   if (Op1.getOpcode() == ISD::Constant &&
7521       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7522        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7523       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7524
7525     // If the input is a setcc, then reuse the input setcc or use a new one with
7526     // the inverted condition.
7527     if (Op0.getOpcode() == X86ISD::SETCC) {
7528       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7529       bool Invert = (CC == ISD::SETNE) ^
7530         cast<ConstantSDNode>(Op1)->isNullValue();
7531       if (!Invert) return Op0;
7532
7533       CCode = X86::GetOppositeBranchCondition(CCode);
7534       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7535                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7536     }
7537   }
7538
7539   bool isFP = Op1.getValueType().isFloatingPoint();
7540   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7541   if (X86CC == X86::COND_INVALID)
7542     return SDValue();
7543
7544   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7545   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7546                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7547 }
7548
7549 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7550   SDValue Cond;
7551   SDValue Op0 = Op.getOperand(0);
7552   SDValue Op1 = Op.getOperand(1);
7553   SDValue CC = Op.getOperand(2);
7554   EVT VT = Op.getValueType();
7555   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7556   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7557   DebugLoc dl = Op.getDebugLoc();
7558
7559   if (isFP) {
7560     unsigned SSECC = 8;
7561     EVT VT0 = Op0.getValueType();
7562     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7563     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7564     bool Swap = false;
7565
7566     switch (SetCCOpcode) {
7567     default: break;
7568     case ISD::SETOEQ:
7569     case ISD::SETEQ:  SSECC = 0; break;
7570     case ISD::SETOGT:
7571     case ISD::SETGT: Swap = true; // Fallthrough
7572     case ISD::SETLT:
7573     case ISD::SETOLT: SSECC = 1; break;
7574     case ISD::SETOGE:
7575     case ISD::SETGE: Swap = true; // Fallthrough
7576     case ISD::SETLE:
7577     case ISD::SETOLE: SSECC = 2; break;
7578     case ISD::SETUO:  SSECC = 3; break;
7579     case ISD::SETUNE:
7580     case ISD::SETNE:  SSECC = 4; break;
7581     case ISD::SETULE: Swap = true;
7582     case ISD::SETUGE: SSECC = 5; break;
7583     case ISD::SETULT: Swap = true;
7584     case ISD::SETUGT: SSECC = 6; break;
7585     case ISD::SETO:   SSECC = 7; break;
7586     }
7587     if (Swap)
7588       std::swap(Op0, Op1);
7589
7590     // In the two special cases we can't handle, emit two comparisons.
7591     if (SSECC == 8) {
7592       if (SetCCOpcode == ISD::SETUEQ) {
7593         SDValue UNORD, EQ;
7594         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7595         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7596         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7597       }
7598       else if (SetCCOpcode == ISD::SETONE) {
7599         SDValue ORD, NEQ;
7600         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7601         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7602         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7603       }
7604       llvm_unreachable("Illegal FP comparison");
7605     }
7606     // Handle all other FP comparisons here.
7607     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7608   }
7609
7610   // We are handling one of the integer comparisons here.  Since SSE only has
7611   // GT and EQ comparisons for integer, swapping operands and multiple
7612   // operations may be required for some comparisons.
7613   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7614   bool Swap = false, Invert = false, FlipSigns = false;
7615
7616   switch (VT.getSimpleVT().SimpleTy) {
7617   default: break;
7618   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7619   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7620   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7621   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7622   }
7623
7624   switch (SetCCOpcode) {
7625   default: break;
7626   case ISD::SETNE:  Invert = true;
7627   case ISD::SETEQ:  Opc = EQOpc; break;
7628   case ISD::SETLT:  Swap = true;
7629   case ISD::SETGT:  Opc = GTOpc; break;
7630   case ISD::SETGE:  Swap = true;
7631   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7632   case ISD::SETULT: Swap = true;
7633   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7634   case ISD::SETUGE: Swap = true;
7635   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7636   }
7637   if (Swap)
7638     std::swap(Op0, Op1);
7639
7640   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7641   // bits of the inputs before performing those operations.
7642   if (FlipSigns) {
7643     EVT EltVT = VT.getVectorElementType();
7644     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7645                                       EltVT);
7646     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7647     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7648                                     SignBits.size());
7649     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7650     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7651   }
7652
7653   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7654
7655   // If the logical-not of the result is required, perform that now.
7656   if (Invert)
7657     Result = DAG.getNOT(dl, Result, VT);
7658
7659   return Result;
7660 }
7661
7662 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7663 static bool isX86LogicalCmp(SDValue Op) {
7664   unsigned Opc = Op.getNode()->getOpcode();
7665   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7666     return true;
7667   if (Op.getResNo() == 1 &&
7668       (Opc == X86ISD::ADD ||
7669        Opc == X86ISD::SUB ||
7670        Opc == X86ISD::ADC ||
7671        Opc == X86ISD::SBB ||
7672        Opc == X86ISD::SMUL ||
7673        Opc == X86ISD::UMUL ||
7674        Opc == X86ISD::INC ||
7675        Opc == X86ISD::DEC ||
7676        Opc == X86ISD::OR ||
7677        Opc == X86ISD::XOR ||
7678        Opc == X86ISD::AND))
7679     return true;
7680
7681   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7682     return true;
7683
7684   return false;
7685 }
7686
7687 static bool isZero(SDValue V) {
7688   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7689   return C && C->isNullValue();
7690 }
7691
7692 static bool isAllOnes(SDValue V) {
7693   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7694   return C && C->isAllOnesValue();
7695 }
7696
7697 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7698   bool addTest = true;
7699   SDValue Cond  = Op.getOperand(0);
7700   SDValue Op1 = Op.getOperand(1);
7701   SDValue Op2 = Op.getOperand(2);
7702   DebugLoc DL = Op.getDebugLoc();
7703   SDValue CC;
7704
7705   if (Cond.getOpcode() == ISD::SETCC) {
7706     SDValue NewCond = LowerSETCC(Cond, DAG);
7707     if (NewCond.getNode())
7708       Cond = NewCond;
7709   }
7710
7711   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7712   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7713   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7714   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7715   if (Cond.getOpcode() == X86ISD::SETCC &&
7716       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7717       isZero(Cond.getOperand(1).getOperand(1))) {
7718     SDValue Cmp = Cond.getOperand(1);
7719
7720     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7721
7722     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7723         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7724       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7725
7726       SDValue CmpOp0 = Cmp.getOperand(0);
7727       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7728                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7729
7730       SDValue Res =   // Res = 0 or -1.
7731         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7732                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7733
7734       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7735         Res = DAG.getNOT(DL, Res, Res.getValueType());
7736
7737       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7738       if (N2C == 0 || !N2C->isNullValue())
7739         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7740       return Res;
7741     }
7742   }
7743
7744   // Look past (and (setcc_carry (cmp ...)), 1).
7745   if (Cond.getOpcode() == ISD::AND &&
7746       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7747     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7748     if (C && C->getAPIntValue() == 1)
7749       Cond = Cond.getOperand(0);
7750   }
7751
7752   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7753   // setting operand in place of the X86ISD::SETCC.
7754   if (Cond.getOpcode() == X86ISD::SETCC ||
7755       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7756     CC = Cond.getOperand(0);
7757
7758     SDValue Cmp = Cond.getOperand(1);
7759     unsigned Opc = Cmp.getOpcode();
7760     EVT VT = Op.getValueType();
7761
7762     bool IllegalFPCMov = false;
7763     if (VT.isFloatingPoint() && !VT.isVector() &&
7764         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7765       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7766
7767     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7768         Opc == X86ISD::BT) { // FIXME
7769       Cond = Cmp;
7770       addTest = false;
7771     }
7772   }
7773
7774   if (addTest) {
7775     // Look pass the truncate.
7776     if (Cond.getOpcode() == ISD::TRUNCATE)
7777       Cond = Cond.getOperand(0);
7778
7779     // We know the result of AND is compared against zero. Try to match
7780     // it to BT.
7781     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7782       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7783       if (NewSetCC.getNode()) {
7784         CC = NewSetCC.getOperand(0);
7785         Cond = NewSetCC.getOperand(1);
7786         addTest = false;
7787       }
7788     }
7789   }
7790
7791   if (addTest) {
7792     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7793     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7794   }
7795
7796   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7797   // a <  b ?  0 : -1 -> RES = setcc_carry
7798   // a >= b ? -1 :  0 -> RES = setcc_carry
7799   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7800   if (Cond.getOpcode() == X86ISD::CMP) {
7801     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7802
7803     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7804         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7805       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7806                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7807       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7808         return DAG.getNOT(DL, Res, Res.getValueType());
7809       return Res;
7810     }
7811   }
7812
7813   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7814   // condition is true.
7815   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7816   SDValue Ops[] = { Op2, Op1, CC, Cond };
7817   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7818 }
7819
7820 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7821 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7822 // from the AND / OR.
7823 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7824   Opc = Op.getOpcode();
7825   if (Opc != ISD::OR && Opc != ISD::AND)
7826     return false;
7827   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7828           Op.getOperand(0).hasOneUse() &&
7829           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7830           Op.getOperand(1).hasOneUse());
7831 }
7832
7833 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7834 // 1 and that the SETCC node has a single use.
7835 static bool isXor1OfSetCC(SDValue Op) {
7836   if (Op.getOpcode() != ISD::XOR)
7837     return false;
7838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7839   if (N1C && N1C->getAPIntValue() == 1) {
7840     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7841       Op.getOperand(0).hasOneUse();
7842   }
7843   return false;
7844 }
7845
7846 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7847   bool addTest = true;
7848   SDValue Chain = Op.getOperand(0);
7849   SDValue Cond  = Op.getOperand(1);
7850   SDValue Dest  = Op.getOperand(2);
7851   DebugLoc dl = Op.getDebugLoc();
7852   SDValue CC;
7853
7854   if (Cond.getOpcode() == ISD::SETCC) {
7855     SDValue NewCond = LowerSETCC(Cond, DAG);
7856     if (NewCond.getNode())
7857       Cond = NewCond;
7858   }
7859 #if 0
7860   // FIXME: LowerXALUO doesn't handle these!!
7861   else if (Cond.getOpcode() == X86ISD::ADD  ||
7862            Cond.getOpcode() == X86ISD::SUB  ||
7863            Cond.getOpcode() == X86ISD::SMUL ||
7864            Cond.getOpcode() == X86ISD::UMUL)
7865     Cond = LowerXALUO(Cond, DAG);
7866 #endif
7867
7868   // Look pass (and (setcc_carry (cmp ...)), 1).
7869   if (Cond.getOpcode() == ISD::AND &&
7870       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7871     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7872     if (C && C->getAPIntValue() == 1)
7873       Cond = Cond.getOperand(0);
7874   }
7875
7876   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7877   // setting operand in place of the X86ISD::SETCC.
7878   if (Cond.getOpcode() == X86ISD::SETCC ||
7879       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7880     CC = Cond.getOperand(0);
7881
7882     SDValue Cmp = Cond.getOperand(1);
7883     unsigned Opc = Cmp.getOpcode();
7884     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7885     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7886       Cond = Cmp;
7887       addTest = false;
7888     } else {
7889       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7890       default: break;
7891       case X86::COND_O:
7892       case X86::COND_B:
7893         // These can only come from an arithmetic instruction with overflow,
7894         // e.g. SADDO, UADDO.
7895         Cond = Cond.getNode()->getOperand(1);
7896         addTest = false;
7897         break;
7898       }
7899     }
7900   } else {
7901     unsigned CondOpc;
7902     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7903       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7904       if (CondOpc == ISD::OR) {
7905         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7906         // two branches instead of an explicit OR instruction with a
7907         // separate test.
7908         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7909             isX86LogicalCmp(Cmp)) {
7910           CC = Cond.getOperand(0).getOperand(0);
7911           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7912                               Chain, Dest, CC, Cmp);
7913           CC = Cond.getOperand(1).getOperand(0);
7914           Cond = Cmp;
7915           addTest = false;
7916         }
7917       } else { // ISD::AND
7918         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7919         // two branches instead of an explicit AND instruction with a
7920         // separate test. However, we only do this if this block doesn't
7921         // have a fall-through edge, because this requires an explicit
7922         // jmp when the condition is false.
7923         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7924             isX86LogicalCmp(Cmp) &&
7925             Op.getNode()->hasOneUse()) {
7926           X86::CondCode CCode =
7927             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7928           CCode = X86::GetOppositeBranchCondition(CCode);
7929           CC = DAG.getConstant(CCode, MVT::i8);
7930           SDNode *User = *Op.getNode()->use_begin();
7931           // Look for an unconditional branch following this conditional branch.
7932           // We need this because we need to reverse the successors in order
7933           // to implement FCMP_OEQ.
7934           if (User->getOpcode() == ISD::BR) {
7935             SDValue FalseBB = User->getOperand(1);
7936             SDNode *NewBR =
7937               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7938             assert(NewBR == User);
7939             (void)NewBR;
7940             Dest = FalseBB;
7941
7942             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7943                                 Chain, Dest, CC, Cmp);
7944             X86::CondCode CCode =
7945               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7946             CCode = X86::GetOppositeBranchCondition(CCode);
7947             CC = DAG.getConstant(CCode, MVT::i8);
7948             Cond = Cmp;
7949             addTest = false;
7950           }
7951         }
7952       }
7953     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7954       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7955       // It should be transformed during dag combiner except when the condition
7956       // is set by a arithmetics with overflow node.
7957       X86::CondCode CCode =
7958         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7959       CCode = X86::GetOppositeBranchCondition(CCode);
7960       CC = DAG.getConstant(CCode, MVT::i8);
7961       Cond = Cond.getOperand(0).getOperand(1);
7962       addTest = false;
7963     }
7964   }
7965
7966   if (addTest) {
7967     // Look pass the truncate.
7968     if (Cond.getOpcode() == ISD::TRUNCATE)
7969       Cond = Cond.getOperand(0);
7970
7971     // We know the result of AND is compared against zero. Try to match
7972     // it to BT.
7973     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7974       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7975       if (NewSetCC.getNode()) {
7976         CC = NewSetCC.getOperand(0);
7977         Cond = NewSetCC.getOperand(1);
7978         addTest = false;
7979       }
7980     }
7981   }
7982
7983   if (addTest) {
7984     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7985     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7986   }
7987   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7988                      Chain, Dest, CC, Cond);
7989 }
7990
7991
7992 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7993 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7994 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7995 // that the guard pages used by the OS virtual memory manager are allocated in
7996 // correct sequence.
7997 SDValue
7998 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7999                                            SelectionDAG &DAG) const {
8000   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8001          "This should be used only on Windows targets");
8002   assert(!Subtarget->isTargetEnvMacho());
8003   DebugLoc dl = Op.getDebugLoc();
8004
8005   // Get the inputs.
8006   SDValue Chain = Op.getOperand(0);
8007   SDValue Size  = Op.getOperand(1);
8008   // FIXME: Ensure alignment here
8009
8010   SDValue Flag;
8011
8012   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8013   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8014
8015   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8016   Flag = Chain.getValue(1);
8017
8018   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8019
8020   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8021   Flag = Chain.getValue(1);
8022
8023   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8024
8025   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8026   return DAG.getMergeValues(Ops1, 2, dl);
8027 }
8028
8029 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8030   MachineFunction &MF = DAG.getMachineFunction();
8031   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8032
8033   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8034   DebugLoc DL = Op.getDebugLoc();
8035
8036   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8037     // vastart just stores the address of the VarArgsFrameIndex slot into the
8038     // memory location argument.
8039     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8040                                    getPointerTy());
8041     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8042                         MachinePointerInfo(SV), false, false, 0);
8043   }
8044
8045   // __va_list_tag:
8046   //   gp_offset         (0 - 6 * 8)
8047   //   fp_offset         (48 - 48 + 8 * 16)
8048   //   overflow_arg_area (point to parameters coming in memory).
8049   //   reg_save_area
8050   SmallVector<SDValue, 8> MemOps;
8051   SDValue FIN = Op.getOperand(1);
8052   // Store gp_offset
8053   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8054                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8055                                                MVT::i32),
8056                                FIN, MachinePointerInfo(SV), false, false, 0);
8057   MemOps.push_back(Store);
8058
8059   // Store fp_offset
8060   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8061                     FIN, DAG.getIntPtrConstant(4));
8062   Store = DAG.getStore(Op.getOperand(0), DL,
8063                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8064                                        MVT::i32),
8065                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8066   MemOps.push_back(Store);
8067
8068   // Store ptr to overflow_arg_area
8069   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8070                     FIN, DAG.getIntPtrConstant(4));
8071   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8072                                     getPointerTy());
8073   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8074                        MachinePointerInfo(SV, 8),
8075                        false, false, 0);
8076   MemOps.push_back(Store);
8077
8078   // Store ptr to reg_save_area.
8079   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8080                     FIN, DAG.getIntPtrConstant(8));
8081   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8082                                     getPointerTy());
8083   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8084                        MachinePointerInfo(SV, 16), false, false, 0);
8085   MemOps.push_back(Store);
8086   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8087                      &MemOps[0], MemOps.size());
8088 }
8089
8090 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8091   assert(Subtarget->is64Bit() &&
8092          "LowerVAARG only handles 64-bit va_arg!");
8093   assert((Subtarget->isTargetLinux() ||
8094           Subtarget->isTargetDarwin()) &&
8095           "Unhandled target in LowerVAARG");
8096   assert(Op.getNode()->getNumOperands() == 4);
8097   SDValue Chain = Op.getOperand(0);
8098   SDValue SrcPtr = Op.getOperand(1);
8099   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8100   unsigned Align = Op.getConstantOperandVal(3);
8101   DebugLoc dl = Op.getDebugLoc();
8102
8103   EVT ArgVT = Op.getNode()->getValueType(0);
8104   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8105   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8106   uint8_t ArgMode;
8107
8108   // Decide which area this value should be read from.
8109   // TODO: Implement the AMD64 ABI in its entirety. This simple
8110   // selection mechanism works only for the basic types.
8111   if (ArgVT == MVT::f80) {
8112     llvm_unreachable("va_arg for f80 not yet implemented");
8113   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8114     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8115   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8116     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8117   } else {
8118     llvm_unreachable("Unhandled argument type in LowerVAARG");
8119   }
8120
8121   if (ArgMode == 2) {
8122     // Sanity Check: Make sure using fp_offset makes sense.
8123     assert(!UseSoftFloat &&
8124            !(DAG.getMachineFunction()
8125                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8126            Subtarget->hasXMM());
8127   }
8128
8129   // Insert VAARG_64 node into the DAG
8130   // VAARG_64 returns two values: Variable Argument Address, Chain
8131   SmallVector<SDValue, 11> InstOps;
8132   InstOps.push_back(Chain);
8133   InstOps.push_back(SrcPtr);
8134   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8135   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8136   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8137   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8138   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8139                                           VTs, &InstOps[0], InstOps.size(),
8140                                           MVT::i64,
8141                                           MachinePointerInfo(SV),
8142                                           /*Align=*/0,
8143                                           /*Volatile=*/false,
8144                                           /*ReadMem=*/true,
8145                                           /*WriteMem=*/true);
8146   Chain = VAARG.getValue(1);
8147
8148   // Load the next argument and return it
8149   return DAG.getLoad(ArgVT, dl,
8150                      Chain,
8151                      VAARG,
8152                      MachinePointerInfo(),
8153                      false, false, 0);
8154 }
8155
8156 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8157   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8158   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8159   SDValue Chain = Op.getOperand(0);
8160   SDValue DstPtr = Op.getOperand(1);
8161   SDValue SrcPtr = Op.getOperand(2);
8162   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8163   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8164   DebugLoc DL = Op.getDebugLoc();
8165
8166   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8167                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8168                        false,
8169                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8170 }
8171
8172 SDValue
8173 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8174   DebugLoc dl = Op.getDebugLoc();
8175   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8176   switch (IntNo) {
8177   default: return SDValue();    // Don't custom lower most intrinsics.
8178   // Comparison intrinsics.
8179   case Intrinsic::x86_sse_comieq_ss:
8180   case Intrinsic::x86_sse_comilt_ss:
8181   case Intrinsic::x86_sse_comile_ss:
8182   case Intrinsic::x86_sse_comigt_ss:
8183   case Intrinsic::x86_sse_comige_ss:
8184   case Intrinsic::x86_sse_comineq_ss:
8185   case Intrinsic::x86_sse_ucomieq_ss:
8186   case Intrinsic::x86_sse_ucomilt_ss:
8187   case Intrinsic::x86_sse_ucomile_ss:
8188   case Intrinsic::x86_sse_ucomigt_ss:
8189   case Intrinsic::x86_sse_ucomige_ss:
8190   case Intrinsic::x86_sse_ucomineq_ss:
8191   case Intrinsic::x86_sse2_comieq_sd:
8192   case Intrinsic::x86_sse2_comilt_sd:
8193   case Intrinsic::x86_sse2_comile_sd:
8194   case Intrinsic::x86_sse2_comigt_sd:
8195   case Intrinsic::x86_sse2_comige_sd:
8196   case Intrinsic::x86_sse2_comineq_sd:
8197   case Intrinsic::x86_sse2_ucomieq_sd:
8198   case Intrinsic::x86_sse2_ucomilt_sd:
8199   case Intrinsic::x86_sse2_ucomile_sd:
8200   case Intrinsic::x86_sse2_ucomigt_sd:
8201   case Intrinsic::x86_sse2_ucomige_sd:
8202   case Intrinsic::x86_sse2_ucomineq_sd: {
8203     unsigned Opc = 0;
8204     ISD::CondCode CC = ISD::SETCC_INVALID;
8205     switch (IntNo) {
8206     default: break;
8207     case Intrinsic::x86_sse_comieq_ss:
8208     case Intrinsic::x86_sse2_comieq_sd:
8209       Opc = X86ISD::COMI;
8210       CC = ISD::SETEQ;
8211       break;
8212     case Intrinsic::x86_sse_comilt_ss:
8213     case Intrinsic::x86_sse2_comilt_sd:
8214       Opc = X86ISD::COMI;
8215       CC = ISD::SETLT;
8216       break;
8217     case Intrinsic::x86_sse_comile_ss:
8218     case Intrinsic::x86_sse2_comile_sd:
8219       Opc = X86ISD::COMI;
8220       CC = ISD::SETLE;
8221       break;
8222     case Intrinsic::x86_sse_comigt_ss:
8223     case Intrinsic::x86_sse2_comigt_sd:
8224       Opc = X86ISD::COMI;
8225       CC = ISD::SETGT;
8226       break;
8227     case Intrinsic::x86_sse_comige_ss:
8228     case Intrinsic::x86_sse2_comige_sd:
8229       Opc = X86ISD::COMI;
8230       CC = ISD::SETGE;
8231       break;
8232     case Intrinsic::x86_sse_comineq_ss:
8233     case Intrinsic::x86_sse2_comineq_sd:
8234       Opc = X86ISD::COMI;
8235       CC = ISD::SETNE;
8236       break;
8237     case Intrinsic::x86_sse_ucomieq_ss:
8238     case Intrinsic::x86_sse2_ucomieq_sd:
8239       Opc = X86ISD::UCOMI;
8240       CC = ISD::SETEQ;
8241       break;
8242     case Intrinsic::x86_sse_ucomilt_ss:
8243     case Intrinsic::x86_sse2_ucomilt_sd:
8244       Opc = X86ISD::UCOMI;
8245       CC = ISD::SETLT;
8246       break;
8247     case Intrinsic::x86_sse_ucomile_ss:
8248     case Intrinsic::x86_sse2_ucomile_sd:
8249       Opc = X86ISD::UCOMI;
8250       CC = ISD::SETLE;
8251       break;
8252     case Intrinsic::x86_sse_ucomigt_ss:
8253     case Intrinsic::x86_sse2_ucomigt_sd:
8254       Opc = X86ISD::UCOMI;
8255       CC = ISD::SETGT;
8256       break;
8257     case Intrinsic::x86_sse_ucomige_ss:
8258     case Intrinsic::x86_sse2_ucomige_sd:
8259       Opc = X86ISD::UCOMI;
8260       CC = ISD::SETGE;
8261       break;
8262     case Intrinsic::x86_sse_ucomineq_ss:
8263     case Intrinsic::x86_sse2_ucomineq_sd:
8264       Opc = X86ISD::UCOMI;
8265       CC = ISD::SETNE;
8266       break;
8267     }
8268
8269     SDValue LHS = Op.getOperand(1);
8270     SDValue RHS = Op.getOperand(2);
8271     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8272     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8273     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8274     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8275                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8276     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8277   }
8278   // ptest and testp intrinsics. The intrinsic these come from are designed to
8279   // return an integer value, not just an instruction so lower it to the ptest
8280   // or testp pattern and a setcc for the result.
8281   case Intrinsic::x86_sse41_ptestz:
8282   case Intrinsic::x86_sse41_ptestc:
8283   case Intrinsic::x86_sse41_ptestnzc:
8284   case Intrinsic::x86_avx_ptestz_256:
8285   case Intrinsic::x86_avx_ptestc_256:
8286   case Intrinsic::x86_avx_ptestnzc_256:
8287   case Intrinsic::x86_avx_vtestz_ps:
8288   case Intrinsic::x86_avx_vtestc_ps:
8289   case Intrinsic::x86_avx_vtestnzc_ps:
8290   case Intrinsic::x86_avx_vtestz_pd:
8291   case Intrinsic::x86_avx_vtestc_pd:
8292   case Intrinsic::x86_avx_vtestnzc_pd:
8293   case Intrinsic::x86_avx_vtestz_ps_256:
8294   case Intrinsic::x86_avx_vtestc_ps_256:
8295   case Intrinsic::x86_avx_vtestnzc_ps_256:
8296   case Intrinsic::x86_avx_vtestz_pd_256:
8297   case Intrinsic::x86_avx_vtestc_pd_256:
8298   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8299     bool IsTestPacked = false;
8300     unsigned X86CC = 0;
8301     switch (IntNo) {
8302     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8303     case Intrinsic::x86_avx_vtestz_ps:
8304     case Intrinsic::x86_avx_vtestz_pd:
8305     case Intrinsic::x86_avx_vtestz_ps_256:
8306     case Intrinsic::x86_avx_vtestz_pd_256:
8307       IsTestPacked = true; // Fallthrough
8308     case Intrinsic::x86_sse41_ptestz:
8309     case Intrinsic::x86_avx_ptestz_256:
8310       // ZF = 1
8311       X86CC = X86::COND_E;
8312       break;
8313     case Intrinsic::x86_avx_vtestc_ps:
8314     case Intrinsic::x86_avx_vtestc_pd:
8315     case Intrinsic::x86_avx_vtestc_ps_256:
8316     case Intrinsic::x86_avx_vtestc_pd_256:
8317       IsTestPacked = true; // Fallthrough
8318     case Intrinsic::x86_sse41_ptestc:
8319     case Intrinsic::x86_avx_ptestc_256:
8320       // CF = 1
8321       X86CC = X86::COND_B;
8322       break;
8323     case Intrinsic::x86_avx_vtestnzc_ps:
8324     case Intrinsic::x86_avx_vtestnzc_pd:
8325     case Intrinsic::x86_avx_vtestnzc_ps_256:
8326     case Intrinsic::x86_avx_vtestnzc_pd_256:
8327       IsTestPacked = true; // Fallthrough
8328     case Intrinsic::x86_sse41_ptestnzc:
8329     case Intrinsic::x86_avx_ptestnzc_256:
8330       // ZF and CF = 0
8331       X86CC = X86::COND_A;
8332       break;
8333     }
8334
8335     SDValue LHS = Op.getOperand(1);
8336     SDValue RHS = Op.getOperand(2);
8337     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8338     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8339     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8340     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8341     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8342   }
8343
8344   // Fix vector shift instructions where the last operand is a non-immediate
8345   // i32 value.
8346   case Intrinsic::x86_sse2_pslli_w:
8347   case Intrinsic::x86_sse2_pslli_d:
8348   case Intrinsic::x86_sse2_pslli_q:
8349   case Intrinsic::x86_sse2_psrli_w:
8350   case Intrinsic::x86_sse2_psrli_d:
8351   case Intrinsic::x86_sse2_psrli_q:
8352   case Intrinsic::x86_sse2_psrai_w:
8353   case Intrinsic::x86_sse2_psrai_d:
8354   case Intrinsic::x86_mmx_pslli_w:
8355   case Intrinsic::x86_mmx_pslli_d:
8356   case Intrinsic::x86_mmx_pslli_q:
8357   case Intrinsic::x86_mmx_psrli_w:
8358   case Intrinsic::x86_mmx_psrli_d:
8359   case Intrinsic::x86_mmx_psrli_q:
8360   case Intrinsic::x86_mmx_psrai_w:
8361   case Intrinsic::x86_mmx_psrai_d: {
8362     SDValue ShAmt = Op.getOperand(2);
8363     if (isa<ConstantSDNode>(ShAmt))
8364       return SDValue();
8365
8366     unsigned NewIntNo = 0;
8367     EVT ShAmtVT = MVT::v4i32;
8368     switch (IntNo) {
8369     case Intrinsic::x86_sse2_pslli_w:
8370       NewIntNo = Intrinsic::x86_sse2_psll_w;
8371       break;
8372     case Intrinsic::x86_sse2_pslli_d:
8373       NewIntNo = Intrinsic::x86_sse2_psll_d;
8374       break;
8375     case Intrinsic::x86_sse2_pslli_q:
8376       NewIntNo = Intrinsic::x86_sse2_psll_q;
8377       break;
8378     case Intrinsic::x86_sse2_psrli_w:
8379       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8380       break;
8381     case Intrinsic::x86_sse2_psrli_d:
8382       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8383       break;
8384     case Intrinsic::x86_sse2_psrli_q:
8385       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8386       break;
8387     case Intrinsic::x86_sse2_psrai_w:
8388       NewIntNo = Intrinsic::x86_sse2_psra_w;
8389       break;
8390     case Intrinsic::x86_sse2_psrai_d:
8391       NewIntNo = Intrinsic::x86_sse2_psra_d;
8392       break;
8393     default: {
8394       ShAmtVT = MVT::v2i32;
8395       switch (IntNo) {
8396       case Intrinsic::x86_mmx_pslli_w:
8397         NewIntNo = Intrinsic::x86_mmx_psll_w;
8398         break;
8399       case Intrinsic::x86_mmx_pslli_d:
8400         NewIntNo = Intrinsic::x86_mmx_psll_d;
8401         break;
8402       case Intrinsic::x86_mmx_pslli_q:
8403         NewIntNo = Intrinsic::x86_mmx_psll_q;
8404         break;
8405       case Intrinsic::x86_mmx_psrli_w:
8406         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8407         break;
8408       case Intrinsic::x86_mmx_psrli_d:
8409         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8410         break;
8411       case Intrinsic::x86_mmx_psrli_q:
8412         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8413         break;
8414       case Intrinsic::x86_mmx_psrai_w:
8415         NewIntNo = Intrinsic::x86_mmx_psra_w;
8416         break;
8417       case Intrinsic::x86_mmx_psrai_d:
8418         NewIntNo = Intrinsic::x86_mmx_psra_d;
8419         break;
8420       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8421       }
8422       break;
8423     }
8424     }
8425
8426     // The vector shift intrinsics with scalars uses 32b shift amounts but
8427     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8428     // to be zero.
8429     SDValue ShOps[4];
8430     ShOps[0] = ShAmt;
8431     ShOps[1] = DAG.getConstant(0, MVT::i32);
8432     if (ShAmtVT == MVT::v4i32) {
8433       ShOps[2] = DAG.getUNDEF(MVT::i32);
8434       ShOps[3] = DAG.getUNDEF(MVT::i32);
8435       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8436     } else {
8437       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8438 // FIXME this must be lowered to get rid of the invalid type.
8439     }
8440
8441     EVT VT = Op.getValueType();
8442     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8443     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8444                        DAG.getConstant(NewIntNo, MVT::i32),
8445                        Op.getOperand(1), ShAmt);
8446   }
8447   }
8448 }
8449
8450 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8451                                            SelectionDAG &DAG) const {
8452   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8453   MFI->setReturnAddressIsTaken(true);
8454
8455   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8456   DebugLoc dl = Op.getDebugLoc();
8457
8458   if (Depth > 0) {
8459     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8460     SDValue Offset =
8461       DAG.getConstant(TD->getPointerSize(),
8462                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8463     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8464                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8465                                    FrameAddr, Offset),
8466                        MachinePointerInfo(), false, false, 0);
8467   }
8468
8469   // Just load the return address.
8470   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8471   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8472                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8473 }
8474
8475 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8476   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8477   MFI->setFrameAddressIsTaken(true);
8478
8479   EVT VT = Op.getValueType();
8480   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8481   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8482   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8483   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8484   while (Depth--)
8485     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8486                             MachinePointerInfo(),
8487                             false, false, 0);
8488   return FrameAddr;
8489 }
8490
8491 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8492                                                      SelectionDAG &DAG) const {
8493   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8494 }
8495
8496 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8497   MachineFunction &MF = DAG.getMachineFunction();
8498   SDValue Chain     = Op.getOperand(0);
8499   SDValue Offset    = Op.getOperand(1);
8500   SDValue Handler   = Op.getOperand(2);
8501   DebugLoc dl       = Op.getDebugLoc();
8502
8503   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8504                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8505                                      getPointerTy());
8506   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8507
8508   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8509                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8510   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8511   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8512                        false, false, 0);
8513   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8514   MF.getRegInfo().addLiveOut(StoreAddrReg);
8515
8516   return DAG.getNode(X86ISD::EH_RETURN, dl,
8517                      MVT::Other,
8518                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8519 }
8520
8521 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8522                                              SelectionDAG &DAG) const {
8523   SDValue Root = Op.getOperand(0);
8524   SDValue Trmp = Op.getOperand(1); // trampoline
8525   SDValue FPtr = Op.getOperand(2); // nested function
8526   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8527   DebugLoc dl  = Op.getDebugLoc();
8528
8529   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8530
8531   if (Subtarget->is64Bit()) {
8532     SDValue OutChains[6];
8533
8534     // Large code-model.
8535     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8536     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8537
8538     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8539     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8540
8541     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8542
8543     // Load the pointer to the nested function into R11.
8544     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8545     SDValue Addr = Trmp;
8546     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8547                                 Addr, MachinePointerInfo(TrmpAddr),
8548                                 false, false, 0);
8549
8550     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8551                        DAG.getConstant(2, MVT::i64));
8552     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8553                                 MachinePointerInfo(TrmpAddr, 2),
8554                                 false, false, 2);
8555
8556     // Load the 'nest' parameter value into R10.
8557     // R10 is specified in X86CallingConv.td
8558     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8559     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8560                        DAG.getConstant(10, MVT::i64));
8561     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8562                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8563                                 false, false, 0);
8564
8565     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8566                        DAG.getConstant(12, MVT::i64));
8567     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8568                                 MachinePointerInfo(TrmpAddr, 12),
8569                                 false, false, 2);
8570
8571     // Jump to the nested function.
8572     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8573     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8574                        DAG.getConstant(20, MVT::i64));
8575     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8576                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8577                                 false, false, 0);
8578
8579     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8580     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8581                        DAG.getConstant(22, MVT::i64));
8582     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8583                                 MachinePointerInfo(TrmpAddr, 22),
8584                                 false, false, 0);
8585
8586     SDValue Ops[] =
8587       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8588     return DAG.getMergeValues(Ops, 2, dl);
8589   } else {
8590     const Function *Func =
8591       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8592     CallingConv::ID CC = Func->getCallingConv();
8593     unsigned NestReg;
8594
8595     switch (CC) {
8596     default:
8597       llvm_unreachable("Unsupported calling convention");
8598     case CallingConv::C:
8599     case CallingConv::X86_StdCall: {
8600       // Pass 'nest' parameter in ECX.
8601       // Must be kept in sync with X86CallingConv.td
8602       NestReg = X86::ECX;
8603
8604       // Check that ECX wasn't needed by an 'inreg' parameter.
8605       const FunctionType *FTy = Func->getFunctionType();
8606       const AttrListPtr &Attrs = Func->getAttributes();
8607
8608       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8609         unsigned InRegCount = 0;
8610         unsigned Idx = 1;
8611
8612         for (FunctionType::param_iterator I = FTy->param_begin(),
8613              E = FTy->param_end(); I != E; ++I, ++Idx)
8614           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8615             // FIXME: should only count parameters that are lowered to integers.
8616             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8617
8618         if (InRegCount > 2) {
8619           report_fatal_error("Nest register in use - reduce number of inreg"
8620                              " parameters!");
8621         }
8622       }
8623       break;
8624     }
8625     case CallingConv::X86_FastCall:
8626     case CallingConv::X86_ThisCall:
8627     case CallingConv::Fast:
8628       // Pass 'nest' parameter in EAX.
8629       // Must be kept in sync with X86CallingConv.td
8630       NestReg = X86::EAX;
8631       break;
8632     }
8633
8634     SDValue OutChains[4];
8635     SDValue Addr, Disp;
8636
8637     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8638                        DAG.getConstant(10, MVT::i32));
8639     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8640
8641     // This is storing the opcode for MOV32ri.
8642     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8643     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8644     OutChains[0] = DAG.getStore(Root, dl,
8645                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8646                                 Trmp, MachinePointerInfo(TrmpAddr),
8647                                 false, false, 0);
8648
8649     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8650                        DAG.getConstant(1, MVT::i32));
8651     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8652                                 MachinePointerInfo(TrmpAddr, 1),
8653                                 false, false, 1);
8654
8655     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8656     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8657                        DAG.getConstant(5, MVT::i32));
8658     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8659                                 MachinePointerInfo(TrmpAddr, 5),
8660                                 false, false, 1);
8661
8662     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8663                        DAG.getConstant(6, MVT::i32));
8664     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8665                                 MachinePointerInfo(TrmpAddr, 6),
8666                                 false, false, 1);
8667
8668     SDValue Ops[] =
8669       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8670     return DAG.getMergeValues(Ops, 2, dl);
8671   }
8672 }
8673
8674 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8675                                             SelectionDAG &DAG) const {
8676   /*
8677    The rounding mode is in bits 11:10 of FPSR, and has the following
8678    settings:
8679      00 Round to nearest
8680      01 Round to -inf
8681      10 Round to +inf
8682      11 Round to 0
8683
8684   FLT_ROUNDS, on the other hand, expects the following:
8685     -1 Undefined
8686      0 Round to 0
8687      1 Round to nearest
8688      2 Round to +inf
8689      3 Round to -inf
8690
8691   To perform the conversion, we do:
8692     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8693   */
8694
8695   MachineFunction &MF = DAG.getMachineFunction();
8696   const TargetMachine &TM = MF.getTarget();
8697   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8698   unsigned StackAlignment = TFI.getStackAlignment();
8699   EVT VT = Op.getValueType();
8700   DebugLoc DL = Op.getDebugLoc();
8701
8702   // Save FP Control Word to stack slot
8703   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8704   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8705
8706
8707   MachineMemOperand *MMO =
8708    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8709                            MachineMemOperand::MOStore, 2, 2);
8710
8711   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8712   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8713                                           DAG.getVTList(MVT::Other),
8714                                           Ops, 2, MVT::i16, MMO);
8715
8716   // Load FP Control Word from stack slot
8717   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8718                             MachinePointerInfo(), false, false, 0);
8719
8720   // Transform as necessary
8721   SDValue CWD1 =
8722     DAG.getNode(ISD::SRL, DL, MVT::i16,
8723                 DAG.getNode(ISD::AND, DL, MVT::i16,
8724                             CWD, DAG.getConstant(0x800, MVT::i16)),
8725                 DAG.getConstant(11, MVT::i8));
8726   SDValue CWD2 =
8727     DAG.getNode(ISD::SRL, DL, MVT::i16,
8728                 DAG.getNode(ISD::AND, DL, MVT::i16,
8729                             CWD, DAG.getConstant(0x400, MVT::i16)),
8730                 DAG.getConstant(9, MVT::i8));
8731
8732   SDValue RetVal =
8733     DAG.getNode(ISD::AND, DL, MVT::i16,
8734                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8735                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8736                             DAG.getConstant(1, MVT::i16)),
8737                 DAG.getConstant(3, MVT::i16));
8738
8739
8740   return DAG.getNode((VT.getSizeInBits() < 16 ?
8741                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8742 }
8743
8744 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8745   EVT VT = Op.getValueType();
8746   EVT OpVT = VT;
8747   unsigned NumBits = VT.getSizeInBits();
8748   DebugLoc dl = Op.getDebugLoc();
8749
8750   Op = Op.getOperand(0);
8751   if (VT == MVT::i8) {
8752     // Zero extend to i32 since there is not an i8 bsr.
8753     OpVT = MVT::i32;
8754     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8755   }
8756
8757   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8758   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8759   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8760
8761   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8762   SDValue Ops[] = {
8763     Op,
8764     DAG.getConstant(NumBits+NumBits-1, OpVT),
8765     DAG.getConstant(X86::COND_E, MVT::i8),
8766     Op.getValue(1)
8767   };
8768   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8769
8770   // Finally xor with NumBits-1.
8771   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8772
8773   if (VT == MVT::i8)
8774     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8775   return Op;
8776 }
8777
8778 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8779   EVT VT = Op.getValueType();
8780   EVT OpVT = VT;
8781   unsigned NumBits = VT.getSizeInBits();
8782   DebugLoc dl = Op.getDebugLoc();
8783
8784   Op = Op.getOperand(0);
8785   if (VT == MVT::i8) {
8786     OpVT = MVT::i32;
8787     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8788   }
8789
8790   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8791   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8792   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8793
8794   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8795   SDValue Ops[] = {
8796     Op,
8797     DAG.getConstant(NumBits, OpVT),
8798     DAG.getConstant(X86::COND_E, MVT::i8),
8799     Op.getValue(1)
8800   };
8801   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8802
8803   if (VT == MVT::i8)
8804     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8805   return Op;
8806 }
8807
8808 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8809   EVT VT = Op.getValueType();
8810   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8811   DebugLoc dl = Op.getDebugLoc();
8812
8813   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8814   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8815   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8816   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8817   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8818   //
8819   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8820   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8821   //  return AloBlo + AloBhi + AhiBlo;
8822
8823   SDValue A = Op.getOperand(0);
8824   SDValue B = Op.getOperand(1);
8825
8826   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8827                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8828                        A, DAG.getConstant(32, MVT::i32));
8829   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8830                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8831                        B, DAG.getConstant(32, MVT::i32));
8832   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8833                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8834                        A, B);
8835   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8836                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8837                        A, Bhi);
8838   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8839                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8840                        Ahi, B);
8841   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8842                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8843                        AloBhi, DAG.getConstant(32, MVT::i32));
8844   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8846                        AhiBlo, DAG.getConstant(32, MVT::i32));
8847   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8848   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8849   return Res;
8850 }
8851
8852 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8853
8854   EVT VT = Op.getValueType();
8855   DebugLoc dl = Op.getDebugLoc();
8856   SDValue R = Op.getOperand(0);
8857   SDValue Amt = Op.getOperand(1);
8858
8859   LLVMContext *Context = DAG.getContext();
8860
8861   // Must have SSE2.
8862   if (!Subtarget->hasSSE2()) return SDValue();
8863
8864   // Optimize shl/srl/sra with constant shift amount.
8865   if (isSplatVector(Amt.getNode())) {
8866     SDValue SclrAmt = Amt->getOperand(0);
8867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8868       uint64_t ShiftAmt = C->getZExtValue();
8869
8870       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8871        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8872                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8873                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8874
8875       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8876        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8877                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8878                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8879
8880       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8881        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8882                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8883                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8884
8885       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8886        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8887                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8888                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8889
8890       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8891        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8892                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8893                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8894
8895       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8896        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8897                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8898                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8899
8900       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8901        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8902                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8903                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8904
8905       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8906        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8907                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8908                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8909     }
8910   }
8911
8912   // Lower SHL with variable shift amount.
8913   // Cannot lower SHL without SSE4.1 or later.
8914   if (!Subtarget->hasSSE41()) return SDValue();
8915
8916   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8917     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8918                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8919                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8920
8921     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8922
8923     std::vector<Constant*> CV(4, CI);
8924     Constant *C = ConstantVector::get(CV);
8925     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8926     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8927                                  MachinePointerInfo::getConstantPool(),
8928                                  false, false, 16);
8929
8930     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8931     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8932     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8933     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8934   }
8935   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8936     // a = a << 5;
8937     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8938                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8939                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8940
8941     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8942     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8943
8944     std::vector<Constant*> CVM1(16, CM1);
8945     std::vector<Constant*> CVM2(16, CM2);
8946     Constant *C = ConstantVector::get(CVM1);
8947     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8948     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8949                             MachinePointerInfo::getConstantPool(),
8950                             false, false, 16);
8951
8952     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8953     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8954     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8955                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8956                     DAG.getConstant(4, MVT::i32));
8957     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8958     // a += a
8959     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8960
8961     C = ConstantVector::get(CVM2);
8962     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8963     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8964                     MachinePointerInfo::getConstantPool(),
8965                     false, false, 16);
8966
8967     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8968     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8969     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8970                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8971                     DAG.getConstant(2, MVT::i32));
8972     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8973     // a += a
8974     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8975
8976     // return pblendv(r, r+r, a);
8977     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8978                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8979     return R;
8980   }
8981   return SDValue();
8982 }
8983
8984 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8985   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8986   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8987   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8988   // has only one use.
8989   SDNode *N = Op.getNode();
8990   SDValue LHS = N->getOperand(0);
8991   SDValue RHS = N->getOperand(1);
8992   unsigned BaseOp = 0;
8993   unsigned Cond = 0;
8994   DebugLoc DL = Op.getDebugLoc();
8995   switch (Op.getOpcode()) {
8996   default: llvm_unreachable("Unknown ovf instruction!");
8997   case ISD::SADDO:
8998     // A subtract of one will be selected as a INC. Note that INC doesn't
8999     // set CF, so we can't do this for UADDO.
9000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9001       if (C->isOne()) {
9002         BaseOp = X86ISD::INC;
9003         Cond = X86::COND_O;
9004         break;
9005       }
9006     BaseOp = X86ISD::ADD;
9007     Cond = X86::COND_O;
9008     break;
9009   case ISD::UADDO:
9010     BaseOp = X86ISD::ADD;
9011     Cond = X86::COND_B;
9012     break;
9013   case ISD::SSUBO:
9014     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9015     // set CF, so we can't do this for USUBO.
9016     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9017       if (C->isOne()) {
9018         BaseOp = X86ISD::DEC;
9019         Cond = X86::COND_O;
9020         break;
9021       }
9022     BaseOp = X86ISD::SUB;
9023     Cond = X86::COND_O;
9024     break;
9025   case ISD::USUBO:
9026     BaseOp = X86ISD::SUB;
9027     Cond = X86::COND_B;
9028     break;
9029   case ISD::SMULO:
9030     BaseOp = X86ISD::SMUL;
9031     Cond = X86::COND_O;
9032     break;
9033   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9034     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9035                                  MVT::i32);
9036     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9037
9038     SDValue SetCC =
9039       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9040                   DAG.getConstant(X86::COND_O, MVT::i32),
9041                   SDValue(Sum.getNode(), 2));
9042
9043     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9044     return Sum;
9045   }
9046   }
9047
9048   // Also sets EFLAGS.
9049   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9050   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9051
9052   SDValue SetCC =
9053     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9054                 DAG.getConstant(Cond, MVT::i32),
9055                 SDValue(Sum.getNode(), 1));
9056
9057   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9058   return Sum;
9059 }
9060
9061 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9062   DebugLoc dl = Op.getDebugLoc();
9063
9064   if (!Subtarget->hasSSE2()) {
9065     SDValue Chain = Op.getOperand(0);
9066     SDValue Zero = DAG.getConstant(0,
9067                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9068     SDValue Ops[] = {
9069       DAG.getRegister(X86::ESP, MVT::i32), // Base
9070       DAG.getTargetConstant(1, MVT::i8),   // Scale
9071       DAG.getRegister(0, MVT::i32),        // Index
9072       DAG.getTargetConstant(0, MVT::i32),  // Disp
9073       DAG.getRegister(0, MVT::i32),        // Segment.
9074       Zero,
9075       Chain
9076     };
9077     SDNode *Res =
9078       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9079                           array_lengthof(Ops));
9080     return SDValue(Res, 0);
9081   }
9082
9083   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9084   if (!isDev)
9085     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9086
9087   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9088   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9089   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9090   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9091
9092   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9093   if (!Op1 && !Op2 && !Op3 && Op4)
9094     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9095
9096   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9097   if (Op1 && !Op2 && !Op3 && !Op4)
9098     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9099
9100   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9101   //           (MFENCE)>;
9102   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9103 }
9104
9105 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9106   EVT T = Op.getValueType();
9107   DebugLoc DL = Op.getDebugLoc();
9108   unsigned Reg = 0;
9109   unsigned size = 0;
9110   switch(T.getSimpleVT().SimpleTy) {
9111   default:
9112     assert(false && "Invalid value type!");
9113   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9114   case MVT::i16: Reg = X86::AX;  size = 2; break;
9115   case MVT::i32: Reg = X86::EAX; size = 4; break;
9116   case MVT::i64:
9117     assert(Subtarget->is64Bit() && "Node not type legal!");
9118     Reg = X86::RAX; size = 8;
9119     break;
9120   }
9121   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9122                                     Op.getOperand(2), SDValue());
9123   SDValue Ops[] = { cpIn.getValue(0),
9124                     Op.getOperand(1),
9125                     Op.getOperand(3),
9126                     DAG.getTargetConstant(size, MVT::i8),
9127                     cpIn.getValue(1) };
9128   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9129   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9130   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9131                                            Ops, 5, T, MMO);
9132   SDValue cpOut =
9133     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9134   return cpOut;
9135 }
9136
9137 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9138                                                  SelectionDAG &DAG) const {
9139   assert(Subtarget->is64Bit() && "Result not type legalized?");
9140   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9141   SDValue TheChain = Op.getOperand(0);
9142   DebugLoc dl = Op.getDebugLoc();
9143   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9144   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9145   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9146                                    rax.getValue(2));
9147   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9148                             DAG.getConstant(32, MVT::i8));
9149   SDValue Ops[] = {
9150     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9151     rdx.getValue(1)
9152   };
9153   return DAG.getMergeValues(Ops, 2, dl);
9154 }
9155
9156 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9157                                             SelectionDAG &DAG) const {
9158   EVT SrcVT = Op.getOperand(0).getValueType();
9159   EVT DstVT = Op.getValueType();
9160   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9161          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9162   assert((DstVT == MVT::i64 ||
9163           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9164          "Unexpected custom BITCAST");
9165   // i64 <=> MMX conversions are Legal.
9166   if (SrcVT==MVT::i64 && DstVT.isVector())
9167     return Op;
9168   if (DstVT==MVT::i64 && SrcVT.isVector())
9169     return Op;
9170   // MMX <=> MMX conversions are Legal.
9171   if (SrcVT.isVector() && DstVT.isVector())
9172     return Op;
9173   // All other conversions need to be expanded.
9174   return SDValue();
9175 }
9176
9177 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9178   SDNode *Node = Op.getNode();
9179   DebugLoc dl = Node->getDebugLoc();
9180   EVT T = Node->getValueType(0);
9181   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9182                               DAG.getConstant(0, T), Node->getOperand(2));
9183   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9184                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9185                        Node->getOperand(0),
9186                        Node->getOperand(1), negOp,
9187                        cast<AtomicSDNode>(Node)->getSrcValue(),
9188                        cast<AtomicSDNode>(Node)->getAlignment());
9189 }
9190
9191 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9192   EVT VT = Op.getNode()->getValueType(0);
9193
9194   // Let legalize expand this if it isn't a legal type yet.
9195   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9196     return SDValue();
9197
9198   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9199
9200   unsigned Opc;
9201   bool ExtraOp = false;
9202   switch (Op.getOpcode()) {
9203   default: assert(0 && "Invalid code");
9204   case ISD::ADDC: Opc = X86ISD::ADD; break;
9205   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9206   case ISD::SUBC: Opc = X86ISD::SUB; break;
9207   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9208   }
9209
9210   if (!ExtraOp)
9211     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9212                        Op.getOperand(1));
9213   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9214                      Op.getOperand(1), Op.getOperand(2));
9215 }
9216
9217 /// LowerOperation - Provide custom lowering hooks for some operations.
9218 ///
9219 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9220   switch (Op.getOpcode()) {
9221   default: llvm_unreachable("Should not custom lower this!");
9222   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9223   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9224   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9225   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9226   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9227   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9228   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9229   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9230   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9231   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9232   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9233   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9234   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9235   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9236   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9237   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9238   case ISD::SHL_PARTS:
9239   case ISD::SRA_PARTS:
9240   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9241   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9242   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9243   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9244   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9245   case ISD::FABS:               return LowerFABS(Op, DAG);
9246   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9247   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9248   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9249   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9250   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9251   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9252   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9253   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9254   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9255   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9256   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9257   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9258   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9259   case ISD::FRAME_TO_ARGS_OFFSET:
9260                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9261   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9262   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9263   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9264   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9265   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9266   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9267   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9268   case ISD::SRA:
9269   case ISD::SRL:
9270   case ISD::SHL:                return LowerShift(Op, DAG);
9271   case ISD::SADDO:
9272   case ISD::UADDO:
9273   case ISD::SSUBO:
9274   case ISD::USUBO:
9275   case ISD::SMULO:
9276   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9277   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9278   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9279   case ISD::ADDC:
9280   case ISD::ADDE:
9281   case ISD::SUBC:
9282   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9283   }
9284 }
9285
9286 void X86TargetLowering::
9287 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9288                         SelectionDAG &DAG, unsigned NewOp) const {
9289   EVT T = Node->getValueType(0);
9290   DebugLoc dl = Node->getDebugLoc();
9291   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9292
9293   SDValue Chain = Node->getOperand(0);
9294   SDValue In1 = Node->getOperand(1);
9295   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9296                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9297   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9298                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9299   SDValue Ops[] = { Chain, In1, In2L, In2H };
9300   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9301   SDValue Result =
9302     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9303                             cast<MemSDNode>(Node)->getMemOperand());
9304   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9305   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9306   Results.push_back(Result.getValue(2));
9307 }
9308
9309 /// ReplaceNodeResults - Replace a node with an illegal result type
9310 /// with a new node built out of custom code.
9311 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9312                                            SmallVectorImpl<SDValue>&Results,
9313                                            SelectionDAG &DAG) const {
9314   DebugLoc dl = N->getDebugLoc();
9315   switch (N->getOpcode()) {
9316   default:
9317     assert(false && "Do not know how to custom type legalize this operation!");
9318     return;
9319   case ISD::ADDC:
9320   case ISD::ADDE:
9321   case ISD::SUBC:
9322   case ISD::SUBE:
9323     // We don't want to expand or promote these.
9324     return;
9325   case ISD::FP_TO_SINT: {
9326     std::pair<SDValue,SDValue> Vals =
9327         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9328     SDValue FIST = Vals.first, StackSlot = Vals.second;
9329     if (FIST.getNode() != 0) {
9330       EVT VT = N->getValueType(0);
9331       // Return a load from the stack slot.
9332       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9333                                     MachinePointerInfo(), false, false, 0));
9334     }
9335     return;
9336   }
9337   case ISD::READCYCLECOUNTER: {
9338     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9339     SDValue TheChain = N->getOperand(0);
9340     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9341     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9342                                      rd.getValue(1));
9343     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9344                                      eax.getValue(2));
9345     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9346     SDValue Ops[] = { eax, edx };
9347     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9348     Results.push_back(edx.getValue(1));
9349     return;
9350   }
9351   case ISD::ATOMIC_CMP_SWAP: {
9352     EVT T = N->getValueType(0);
9353     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9354     SDValue cpInL, cpInH;
9355     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9356                         DAG.getConstant(0, MVT::i32));
9357     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9358                         DAG.getConstant(1, MVT::i32));
9359     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9360     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9361                              cpInL.getValue(1));
9362     SDValue swapInL, swapInH;
9363     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9364                           DAG.getConstant(0, MVT::i32));
9365     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9366                           DAG.getConstant(1, MVT::i32));
9367     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9368                                cpInH.getValue(1));
9369     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9370                                swapInL.getValue(1));
9371     SDValue Ops[] = { swapInH.getValue(0),
9372                       N->getOperand(1),
9373                       swapInH.getValue(1) };
9374     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9375     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9376     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9377                                              Ops, 3, T, MMO);
9378     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9379                                         MVT::i32, Result.getValue(1));
9380     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9381                                         MVT::i32, cpOutL.getValue(2));
9382     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9383     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9384     Results.push_back(cpOutH.getValue(1));
9385     return;
9386   }
9387   case ISD::ATOMIC_LOAD_ADD:
9388     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9389     return;
9390   case ISD::ATOMIC_LOAD_AND:
9391     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9392     return;
9393   case ISD::ATOMIC_LOAD_NAND:
9394     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9395     return;
9396   case ISD::ATOMIC_LOAD_OR:
9397     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9398     return;
9399   case ISD::ATOMIC_LOAD_SUB:
9400     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9401     return;
9402   case ISD::ATOMIC_LOAD_XOR:
9403     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9404     return;
9405   case ISD::ATOMIC_SWAP:
9406     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9407     return;
9408   }
9409 }
9410
9411 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9412   switch (Opcode) {
9413   default: return NULL;
9414   case X86ISD::BSF:                return "X86ISD::BSF";
9415   case X86ISD::BSR:                return "X86ISD::BSR";
9416   case X86ISD::SHLD:               return "X86ISD::SHLD";
9417   case X86ISD::SHRD:               return "X86ISD::SHRD";
9418   case X86ISD::FAND:               return "X86ISD::FAND";
9419   case X86ISD::FOR:                return "X86ISD::FOR";
9420   case X86ISD::FXOR:               return "X86ISD::FXOR";
9421   case X86ISD::FSRL:               return "X86ISD::FSRL";
9422   case X86ISD::FILD:               return "X86ISD::FILD";
9423   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9424   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9425   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9426   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9427   case X86ISD::FLD:                return "X86ISD::FLD";
9428   case X86ISD::FST:                return "X86ISD::FST";
9429   case X86ISD::CALL:               return "X86ISD::CALL";
9430   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9431   case X86ISD::BT:                 return "X86ISD::BT";
9432   case X86ISD::CMP:                return "X86ISD::CMP";
9433   case X86ISD::COMI:               return "X86ISD::COMI";
9434   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9435   case X86ISD::SETCC:              return "X86ISD::SETCC";
9436   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9437   case X86ISD::CMOV:               return "X86ISD::CMOV";
9438   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9439   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9440   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9441   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9442   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9443   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9444   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9445   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9446   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9447   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9448   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9449   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9450   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9451   case X86ISD::PANDN:              return "X86ISD::PANDN";
9452   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9453   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9454   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9455   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9456   case X86ISD::FMAX:               return "X86ISD::FMAX";
9457   case X86ISD::FMIN:               return "X86ISD::FMIN";
9458   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9459   case X86ISD::FRCP:               return "X86ISD::FRCP";
9460   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9461   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9462   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9463   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9464   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9465   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9466   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9467   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9468   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9469   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9470   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9471   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9472   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9473   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9474   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9475   case X86ISD::VSHL:               return "X86ISD::VSHL";
9476   case X86ISD::VSRL:               return "X86ISD::VSRL";
9477   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9478   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9479   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9480   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9481   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9482   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9483   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9484   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9485   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9486   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9487   case X86ISD::ADD:                return "X86ISD::ADD";
9488   case X86ISD::SUB:                return "X86ISD::SUB";
9489   case X86ISD::ADC:                return "X86ISD::ADC";
9490   case X86ISD::SBB:                return "X86ISD::SBB";
9491   case X86ISD::SMUL:               return "X86ISD::SMUL";
9492   case X86ISD::UMUL:               return "X86ISD::UMUL";
9493   case X86ISD::INC:                return "X86ISD::INC";
9494   case X86ISD::DEC:                return "X86ISD::DEC";
9495   case X86ISD::OR:                 return "X86ISD::OR";
9496   case X86ISD::XOR:                return "X86ISD::XOR";
9497   case X86ISD::AND:                return "X86ISD::AND";
9498   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9499   case X86ISD::PTEST:              return "X86ISD::PTEST";
9500   case X86ISD::TESTP:              return "X86ISD::TESTP";
9501   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9502   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9503   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9504   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9505   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9506   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9507   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9508   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9509   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9510   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9511   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9512   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9513   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9514   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9515   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9516   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9517   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9518   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9519   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9520   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9521   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9522   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9523   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9524   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9525   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9526   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9527   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9528   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9529   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9530   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9531   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9532   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9533   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9534   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9535   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9536   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9537   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9538   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9539   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9540   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9541   }
9542 }
9543
9544 // isLegalAddressingMode - Return true if the addressing mode represented
9545 // by AM is legal for this target, for a load/store of the specified type.
9546 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9547                                               const Type *Ty) const {
9548   // X86 supports extremely general addressing modes.
9549   CodeModel::Model M = getTargetMachine().getCodeModel();
9550   Reloc::Model R = getTargetMachine().getRelocationModel();
9551
9552   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9553   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9554     return false;
9555
9556   if (AM.BaseGV) {
9557     unsigned GVFlags =
9558       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9559
9560     // If a reference to this global requires an extra load, we can't fold it.
9561     if (isGlobalStubReference(GVFlags))
9562       return false;
9563
9564     // If BaseGV requires a register for the PIC base, we cannot also have a
9565     // BaseReg specified.
9566     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9567       return false;
9568
9569     // If lower 4G is not available, then we must use rip-relative addressing.
9570     if ((M != CodeModel::Small || R != Reloc::Static) &&
9571         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9572       return false;
9573   }
9574
9575   switch (AM.Scale) {
9576   case 0:
9577   case 1:
9578   case 2:
9579   case 4:
9580   case 8:
9581     // These scales always work.
9582     break;
9583   case 3:
9584   case 5:
9585   case 9:
9586     // These scales are formed with basereg+scalereg.  Only accept if there is
9587     // no basereg yet.
9588     if (AM.HasBaseReg)
9589       return false;
9590     break;
9591   default:  // Other stuff never works.
9592     return false;
9593   }
9594
9595   return true;
9596 }
9597
9598
9599 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9600   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9601     return false;
9602   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9603   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9604   if (NumBits1 <= NumBits2)
9605     return false;
9606   return true;
9607 }
9608
9609 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9610   if (!VT1.isInteger() || !VT2.isInteger())
9611     return false;
9612   unsigned NumBits1 = VT1.getSizeInBits();
9613   unsigned NumBits2 = VT2.getSizeInBits();
9614   if (NumBits1 <= NumBits2)
9615     return false;
9616   return true;
9617 }
9618
9619 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9620   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9621   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9622 }
9623
9624 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9625   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9626   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9627 }
9628
9629 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9630   // i16 instructions are longer (0x66 prefix) and potentially slower.
9631   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9632 }
9633
9634 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9635 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9636 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9637 /// are assumed to be legal.
9638 bool
9639 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9640                                       EVT VT) const {
9641   // Very little shuffling can be done for 64-bit vectors right now.
9642   if (VT.getSizeInBits() == 64)
9643     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9644
9645   // FIXME: pshufb, blends, shifts.
9646   return (VT.getVectorNumElements() == 2 ||
9647           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9648           isMOVLMask(M, VT) ||
9649           isSHUFPMask(M, VT) ||
9650           isPSHUFDMask(M, VT) ||
9651           isPSHUFHWMask(M, VT) ||
9652           isPSHUFLWMask(M, VT) ||
9653           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9654           isUNPCKLMask(M, VT) ||
9655           isUNPCKHMask(M, VT) ||
9656           isUNPCKL_v_undef_Mask(M, VT) ||
9657           isUNPCKH_v_undef_Mask(M, VT));
9658 }
9659
9660 bool
9661 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9662                                           EVT VT) const {
9663   unsigned NumElts = VT.getVectorNumElements();
9664   // FIXME: This collection of masks seems suspect.
9665   if (NumElts == 2)
9666     return true;
9667   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9668     return (isMOVLMask(Mask, VT)  ||
9669             isCommutedMOVLMask(Mask, VT, true) ||
9670             isSHUFPMask(Mask, VT) ||
9671             isCommutedSHUFPMask(Mask, VT));
9672   }
9673   return false;
9674 }
9675
9676 //===----------------------------------------------------------------------===//
9677 //                           X86 Scheduler Hooks
9678 //===----------------------------------------------------------------------===//
9679
9680 // private utility function
9681 MachineBasicBlock *
9682 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9683                                                        MachineBasicBlock *MBB,
9684                                                        unsigned regOpc,
9685                                                        unsigned immOpc,
9686                                                        unsigned LoadOpc,
9687                                                        unsigned CXchgOpc,
9688                                                        unsigned notOpc,
9689                                                        unsigned EAXreg,
9690                                                        TargetRegisterClass *RC,
9691                                                        bool invSrc) const {
9692   // For the atomic bitwise operator, we generate
9693   //   thisMBB:
9694   //   newMBB:
9695   //     ld  t1 = [bitinstr.addr]
9696   //     op  t2 = t1, [bitinstr.val]
9697   //     mov EAX = t1
9698   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9699   //     bz  newMBB
9700   //     fallthrough -->nextMBB
9701   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9702   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9703   MachineFunction::iterator MBBIter = MBB;
9704   ++MBBIter;
9705
9706   /// First build the CFG
9707   MachineFunction *F = MBB->getParent();
9708   MachineBasicBlock *thisMBB = MBB;
9709   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9710   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9711   F->insert(MBBIter, newMBB);
9712   F->insert(MBBIter, nextMBB);
9713
9714   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9715   nextMBB->splice(nextMBB->begin(), thisMBB,
9716                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9717                   thisMBB->end());
9718   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9719
9720   // Update thisMBB to fall through to newMBB
9721   thisMBB->addSuccessor(newMBB);
9722
9723   // newMBB jumps to itself and fall through to nextMBB
9724   newMBB->addSuccessor(nextMBB);
9725   newMBB->addSuccessor(newMBB);
9726
9727   // Insert instructions into newMBB based on incoming instruction
9728   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9729          "unexpected number of operands");
9730   DebugLoc dl = bInstr->getDebugLoc();
9731   MachineOperand& destOper = bInstr->getOperand(0);
9732   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9733   int numArgs = bInstr->getNumOperands() - 1;
9734   for (int i=0; i < numArgs; ++i)
9735     argOpers[i] = &bInstr->getOperand(i+1);
9736
9737   // x86 address has 4 operands: base, index, scale, and displacement
9738   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9739   int valArgIndx = lastAddrIndx + 1;
9740
9741   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9742   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9743   for (int i=0; i <= lastAddrIndx; ++i)
9744     (*MIB).addOperand(*argOpers[i]);
9745
9746   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9747   if (invSrc) {
9748     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9749   }
9750   else
9751     tt = t1;
9752
9753   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9754   assert((argOpers[valArgIndx]->isReg() ||
9755           argOpers[valArgIndx]->isImm()) &&
9756          "invalid operand");
9757   if (argOpers[valArgIndx]->isReg())
9758     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9759   else
9760     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9761   MIB.addReg(tt);
9762   (*MIB).addOperand(*argOpers[valArgIndx]);
9763
9764   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9765   MIB.addReg(t1);
9766
9767   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9768   for (int i=0; i <= lastAddrIndx; ++i)
9769     (*MIB).addOperand(*argOpers[i]);
9770   MIB.addReg(t2);
9771   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9772   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9773                     bInstr->memoperands_end());
9774
9775   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9776   MIB.addReg(EAXreg);
9777
9778   // insert branch
9779   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9780
9781   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9782   return nextMBB;
9783 }
9784
9785 // private utility function:  64 bit atomics on 32 bit host.
9786 MachineBasicBlock *
9787 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9788                                                        MachineBasicBlock *MBB,
9789                                                        unsigned regOpcL,
9790                                                        unsigned regOpcH,
9791                                                        unsigned immOpcL,
9792                                                        unsigned immOpcH,
9793                                                        bool invSrc) const {
9794   // For the atomic bitwise operator, we generate
9795   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9796   //     ld t1,t2 = [bitinstr.addr]
9797   //   newMBB:
9798   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9799   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9800   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9801   //     mov ECX, EBX <- t5, t6
9802   //     mov EAX, EDX <- t1, t2
9803   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9804   //     mov t3, t4 <- EAX, EDX
9805   //     bz  newMBB
9806   //     result in out1, out2
9807   //     fallthrough -->nextMBB
9808
9809   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9810   const unsigned LoadOpc = X86::MOV32rm;
9811   const unsigned NotOpc = X86::NOT32r;
9812   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9813   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9814   MachineFunction::iterator MBBIter = MBB;
9815   ++MBBIter;
9816
9817   /// First build the CFG
9818   MachineFunction *F = MBB->getParent();
9819   MachineBasicBlock *thisMBB = MBB;
9820   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9821   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9822   F->insert(MBBIter, newMBB);
9823   F->insert(MBBIter, nextMBB);
9824
9825   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9826   nextMBB->splice(nextMBB->begin(), thisMBB,
9827                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9828                   thisMBB->end());
9829   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9830
9831   // Update thisMBB to fall through to newMBB
9832   thisMBB->addSuccessor(newMBB);
9833
9834   // newMBB jumps to itself and fall through to nextMBB
9835   newMBB->addSuccessor(nextMBB);
9836   newMBB->addSuccessor(newMBB);
9837
9838   DebugLoc dl = bInstr->getDebugLoc();
9839   // Insert instructions into newMBB based on incoming instruction
9840   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9841   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9842          "unexpected number of operands");
9843   MachineOperand& dest1Oper = bInstr->getOperand(0);
9844   MachineOperand& dest2Oper = bInstr->getOperand(1);
9845   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9846   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9847     argOpers[i] = &bInstr->getOperand(i+2);
9848
9849     // We use some of the operands multiple times, so conservatively just
9850     // clear any kill flags that might be present.
9851     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9852       argOpers[i]->setIsKill(false);
9853   }
9854
9855   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9856   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9857
9858   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9859   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9860   for (int i=0; i <= lastAddrIndx; ++i)
9861     (*MIB).addOperand(*argOpers[i]);
9862   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9863   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9864   // add 4 to displacement.
9865   for (int i=0; i <= lastAddrIndx-2; ++i)
9866     (*MIB).addOperand(*argOpers[i]);
9867   MachineOperand newOp3 = *(argOpers[3]);
9868   if (newOp3.isImm())
9869     newOp3.setImm(newOp3.getImm()+4);
9870   else
9871     newOp3.setOffset(newOp3.getOffset()+4);
9872   (*MIB).addOperand(newOp3);
9873   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9874
9875   // t3/4 are defined later, at the bottom of the loop
9876   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9877   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9878   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9879     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9880   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9881     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9882
9883   // The subsequent operations should be using the destination registers of
9884   //the PHI instructions.
9885   if (invSrc) {
9886     t1 = F->getRegInfo().createVirtualRegister(RC);
9887     t2 = F->getRegInfo().createVirtualRegister(RC);
9888     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9889     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9890   } else {
9891     t1 = dest1Oper.getReg();
9892     t2 = dest2Oper.getReg();
9893   }
9894
9895   int valArgIndx = lastAddrIndx + 1;
9896   assert((argOpers[valArgIndx]->isReg() ||
9897           argOpers[valArgIndx]->isImm()) &&
9898          "invalid operand");
9899   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9900   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9901   if (argOpers[valArgIndx]->isReg())
9902     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9903   else
9904     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9905   if (regOpcL != X86::MOV32rr)
9906     MIB.addReg(t1);
9907   (*MIB).addOperand(*argOpers[valArgIndx]);
9908   assert(argOpers[valArgIndx + 1]->isReg() ==
9909          argOpers[valArgIndx]->isReg());
9910   assert(argOpers[valArgIndx + 1]->isImm() ==
9911          argOpers[valArgIndx]->isImm());
9912   if (argOpers[valArgIndx + 1]->isReg())
9913     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9914   else
9915     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9916   if (regOpcH != X86::MOV32rr)
9917     MIB.addReg(t2);
9918   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9919
9920   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9921   MIB.addReg(t1);
9922   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9923   MIB.addReg(t2);
9924
9925   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9926   MIB.addReg(t5);
9927   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9928   MIB.addReg(t6);
9929
9930   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9931   for (int i=0; i <= lastAddrIndx; ++i)
9932     (*MIB).addOperand(*argOpers[i]);
9933
9934   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9935   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9936                     bInstr->memoperands_end());
9937
9938   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9939   MIB.addReg(X86::EAX);
9940   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9941   MIB.addReg(X86::EDX);
9942
9943   // insert branch
9944   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9945
9946   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9947   return nextMBB;
9948 }
9949
9950 // private utility function
9951 MachineBasicBlock *
9952 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9953                                                       MachineBasicBlock *MBB,
9954                                                       unsigned cmovOpc) const {
9955   // For the atomic min/max operator, we generate
9956   //   thisMBB:
9957   //   newMBB:
9958   //     ld t1 = [min/max.addr]
9959   //     mov t2 = [min/max.val]
9960   //     cmp  t1, t2
9961   //     cmov[cond] t2 = t1
9962   //     mov EAX = t1
9963   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9964   //     bz   newMBB
9965   //     fallthrough -->nextMBB
9966   //
9967   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9968   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9969   MachineFunction::iterator MBBIter = MBB;
9970   ++MBBIter;
9971
9972   /// First build the CFG
9973   MachineFunction *F = MBB->getParent();
9974   MachineBasicBlock *thisMBB = MBB;
9975   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9976   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9977   F->insert(MBBIter, newMBB);
9978   F->insert(MBBIter, nextMBB);
9979
9980   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9981   nextMBB->splice(nextMBB->begin(), thisMBB,
9982                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9983                   thisMBB->end());
9984   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9985
9986   // Update thisMBB to fall through to newMBB
9987   thisMBB->addSuccessor(newMBB);
9988
9989   // newMBB jumps to newMBB and fall through to nextMBB
9990   newMBB->addSuccessor(nextMBB);
9991   newMBB->addSuccessor(newMBB);
9992
9993   DebugLoc dl = mInstr->getDebugLoc();
9994   // Insert instructions into newMBB based on incoming instruction
9995   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9996          "unexpected number of operands");
9997   MachineOperand& destOper = mInstr->getOperand(0);
9998   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9999   int numArgs = mInstr->getNumOperands() - 1;
10000   for (int i=0; i < numArgs; ++i)
10001     argOpers[i] = &mInstr->getOperand(i+1);
10002
10003   // x86 address has 4 operands: base, index, scale, and displacement
10004   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10005   int valArgIndx = lastAddrIndx + 1;
10006
10007   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10008   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10009   for (int i=0; i <= lastAddrIndx; ++i)
10010     (*MIB).addOperand(*argOpers[i]);
10011
10012   // We only support register and immediate values
10013   assert((argOpers[valArgIndx]->isReg() ||
10014           argOpers[valArgIndx]->isImm()) &&
10015          "invalid operand");
10016
10017   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10018   if (argOpers[valArgIndx]->isReg())
10019     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10020   else
10021     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10022   (*MIB).addOperand(*argOpers[valArgIndx]);
10023
10024   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10025   MIB.addReg(t1);
10026
10027   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10028   MIB.addReg(t1);
10029   MIB.addReg(t2);
10030
10031   // Generate movc
10032   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10033   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10034   MIB.addReg(t2);
10035   MIB.addReg(t1);
10036
10037   // Cmp and exchange if none has modified the memory location
10038   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10039   for (int i=0; i <= lastAddrIndx; ++i)
10040     (*MIB).addOperand(*argOpers[i]);
10041   MIB.addReg(t3);
10042   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10043   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10044                     mInstr->memoperands_end());
10045
10046   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10047   MIB.addReg(X86::EAX);
10048
10049   // insert branch
10050   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10051
10052   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10053   return nextMBB;
10054 }
10055
10056 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10057 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10058 // in the .td file.
10059 MachineBasicBlock *
10060 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10061                             unsigned numArgs, bool memArg) const {
10062   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10063          "Target must have SSE4.2 or AVX features enabled");
10064
10065   DebugLoc dl = MI->getDebugLoc();
10066   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10067   unsigned Opc;
10068   if (!Subtarget->hasAVX()) {
10069     if (memArg)
10070       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10071     else
10072       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10073   } else {
10074     if (memArg)
10075       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10076     else
10077       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10078   }
10079
10080   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10081   for (unsigned i = 0; i < numArgs; ++i) {
10082     MachineOperand &Op = MI->getOperand(i+1);
10083     if (!(Op.isReg() && Op.isImplicit()))
10084       MIB.addOperand(Op);
10085   }
10086   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10087     .addReg(X86::XMM0);
10088
10089   MI->eraseFromParent();
10090   return BB;
10091 }
10092
10093 MachineBasicBlock *
10094 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10095   DebugLoc dl = MI->getDebugLoc();
10096   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10097
10098   // Address into RAX/EAX, other two args into ECX, EDX.
10099   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10100   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10101   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10102   for (int i = 0; i < X86::AddrNumOperands; ++i)
10103     MIB.addOperand(MI->getOperand(i));
10104
10105   unsigned ValOps = X86::AddrNumOperands;
10106   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10107     .addReg(MI->getOperand(ValOps).getReg());
10108   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10109     .addReg(MI->getOperand(ValOps+1).getReg());
10110
10111   // The instruction doesn't actually take any operands though.
10112   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10113
10114   MI->eraseFromParent(); // The pseudo is gone now.
10115   return BB;
10116 }
10117
10118 MachineBasicBlock *
10119 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10120   DebugLoc dl = MI->getDebugLoc();
10121   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10122
10123   // First arg in ECX, the second in EAX.
10124   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10125     .addReg(MI->getOperand(0).getReg());
10126   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10127     .addReg(MI->getOperand(1).getReg());
10128
10129   // The instruction doesn't actually take any operands though.
10130   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10131
10132   MI->eraseFromParent(); // The pseudo is gone now.
10133   return BB;
10134 }
10135
10136 MachineBasicBlock *
10137 X86TargetLowering::EmitVAARG64WithCustomInserter(
10138                    MachineInstr *MI,
10139                    MachineBasicBlock *MBB) const {
10140   // Emit va_arg instruction on X86-64.
10141
10142   // Operands to this pseudo-instruction:
10143   // 0  ) Output        : destination address (reg)
10144   // 1-5) Input         : va_list address (addr, i64mem)
10145   // 6  ) ArgSize       : Size (in bytes) of vararg type
10146   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10147   // 8  ) Align         : Alignment of type
10148   // 9  ) EFLAGS (implicit-def)
10149
10150   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10151   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10152
10153   unsigned DestReg = MI->getOperand(0).getReg();
10154   MachineOperand &Base = MI->getOperand(1);
10155   MachineOperand &Scale = MI->getOperand(2);
10156   MachineOperand &Index = MI->getOperand(3);
10157   MachineOperand &Disp = MI->getOperand(4);
10158   MachineOperand &Segment = MI->getOperand(5);
10159   unsigned ArgSize = MI->getOperand(6).getImm();
10160   unsigned ArgMode = MI->getOperand(7).getImm();
10161   unsigned Align = MI->getOperand(8).getImm();
10162
10163   // Memory Reference
10164   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10165   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10166   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10167
10168   // Machine Information
10169   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10170   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10171   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10172   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10173   DebugLoc DL = MI->getDebugLoc();
10174
10175   // struct va_list {
10176   //   i32   gp_offset
10177   //   i32   fp_offset
10178   //   i64   overflow_area (address)
10179   //   i64   reg_save_area (address)
10180   // }
10181   // sizeof(va_list) = 24
10182   // alignment(va_list) = 8
10183
10184   unsigned TotalNumIntRegs = 6;
10185   unsigned TotalNumXMMRegs = 8;
10186   bool UseGPOffset = (ArgMode == 1);
10187   bool UseFPOffset = (ArgMode == 2);
10188   unsigned MaxOffset = TotalNumIntRegs * 8 +
10189                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10190
10191   /* Align ArgSize to a multiple of 8 */
10192   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10193   bool NeedsAlign = (Align > 8);
10194
10195   MachineBasicBlock *thisMBB = MBB;
10196   MachineBasicBlock *overflowMBB;
10197   MachineBasicBlock *offsetMBB;
10198   MachineBasicBlock *endMBB;
10199
10200   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10201   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10202   unsigned OffsetReg = 0;
10203
10204   if (!UseGPOffset && !UseFPOffset) {
10205     // If we only pull from the overflow region, we don't create a branch.
10206     // We don't need to alter control flow.
10207     OffsetDestReg = 0; // unused
10208     OverflowDestReg = DestReg;
10209
10210     offsetMBB = NULL;
10211     overflowMBB = thisMBB;
10212     endMBB = thisMBB;
10213   } else {
10214     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10215     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10216     // If not, pull from overflow_area. (branch to overflowMBB)
10217     //
10218     //       thisMBB
10219     //         |     .
10220     //         |        .
10221     //     offsetMBB   overflowMBB
10222     //         |        .
10223     //         |     .
10224     //        endMBB
10225
10226     // Registers for the PHI in endMBB
10227     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10228     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10229
10230     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10231     MachineFunction *MF = MBB->getParent();
10232     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10233     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10234     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10235
10236     MachineFunction::iterator MBBIter = MBB;
10237     ++MBBIter;
10238
10239     // Insert the new basic blocks
10240     MF->insert(MBBIter, offsetMBB);
10241     MF->insert(MBBIter, overflowMBB);
10242     MF->insert(MBBIter, endMBB);
10243
10244     // Transfer the remainder of MBB and its successor edges to endMBB.
10245     endMBB->splice(endMBB->begin(), thisMBB,
10246                     llvm::next(MachineBasicBlock::iterator(MI)),
10247                     thisMBB->end());
10248     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10249
10250     // Make offsetMBB and overflowMBB successors of thisMBB
10251     thisMBB->addSuccessor(offsetMBB);
10252     thisMBB->addSuccessor(overflowMBB);
10253
10254     // endMBB is a successor of both offsetMBB and overflowMBB
10255     offsetMBB->addSuccessor(endMBB);
10256     overflowMBB->addSuccessor(endMBB);
10257
10258     // Load the offset value into a register
10259     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10260     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10261       .addOperand(Base)
10262       .addOperand(Scale)
10263       .addOperand(Index)
10264       .addDisp(Disp, UseFPOffset ? 4 : 0)
10265       .addOperand(Segment)
10266       .setMemRefs(MMOBegin, MMOEnd);
10267
10268     // Check if there is enough room left to pull this argument.
10269     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10270       .addReg(OffsetReg)
10271       .addImm(MaxOffset + 8 - ArgSizeA8);
10272
10273     // Branch to "overflowMBB" if offset >= max
10274     // Fall through to "offsetMBB" otherwise
10275     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10276       .addMBB(overflowMBB);
10277   }
10278
10279   // In offsetMBB, emit code to use the reg_save_area.
10280   if (offsetMBB) {
10281     assert(OffsetReg != 0);
10282
10283     // Read the reg_save_area address.
10284     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10285     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10286       .addOperand(Base)
10287       .addOperand(Scale)
10288       .addOperand(Index)
10289       .addDisp(Disp, 16)
10290       .addOperand(Segment)
10291       .setMemRefs(MMOBegin, MMOEnd);
10292
10293     // Zero-extend the offset
10294     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10295       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10296         .addImm(0)
10297         .addReg(OffsetReg)
10298         .addImm(X86::sub_32bit);
10299
10300     // Add the offset to the reg_save_area to get the final address.
10301     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10302       .addReg(OffsetReg64)
10303       .addReg(RegSaveReg);
10304
10305     // Compute the offset for the next argument
10306     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10307     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10308       .addReg(OffsetReg)
10309       .addImm(UseFPOffset ? 16 : 8);
10310
10311     // Store it back into the va_list.
10312     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10313       .addOperand(Base)
10314       .addOperand(Scale)
10315       .addOperand(Index)
10316       .addDisp(Disp, UseFPOffset ? 4 : 0)
10317       .addOperand(Segment)
10318       .addReg(NextOffsetReg)
10319       .setMemRefs(MMOBegin, MMOEnd);
10320
10321     // Jump to endMBB
10322     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10323       .addMBB(endMBB);
10324   }
10325
10326   //
10327   // Emit code to use overflow area
10328   //
10329
10330   // Load the overflow_area address into a register.
10331   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10332   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10333     .addOperand(Base)
10334     .addOperand(Scale)
10335     .addOperand(Index)
10336     .addDisp(Disp, 8)
10337     .addOperand(Segment)
10338     .setMemRefs(MMOBegin, MMOEnd);
10339
10340   // If we need to align it, do so. Otherwise, just copy the address
10341   // to OverflowDestReg.
10342   if (NeedsAlign) {
10343     // Align the overflow address
10344     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10345     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10346
10347     // aligned_addr = (addr + (align-1)) & ~(align-1)
10348     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10349       .addReg(OverflowAddrReg)
10350       .addImm(Align-1);
10351
10352     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10353       .addReg(TmpReg)
10354       .addImm(~(uint64_t)(Align-1));
10355   } else {
10356     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10357       .addReg(OverflowAddrReg);
10358   }
10359
10360   // Compute the next overflow address after this argument.
10361   // (the overflow address should be kept 8-byte aligned)
10362   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10363   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10364     .addReg(OverflowDestReg)
10365     .addImm(ArgSizeA8);
10366
10367   // Store the new overflow address.
10368   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10369     .addOperand(Base)
10370     .addOperand(Scale)
10371     .addOperand(Index)
10372     .addDisp(Disp, 8)
10373     .addOperand(Segment)
10374     .addReg(NextAddrReg)
10375     .setMemRefs(MMOBegin, MMOEnd);
10376
10377   // If we branched, emit the PHI to the front of endMBB.
10378   if (offsetMBB) {
10379     BuildMI(*endMBB, endMBB->begin(), DL,
10380             TII->get(X86::PHI), DestReg)
10381       .addReg(OffsetDestReg).addMBB(offsetMBB)
10382       .addReg(OverflowDestReg).addMBB(overflowMBB);
10383   }
10384
10385   // Erase the pseudo instruction
10386   MI->eraseFromParent();
10387
10388   return endMBB;
10389 }
10390
10391 MachineBasicBlock *
10392 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10393                                                  MachineInstr *MI,
10394                                                  MachineBasicBlock *MBB) const {
10395   // Emit code to save XMM registers to the stack. The ABI says that the
10396   // number of registers to save is given in %al, so it's theoretically
10397   // possible to do an indirect jump trick to avoid saving all of them,
10398   // however this code takes a simpler approach and just executes all
10399   // of the stores if %al is non-zero. It's less code, and it's probably
10400   // easier on the hardware branch predictor, and stores aren't all that
10401   // expensive anyway.
10402
10403   // Create the new basic blocks. One block contains all the XMM stores,
10404   // and one block is the final destination regardless of whether any
10405   // stores were performed.
10406   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10407   MachineFunction *F = MBB->getParent();
10408   MachineFunction::iterator MBBIter = MBB;
10409   ++MBBIter;
10410   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10411   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10412   F->insert(MBBIter, XMMSaveMBB);
10413   F->insert(MBBIter, EndMBB);
10414
10415   // Transfer the remainder of MBB and its successor edges to EndMBB.
10416   EndMBB->splice(EndMBB->begin(), MBB,
10417                  llvm::next(MachineBasicBlock::iterator(MI)),
10418                  MBB->end());
10419   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10420
10421   // The original block will now fall through to the XMM save block.
10422   MBB->addSuccessor(XMMSaveMBB);
10423   // The XMMSaveMBB will fall through to the end block.
10424   XMMSaveMBB->addSuccessor(EndMBB);
10425
10426   // Now add the instructions.
10427   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10428   DebugLoc DL = MI->getDebugLoc();
10429
10430   unsigned CountReg = MI->getOperand(0).getReg();
10431   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10432   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10433
10434   if (!Subtarget->isTargetWin64()) {
10435     // If %al is 0, branch around the XMM save block.
10436     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10437     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10438     MBB->addSuccessor(EndMBB);
10439   }
10440
10441   // In the XMM save block, save all the XMM argument registers.
10442   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10443     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10444     MachineMemOperand *MMO =
10445       F->getMachineMemOperand(
10446           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10447         MachineMemOperand::MOStore,
10448         /*Size=*/16, /*Align=*/16);
10449     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10450       .addFrameIndex(RegSaveFrameIndex)
10451       .addImm(/*Scale=*/1)
10452       .addReg(/*IndexReg=*/0)
10453       .addImm(/*Disp=*/Offset)
10454       .addReg(/*Segment=*/0)
10455       .addReg(MI->getOperand(i).getReg())
10456       .addMemOperand(MMO);
10457   }
10458
10459   MI->eraseFromParent();   // The pseudo instruction is gone now.
10460
10461   return EndMBB;
10462 }
10463
10464 MachineBasicBlock *
10465 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10466                                      MachineBasicBlock *BB) const {
10467   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10468   DebugLoc DL = MI->getDebugLoc();
10469
10470   // To "insert" a SELECT_CC instruction, we actually have to insert the
10471   // diamond control-flow pattern.  The incoming instruction knows the
10472   // destination vreg to set, the condition code register to branch on, the
10473   // true/false values to select between, and a branch opcode to use.
10474   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10475   MachineFunction::iterator It = BB;
10476   ++It;
10477
10478   //  thisMBB:
10479   //  ...
10480   //   TrueVal = ...
10481   //   cmpTY ccX, r1, r2
10482   //   bCC copy1MBB
10483   //   fallthrough --> copy0MBB
10484   MachineBasicBlock *thisMBB = BB;
10485   MachineFunction *F = BB->getParent();
10486   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10487   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10488   F->insert(It, copy0MBB);
10489   F->insert(It, sinkMBB);
10490
10491   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10492   // live into the sink and copy blocks.
10493   const MachineFunction *MF = BB->getParent();
10494   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10495   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10496
10497   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10498     const MachineOperand &MO = MI->getOperand(I);
10499     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10500     unsigned Reg = MO.getReg();
10501     if (Reg != X86::EFLAGS) continue;
10502     copy0MBB->addLiveIn(Reg);
10503     sinkMBB->addLiveIn(Reg);
10504   }
10505
10506   // Transfer the remainder of BB and its successor edges to sinkMBB.
10507   sinkMBB->splice(sinkMBB->begin(), BB,
10508                   llvm::next(MachineBasicBlock::iterator(MI)),
10509                   BB->end());
10510   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10511
10512   // Add the true and fallthrough blocks as its successors.
10513   BB->addSuccessor(copy0MBB);
10514   BB->addSuccessor(sinkMBB);
10515
10516   // Create the conditional branch instruction.
10517   unsigned Opc =
10518     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10519   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10520
10521   //  copy0MBB:
10522   //   %FalseValue = ...
10523   //   # fallthrough to sinkMBB
10524   copy0MBB->addSuccessor(sinkMBB);
10525
10526   //  sinkMBB:
10527   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10528   //  ...
10529   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10530           TII->get(X86::PHI), MI->getOperand(0).getReg())
10531     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10532     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10533
10534   MI->eraseFromParent();   // The pseudo instruction is gone now.
10535   return sinkMBB;
10536 }
10537
10538 MachineBasicBlock *
10539 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10540                                           MachineBasicBlock *BB) const {
10541   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10542   DebugLoc DL = MI->getDebugLoc();
10543
10544   assert(!Subtarget->isTargetEnvMacho());
10545
10546   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10547   // non-trivial part is impdef of ESP.
10548
10549   if (Subtarget->isTargetWin64()) {
10550     if (Subtarget->isTargetCygMing()) {
10551       // ___chkstk(Mingw64):
10552       // Clobbers R10, R11, RAX and EFLAGS.
10553       // Updates RSP.
10554       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10555         .addExternalSymbol("___chkstk")
10556         .addReg(X86::RAX, RegState::Implicit)
10557         .addReg(X86::RSP, RegState::Implicit)
10558         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10559         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10560         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10561     } else {
10562       // __chkstk(MSVCRT): does not update stack pointer.
10563       // Clobbers R10, R11 and EFLAGS.
10564       // FIXME: RAX(allocated size) might be reused and not killed.
10565       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10566         .addExternalSymbol("__chkstk")
10567         .addReg(X86::RAX, RegState::Implicit)
10568         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10569       // RAX has the offset to subtracted from RSP.
10570       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10571         .addReg(X86::RSP)
10572         .addReg(X86::RAX);
10573     }
10574   } else {
10575     const char *StackProbeSymbol =
10576       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10577
10578     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10579       .addExternalSymbol(StackProbeSymbol)
10580       .addReg(X86::EAX, RegState::Implicit)
10581       .addReg(X86::ESP, RegState::Implicit)
10582       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10583       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10584       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10585   }
10586
10587   MI->eraseFromParent();   // The pseudo instruction is gone now.
10588   return BB;
10589 }
10590
10591 MachineBasicBlock *
10592 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10593                                       MachineBasicBlock *BB) const {
10594   // This is pretty easy.  We're taking the value that we received from
10595   // our load from the relocation, sticking it in either RDI (x86-64)
10596   // or EAX and doing an indirect call.  The return value will then
10597   // be in the normal return register.
10598   const X86InstrInfo *TII
10599     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10600   DebugLoc DL = MI->getDebugLoc();
10601   MachineFunction *F = BB->getParent();
10602
10603   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10604   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10605
10606   if (Subtarget->is64Bit()) {
10607     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10608                                       TII->get(X86::MOV64rm), X86::RDI)
10609     .addReg(X86::RIP)
10610     .addImm(0).addReg(0)
10611     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10612                       MI->getOperand(3).getTargetFlags())
10613     .addReg(0);
10614     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10615     addDirectMem(MIB, X86::RDI);
10616   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10617     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10618                                       TII->get(X86::MOV32rm), X86::EAX)
10619     .addReg(0)
10620     .addImm(0).addReg(0)
10621     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10622                       MI->getOperand(3).getTargetFlags())
10623     .addReg(0);
10624     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10625     addDirectMem(MIB, X86::EAX);
10626   } else {
10627     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10628                                       TII->get(X86::MOV32rm), X86::EAX)
10629     .addReg(TII->getGlobalBaseReg(F))
10630     .addImm(0).addReg(0)
10631     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10632                       MI->getOperand(3).getTargetFlags())
10633     .addReg(0);
10634     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10635     addDirectMem(MIB, X86::EAX);
10636   }
10637
10638   MI->eraseFromParent(); // The pseudo instruction is gone now.
10639   return BB;
10640 }
10641
10642 MachineBasicBlock *
10643 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10644                                                MachineBasicBlock *BB) const {
10645   switch (MI->getOpcode()) {
10646   default: assert(false && "Unexpected instr type to insert");
10647   case X86::TAILJMPd64:
10648   case X86::TAILJMPr64:
10649   case X86::TAILJMPm64:
10650     assert(!"TAILJMP64 would not be touched here.");
10651   case X86::TCRETURNdi64:
10652   case X86::TCRETURNri64:
10653   case X86::TCRETURNmi64:
10654     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10655     // On AMD64, additional defs should be added before register allocation.
10656     if (!Subtarget->isTargetWin64()) {
10657       MI->addRegisterDefined(X86::RSI);
10658       MI->addRegisterDefined(X86::RDI);
10659       MI->addRegisterDefined(X86::XMM6);
10660       MI->addRegisterDefined(X86::XMM7);
10661       MI->addRegisterDefined(X86::XMM8);
10662       MI->addRegisterDefined(X86::XMM9);
10663       MI->addRegisterDefined(X86::XMM10);
10664       MI->addRegisterDefined(X86::XMM11);
10665       MI->addRegisterDefined(X86::XMM12);
10666       MI->addRegisterDefined(X86::XMM13);
10667       MI->addRegisterDefined(X86::XMM14);
10668       MI->addRegisterDefined(X86::XMM15);
10669     }
10670     return BB;
10671   case X86::WIN_ALLOCA:
10672     return EmitLoweredWinAlloca(MI, BB);
10673   case X86::TLSCall_32:
10674   case X86::TLSCall_64:
10675     return EmitLoweredTLSCall(MI, BB);
10676   case X86::CMOV_GR8:
10677   case X86::CMOV_FR32:
10678   case X86::CMOV_FR64:
10679   case X86::CMOV_V4F32:
10680   case X86::CMOV_V2F64:
10681   case X86::CMOV_V2I64:
10682   case X86::CMOV_GR16:
10683   case X86::CMOV_GR32:
10684   case X86::CMOV_RFP32:
10685   case X86::CMOV_RFP64:
10686   case X86::CMOV_RFP80:
10687     return EmitLoweredSelect(MI, BB);
10688
10689   case X86::FP32_TO_INT16_IN_MEM:
10690   case X86::FP32_TO_INT32_IN_MEM:
10691   case X86::FP32_TO_INT64_IN_MEM:
10692   case X86::FP64_TO_INT16_IN_MEM:
10693   case X86::FP64_TO_INT32_IN_MEM:
10694   case X86::FP64_TO_INT64_IN_MEM:
10695   case X86::FP80_TO_INT16_IN_MEM:
10696   case X86::FP80_TO_INT32_IN_MEM:
10697   case X86::FP80_TO_INT64_IN_MEM: {
10698     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10699     DebugLoc DL = MI->getDebugLoc();
10700
10701     // Change the floating point control register to use "round towards zero"
10702     // mode when truncating to an integer value.
10703     MachineFunction *F = BB->getParent();
10704     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10705     addFrameReference(BuildMI(*BB, MI, DL,
10706                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10707
10708     // Load the old value of the high byte of the control word...
10709     unsigned OldCW =
10710       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10711     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10712                       CWFrameIdx);
10713
10714     // Set the high part to be round to zero...
10715     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10716       .addImm(0xC7F);
10717
10718     // Reload the modified control word now...
10719     addFrameReference(BuildMI(*BB, MI, DL,
10720                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10721
10722     // Restore the memory image of control word to original value
10723     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10724       .addReg(OldCW);
10725
10726     // Get the X86 opcode to use.
10727     unsigned Opc;
10728     switch (MI->getOpcode()) {
10729     default: llvm_unreachable("illegal opcode!");
10730     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10731     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10732     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10733     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10734     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10735     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10736     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10737     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10738     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10739     }
10740
10741     X86AddressMode AM;
10742     MachineOperand &Op = MI->getOperand(0);
10743     if (Op.isReg()) {
10744       AM.BaseType = X86AddressMode::RegBase;
10745       AM.Base.Reg = Op.getReg();
10746     } else {
10747       AM.BaseType = X86AddressMode::FrameIndexBase;
10748       AM.Base.FrameIndex = Op.getIndex();
10749     }
10750     Op = MI->getOperand(1);
10751     if (Op.isImm())
10752       AM.Scale = Op.getImm();
10753     Op = MI->getOperand(2);
10754     if (Op.isImm())
10755       AM.IndexReg = Op.getImm();
10756     Op = MI->getOperand(3);
10757     if (Op.isGlobal()) {
10758       AM.GV = Op.getGlobal();
10759     } else {
10760       AM.Disp = Op.getImm();
10761     }
10762     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10763                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10764
10765     // Reload the original control word now.
10766     addFrameReference(BuildMI(*BB, MI, DL,
10767                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10768
10769     MI->eraseFromParent();   // The pseudo instruction is gone now.
10770     return BB;
10771   }
10772     // String/text processing lowering.
10773   case X86::PCMPISTRM128REG:
10774   case X86::VPCMPISTRM128REG:
10775     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10776   case X86::PCMPISTRM128MEM:
10777   case X86::VPCMPISTRM128MEM:
10778     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10779   case X86::PCMPESTRM128REG:
10780   case X86::VPCMPESTRM128REG:
10781     return EmitPCMP(MI, BB, 5, false /* in mem */);
10782   case X86::PCMPESTRM128MEM:
10783   case X86::VPCMPESTRM128MEM:
10784     return EmitPCMP(MI, BB, 5, true /* in mem */);
10785
10786     // Thread synchronization.
10787   case X86::MONITOR:
10788     return EmitMonitor(MI, BB);
10789   case X86::MWAIT:
10790     return EmitMwait(MI, BB);
10791
10792     // Atomic Lowering.
10793   case X86::ATOMAND32:
10794     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10795                                                X86::AND32ri, X86::MOV32rm,
10796                                                X86::LCMPXCHG32,
10797                                                X86::NOT32r, X86::EAX,
10798                                                X86::GR32RegisterClass);
10799   case X86::ATOMOR32:
10800     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10801                                                X86::OR32ri, X86::MOV32rm,
10802                                                X86::LCMPXCHG32,
10803                                                X86::NOT32r, X86::EAX,
10804                                                X86::GR32RegisterClass);
10805   case X86::ATOMXOR32:
10806     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10807                                                X86::XOR32ri, X86::MOV32rm,
10808                                                X86::LCMPXCHG32,
10809                                                X86::NOT32r, X86::EAX,
10810                                                X86::GR32RegisterClass);
10811   case X86::ATOMNAND32:
10812     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10813                                                X86::AND32ri, X86::MOV32rm,
10814                                                X86::LCMPXCHG32,
10815                                                X86::NOT32r, X86::EAX,
10816                                                X86::GR32RegisterClass, true);
10817   case X86::ATOMMIN32:
10818     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10819   case X86::ATOMMAX32:
10820     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10821   case X86::ATOMUMIN32:
10822     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10823   case X86::ATOMUMAX32:
10824     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10825
10826   case X86::ATOMAND16:
10827     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10828                                                X86::AND16ri, X86::MOV16rm,
10829                                                X86::LCMPXCHG16,
10830                                                X86::NOT16r, X86::AX,
10831                                                X86::GR16RegisterClass);
10832   case X86::ATOMOR16:
10833     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10834                                                X86::OR16ri, X86::MOV16rm,
10835                                                X86::LCMPXCHG16,
10836                                                X86::NOT16r, X86::AX,
10837                                                X86::GR16RegisterClass);
10838   case X86::ATOMXOR16:
10839     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10840                                                X86::XOR16ri, X86::MOV16rm,
10841                                                X86::LCMPXCHG16,
10842                                                X86::NOT16r, X86::AX,
10843                                                X86::GR16RegisterClass);
10844   case X86::ATOMNAND16:
10845     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10846                                                X86::AND16ri, X86::MOV16rm,
10847                                                X86::LCMPXCHG16,
10848                                                X86::NOT16r, X86::AX,
10849                                                X86::GR16RegisterClass, true);
10850   case X86::ATOMMIN16:
10851     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10852   case X86::ATOMMAX16:
10853     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10854   case X86::ATOMUMIN16:
10855     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10856   case X86::ATOMUMAX16:
10857     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10858
10859   case X86::ATOMAND8:
10860     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10861                                                X86::AND8ri, X86::MOV8rm,
10862                                                X86::LCMPXCHG8,
10863                                                X86::NOT8r, X86::AL,
10864                                                X86::GR8RegisterClass);
10865   case X86::ATOMOR8:
10866     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10867                                                X86::OR8ri, X86::MOV8rm,
10868                                                X86::LCMPXCHG8,
10869                                                X86::NOT8r, X86::AL,
10870                                                X86::GR8RegisterClass);
10871   case X86::ATOMXOR8:
10872     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10873                                                X86::XOR8ri, X86::MOV8rm,
10874                                                X86::LCMPXCHG8,
10875                                                X86::NOT8r, X86::AL,
10876                                                X86::GR8RegisterClass);
10877   case X86::ATOMNAND8:
10878     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10879                                                X86::AND8ri, X86::MOV8rm,
10880                                                X86::LCMPXCHG8,
10881                                                X86::NOT8r, X86::AL,
10882                                                X86::GR8RegisterClass, true);
10883   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10884   // This group is for 64-bit host.
10885   case X86::ATOMAND64:
10886     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10887                                                X86::AND64ri32, X86::MOV64rm,
10888                                                X86::LCMPXCHG64,
10889                                                X86::NOT64r, X86::RAX,
10890                                                X86::GR64RegisterClass);
10891   case X86::ATOMOR64:
10892     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10893                                                X86::OR64ri32, X86::MOV64rm,
10894                                                X86::LCMPXCHG64,
10895                                                X86::NOT64r, X86::RAX,
10896                                                X86::GR64RegisterClass);
10897   case X86::ATOMXOR64:
10898     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10899                                                X86::XOR64ri32, X86::MOV64rm,
10900                                                X86::LCMPXCHG64,
10901                                                X86::NOT64r, X86::RAX,
10902                                                X86::GR64RegisterClass);
10903   case X86::ATOMNAND64:
10904     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10905                                                X86::AND64ri32, X86::MOV64rm,
10906                                                X86::LCMPXCHG64,
10907                                                X86::NOT64r, X86::RAX,
10908                                                X86::GR64RegisterClass, true);
10909   case X86::ATOMMIN64:
10910     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10911   case X86::ATOMMAX64:
10912     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10913   case X86::ATOMUMIN64:
10914     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10915   case X86::ATOMUMAX64:
10916     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10917
10918   // This group does 64-bit operations on a 32-bit host.
10919   case X86::ATOMAND6432:
10920     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10921                                                X86::AND32rr, X86::AND32rr,
10922                                                X86::AND32ri, X86::AND32ri,
10923                                                false);
10924   case X86::ATOMOR6432:
10925     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10926                                                X86::OR32rr, X86::OR32rr,
10927                                                X86::OR32ri, X86::OR32ri,
10928                                                false);
10929   case X86::ATOMXOR6432:
10930     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10931                                                X86::XOR32rr, X86::XOR32rr,
10932                                                X86::XOR32ri, X86::XOR32ri,
10933                                                false);
10934   case X86::ATOMNAND6432:
10935     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10936                                                X86::AND32rr, X86::AND32rr,
10937                                                X86::AND32ri, X86::AND32ri,
10938                                                true);
10939   case X86::ATOMADD6432:
10940     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10941                                                X86::ADD32rr, X86::ADC32rr,
10942                                                X86::ADD32ri, X86::ADC32ri,
10943                                                false);
10944   case X86::ATOMSUB6432:
10945     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10946                                                X86::SUB32rr, X86::SBB32rr,
10947                                                X86::SUB32ri, X86::SBB32ri,
10948                                                false);
10949   case X86::ATOMSWAP6432:
10950     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10951                                                X86::MOV32rr, X86::MOV32rr,
10952                                                X86::MOV32ri, X86::MOV32ri,
10953                                                false);
10954   case X86::VASTART_SAVE_XMM_REGS:
10955     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10956
10957   case X86::VAARG_64:
10958     return EmitVAARG64WithCustomInserter(MI, BB);
10959   }
10960 }
10961
10962 //===----------------------------------------------------------------------===//
10963 //                           X86 Optimization Hooks
10964 //===----------------------------------------------------------------------===//
10965
10966 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10967                                                        const APInt &Mask,
10968                                                        APInt &KnownZero,
10969                                                        APInt &KnownOne,
10970                                                        const SelectionDAG &DAG,
10971                                                        unsigned Depth) const {
10972   unsigned Opc = Op.getOpcode();
10973   assert((Opc >= ISD::BUILTIN_OP_END ||
10974           Opc == ISD::INTRINSIC_WO_CHAIN ||
10975           Opc == ISD::INTRINSIC_W_CHAIN ||
10976           Opc == ISD::INTRINSIC_VOID) &&
10977          "Should use MaskedValueIsZero if you don't know whether Op"
10978          " is a target node!");
10979
10980   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10981   switch (Opc) {
10982   default: break;
10983   case X86ISD::ADD:
10984   case X86ISD::SUB:
10985   case X86ISD::ADC:
10986   case X86ISD::SBB:
10987   case X86ISD::SMUL:
10988   case X86ISD::UMUL:
10989   case X86ISD::INC:
10990   case X86ISD::DEC:
10991   case X86ISD::OR:
10992   case X86ISD::XOR:
10993   case X86ISD::AND:
10994     // These nodes' second result is a boolean.
10995     if (Op.getResNo() == 0)
10996       break;
10997     // Fallthrough
10998   case X86ISD::SETCC:
10999     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11000                                        Mask.getBitWidth() - 1);
11001     break;
11002   }
11003 }
11004
11005 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11006                                                          unsigned Depth) const {
11007   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11008   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11009     return Op.getValueType().getScalarType().getSizeInBits();
11010
11011   // Fallback case.
11012   return 1;
11013 }
11014
11015 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11016 /// node is a GlobalAddress + offset.
11017 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11018                                        const GlobalValue* &GA,
11019                                        int64_t &Offset) const {
11020   if (N->getOpcode() == X86ISD::Wrapper) {
11021     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11022       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11023       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11024       return true;
11025     }
11026   }
11027   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11028 }
11029
11030 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11031 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11032 /// if the load addresses are consecutive, non-overlapping, and in the right
11033 /// order.
11034 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11035                                      TargetLowering::DAGCombinerInfo &DCI) {
11036   DebugLoc dl = N->getDebugLoc();
11037   EVT VT = N->getValueType(0);
11038
11039   if (VT.getSizeInBits() != 128)
11040     return SDValue();
11041
11042   // Don't create instructions with illegal types after legalize types has run.
11043   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11044   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11045     return SDValue();
11046
11047   SmallVector<SDValue, 16> Elts;
11048   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11049     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11050
11051   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11052 }
11053
11054 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11055 /// generation and convert it from being a bunch of shuffles and extracts
11056 /// to a simple store and scalar loads to extract the elements.
11057 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11058                                                 const TargetLowering &TLI) {
11059   SDValue InputVector = N->getOperand(0);
11060
11061   // Only operate on vectors of 4 elements, where the alternative shuffling
11062   // gets to be more expensive.
11063   if (InputVector.getValueType() != MVT::v4i32)
11064     return SDValue();
11065
11066   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11067   // single use which is a sign-extend or zero-extend, and all elements are
11068   // used.
11069   SmallVector<SDNode *, 4> Uses;
11070   unsigned ExtractedElements = 0;
11071   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11072        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11073     if (UI.getUse().getResNo() != InputVector.getResNo())
11074       return SDValue();
11075
11076     SDNode *Extract = *UI;
11077     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11078       return SDValue();
11079
11080     if (Extract->getValueType(0) != MVT::i32)
11081       return SDValue();
11082     if (!Extract->hasOneUse())
11083       return SDValue();
11084     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11085         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11086       return SDValue();
11087     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11088       return SDValue();
11089
11090     // Record which element was extracted.
11091     ExtractedElements |=
11092       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11093
11094     Uses.push_back(Extract);
11095   }
11096
11097   // If not all the elements were used, this may not be worthwhile.
11098   if (ExtractedElements != 15)
11099     return SDValue();
11100
11101   // Ok, we've now decided to do the transformation.
11102   DebugLoc dl = InputVector.getDebugLoc();
11103
11104   // Store the value to a temporary stack slot.
11105   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11106   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11107                             MachinePointerInfo(), false, false, 0);
11108
11109   // Replace each use (extract) with a load of the appropriate element.
11110   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11111        UE = Uses.end(); UI != UE; ++UI) {
11112     SDNode *Extract = *UI;
11113
11114     // cOMpute the element's address.
11115     SDValue Idx = Extract->getOperand(1);
11116     unsigned EltSize =
11117         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11118     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11119     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11120
11121     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11122                                      StackPtr, OffsetVal);
11123
11124     // Load the scalar.
11125     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11126                                      ScalarAddr, MachinePointerInfo(),
11127                                      false, false, 0);
11128
11129     // Replace the exact with the load.
11130     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11131   }
11132
11133   // The replacement was made in place; don't return anything.
11134   return SDValue();
11135 }
11136
11137 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11138 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11139                                     const X86Subtarget *Subtarget) {
11140   DebugLoc DL = N->getDebugLoc();
11141   SDValue Cond = N->getOperand(0);
11142   // Get the LHS/RHS of the select.
11143   SDValue LHS = N->getOperand(1);
11144   SDValue RHS = N->getOperand(2);
11145
11146   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11147   // instructions match the semantics of the common C idiom x<y?x:y but not
11148   // x<=y?x:y, because of how they handle negative zero (which can be
11149   // ignored in unsafe-math mode).
11150   if (Subtarget->hasSSE2() &&
11151       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11152       Cond.getOpcode() == ISD::SETCC) {
11153     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11154
11155     unsigned Opcode = 0;
11156     // Check for x CC y ? x : y.
11157     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11158         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11159       switch (CC) {
11160       default: break;
11161       case ISD::SETULT:
11162         // Converting this to a min would handle NaNs incorrectly, and swapping
11163         // the operands would cause it to handle comparisons between positive
11164         // and negative zero incorrectly.
11165         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11166           if (!UnsafeFPMath &&
11167               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11168             break;
11169           std::swap(LHS, RHS);
11170         }
11171         Opcode = X86ISD::FMIN;
11172         break;
11173       case ISD::SETOLE:
11174         // Converting this to a min would handle comparisons between positive
11175         // and negative zero incorrectly.
11176         if (!UnsafeFPMath &&
11177             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11178           break;
11179         Opcode = X86ISD::FMIN;
11180         break;
11181       case ISD::SETULE:
11182         // Converting this to a min would handle both negative zeros and NaNs
11183         // incorrectly, but we can swap the operands to fix both.
11184         std::swap(LHS, RHS);
11185       case ISD::SETOLT:
11186       case ISD::SETLT:
11187       case ISD::SETLE:
11188         Opcode = X86ISD::FMIN;
11189         break;
11190
11191       case ISD::SETOGE:
11192         // Converting this to a max would handle comparisons between positive
11193         // and negative zero incorrectly.
11194         if (!UnsafeFPMath &&
11195             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11196           break;
11197         Opcode = X86ISD::FMAX;
11198         break;
11199       case ISD::SETUGT:
11200         // Converting this to a max would handle NaNs incorrectly, and swapping
11201         // the operands would cause it to handle comparisons between positive
11202         // and negative zero incorrectly.
11203         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11204           if (!UnsafeFPMath &&
11205               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11206             break;
11207           std::swap(LHS, RHS);
11208         }
11209         Opcode = X86ISD::FMAX;
11210         break;
11211       case ISD::SETUGE:
11212         // Converting this to a max would handle both negative zeros and NaNs
11213         // incorrectly, but we can swap the operands to fix both.
11214         std::swap(LHS, RHS);
11215       case ISD::SETOGT:
11216       case ISD::SETGT:
11217       case ISD::SETGE:
11218         Opcode = X86ISD::FMAX;
11219         break;
11220       }
11221     // Check for x CC y ? y : x -- a min/max with reversed arms.
11222     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11223                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11224       switch (CC) {
11225       default: break;
11226       case ISD::SETOGE:
11227         // Converting this to a min would handle comparisons between positive
11228         // and negative zero incorrectly, and swapping the operands would
11229         // cause it to handle NaNs incorrectly.
11230         if (!UnsafeFPMath &&
11231             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11232           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11233             break;
11234           std::swap(LHS, RHS);
11235         }
11236         Opcode = X86ISD::FMIN;
11237         break;
11238       case ISD::SETUGT:
11239         // Converting this to a min would handle NaNs incorrectly.
11240         if (!UnsafeFPMath &&
11241             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11242           break;
11243         Opcode = X86ISD::FMIN;
11244         break;
11245       case ISD::SETUGE:
11246         // Converting this to a min would handle both negative zeros and NaNs
11247         // incorrectly, but we can swap the operands to fix both.
11248         std::swap(LHS, RHS);
11249       case ISD::SETOGT:
11250       case ISD::SETGT:
11251       case ISD::SETGE:
11252         Opcode = X86ISD::FMIN;
11253         break;
11254
11255       case ISD::SETULT:
11256         // Converting this to a max would handle NaNs incorrectly.
11257         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11258           break;
11259         Opcode = X86ISD::FMAX;
11260         break;
11261       case ISD::SETOLE:
11262         // Converting this to a max would handle comparisons between positive
11263         // and negative zero incorrectly, and swapping the operands would
11264         // cause it to handle NaNs incorrectly.
11265         if (!UnsafeFPMath &&
11266             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11267           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11268             break;
11269           std::swap(LHS, RHS);
11270         }
11271         Opcode = X86ISD::FMAX;
11272         break;
11273       case ISD::SETULE:
11274         // Converting this to a max would handle both negative zeros and NaNs
11275         // incorrectly, but we can swap the operands to fix both.
11276         std::swap(LHS, RHS);
11277       case ISD::SETOLT:
11278       case ISD::SETLT:
11279       case ISD::SETLE:
11280         Opcode = X86ISD::FMAX;
11281         break;
11282       }
11283     }
11284
11285     if (Opcode)
11286       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11287   }
11288
11289   // If this is a select between two integer constants, try to do some
11290   // optimizations.
11291   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11292     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11293       // Don't do this for crazy integer types.
11294       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11295         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11296         // so that TrueC (the true value) is larger than FalseC.
11297         bool NeedsCondInvert = false;
11298
11299         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11300             // Efficiently invertible.
11301             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11302              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11303               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11304           NeedsCondInvert = true;
11305           std::swap(TrueC, FalseC);
11306         }
11307
11308         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11309         if (FalseC->getAPIntValue() == 0 &&
11310             TrueC->getAPIntValue().isPowerOf2()) {
11311           if (NeedsCondInvert) // Invert the condition if needed.
11312             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11313                                DAG.getConstant(1, Cond.getValueType()));
11314
11315           // Zero extend the condition if needed.
11316           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11317
11318           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11319           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11320                              DAG.getConstant(ShAmt, MVT::i8));
11321         }
11322
11323         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11324         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11325           if (NeedsCondInvert) // Invert the condition if needed.
11326             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11327                                DAG.getConstant(1, Cond.getValueType()));
11328
11329           // Zero extend the condition if needed.
11330           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11331                              FalseC->getValueType(0), Cond);
11332           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11333                              SDValue(FalseC, 0));
11334         }
11335
11336         // Optimize cases that will turn into an LEA instruction.  This requires
11337         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11338         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11339           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11340           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11341
11342           bool isFastMultiplier = false;
11343           if (Diff < 10) {
11344             switch ((unsigned char)Diff) {
11345               default: break;
11346               case 1:  // result = add base, cond
11347               case 2:  // result = lea base(    , cond*2)
11348               case 3:  // result = lea base(cond, cond*2)
11349               case 4:  // result = lea base(    , cond*4)
11350               case 5:  // result = lea base(cond, cond*4)
11351               case 8:  // result = lea base(    , cond*8)
11352               case 9:  // result = lea base(cond, cond*8)
11353                 isFastMultiplier = true;
11354                 break;
11355             }
11356           }
11357
11358           if (isFastMultiplier) {
11359             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11360             if (NeedsCondInvert) // Invert the condition if needed.
11361               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11362                                  DAG.getConstant(1, Cond.getValueType()));
11363
11364             // Zero extend the condition if needed.
11365             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11366                                Cond);
11367             // Scale the condition by the difference.
11368             if (Diff != 1)
11369               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11370                                  DAG.getConstant(Diff, Cond.getValueType()));
11371
11372             // Add the base if non-zero.
11373             if (FalseC->getAPIntValue() != 0)
11374               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11375                                  SDValue(FalseC, 0));
11376             return Cond;
11377           }
11378         }
11379       }
11380   }
11381
11382   return SDValue();
11383 }
11384
11385 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11386 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11387                                   TargetLowering::DAGCombinerInfo &DCI) {
11388   DebugLoc DL = N->getDebugLoc();
11389
11390   // If the flag operand isn't dead, don't touch this CMOV.
11391   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11392     return SDValue();
11393
11394   SDValue FalseOp = N->getOperand(0);
11395   SDValue TrueOp = N->getOperand(1);
11396   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11397   SDValue Cond = N->getOperand(3);
11398   if (CC == X86::COND_E || CC == X86::COND_NE) {
11399     switch (Cond.getOpcode()) {
11400     default: break;
11401     case X86ISD::BSR:
11402     case X86ISD::BSF:
11403       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11404       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11405         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11406     }
11407   }
11408
11409   // If this is a select between two integer constants, try to do some
11410   // optimizations.  Note that the operands are ordered the opposite of SELECT
11411   // operands.
11412   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11413     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11414       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11415       // larger than FalseC (the false value).
11416       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11417         CC = X86::GetOppositeBranchCondition(CC);
11418         std::swap(TrueC, FalseC);
11419       }
11420
11421       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11422       // This is efficient for any integer data type (including i8/i16) and
11423       // shift amount.
11424       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11425         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11426                            DAG.getConstant(CC, MVT::i8), Cond);
11427
11428         // Zero extend the condition if needed.
11429         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11430
11431         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11432         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11433                            DAG.getConstant(ShAmt, MVT::i8));
11434         if (N->getNumValues() == 2)  // Dead flag value?
11435           return DCI.CombineTo(N, Cond, SDValue());
11436         return Cond;
11437       }
11438
11439       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11440       // for any integer data type, including i8/i16.
11441       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11442         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11443                            DAG.getConstant(CC, MVT::i8), Cond);
11444
11445         // Zero extend the condition if needed.
11446         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11447                            FalseC->getValueType(0), Cond);
11448         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11449                            SDValue(FalseC, 0));
11450
11451         if (N->getNumValues() == 2)  // Dead flag value?
11452           return DCI.CombineTo(N, Cond, SDValue());
11453         return Cond;
11454       }
11455
11456       // Optimize cases that will turn into an LEA instruction.  This requires
11457       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11458       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11459         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11460         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11461
11462         bool isFastMultiplier = false;
11463         if (Diff < 10) {
11464           switch ((unsigned char)Diff) {
11465           default: break;
11466           case 1:  // result = add base, cond
11467           case 2:  // result = lea base(    , cond*2)
11468           case 3:  // result = lea base(cond, cond*2)
11469           case 4:  // result = lea base(    , cond*4)
11470           case 5:  // result = lea base(cond, cond*4)
11471           case 8:  // result = lea base(    , cond*8)
11472           case 9:  // result = lea base(cond, cond*8)
11473             isFastMultiplier = true;
11474             break;
11475           }
11476         }
11477
11478         if (isFastMultiplier) {
11479           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11480           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11481                              DAG.getConstant(CC, MVT::i8), Cond);
11482           // Zero extend the condition if needed.
11483           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11484                              Cond);
11485           // Scale the condition by the difference.
11486           if (Diff != 1)
11487             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11488                                DAG.getConstant(Diff, Cond.getValueType()));
11489
11490           // Add the base if non-zero.
11491           if (FalseC->getAPIntValue() != 0)
11492             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11493                                SDValue(FalseC, 0));
11494           if (N->getNumValues() == 2)  // Dead flag value?
11495             return DCI.CombineTo(N, Cond, SDValue());
11496           return Cond;
11497         }
11498       }
11499     }
11500   }
11501   return SDValue();
11502 }
11503
11504
11505 /// PerformMulCombine - Optimize a single multiply with constant into two
11506 /// in order to implement it with two cheaper instructions, e.g.
11507 /// LEA + SHL, LEA + LEA.
11508 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11509                                  TargetLowering::DAGCombinerInfo &DCI) {
11510   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11511     return SDValue();
11512
11513   EVT VT = N->getValueType(0);
11514   if (VT != MVT::i64)
11515     return SDValue();
11516
11517   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11518   if (!C)
11519     return SDValue();
11520   uint64_t MulAmt = C->getZExtValue();
11521   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11522     return SDValue();
11523
11524   uint64_t MulAmt1 = 0;
11525   uint64_t MulAmt2 = 0;
11526   if ((MulAmt % 9) == 0) {
11527     MulAmt1 = 9;
11528     MulAmt2 = MulAmt / 9;
11529   } else if ((MulAmt % 5) == 0) {
11530     MulAmt1 = 5;
11531     MulAmt2 = MulAmt / 5;
11532   } else if ((MulAmt % 3) == 0) {
11533     MulAmt1 = 3;
11534     MulAmt2 = MulAmt / 3;
11535   }
11536   if (MulAmt2 &&
11537       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11538     DebugLoc DL = N->getDebugLoc();
11539
11540     if (isPowerOf2_64(MulAmt2) &&
11541         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11542       // If second multiplifer is pow2, issue it first. We want the multiply by
11543       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11544       // is an add.
11545       std::swap(MulAmt1, MulAmt2);
11546
11547     SDValue NewMul;
11548     if (isPowerOf2_64(MulAmt1))
11549       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11550                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11551     else
11552       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11553                            DAG.getConstant(MulAmt1, VT));
11554
11555     if (isPowerOf2_64(MulAmt2))
11556       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11557                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11558     else
11559       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11560                            DAG.getConstant(MulAmt2, VT));
11561
11562     // Do not add new nodes to DAG combiner worklist.
11563     DCI.CombineTo(N, NewMul, false);
11564   }
11565   return SDValue();
11566 }
11567
11568 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11569   SDValue N0 = N->getOperand(0);
11570   SDValue N1 = N->getOperand(1);
11571   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11572   EVT VT = N0.getValueType();
11573
11574   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11575   // since the result of setcc_c is all zero's or all ones.
11576   if (N1C && N0.getOpcode() == ISD::AND &&
11577       N0.getOperand(1).getOpcode() == ISD::Constant) {
11578     SDValue N00 = N0.getOperand(0);
11579     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11580         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11581           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11582          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11583       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11584       APInt ShAmt = N1C->getAPIntValue();
11585       Mask = Mask.shl(ShAmt);
11586       if (Mask != 0)
11587         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11588                            N00, DAG.getConstant(Mask, VT));
11589     }
11590   }
11591
11592   return SDValue();
11593 }
11594
11595 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11596 ///                       when possible.
11597 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11598                                    const X86Subtarget *Subtarget) {
11599   EVT VT = N->getValueType(0);
11600   if (!VT.isVector() && VT.isInteger() &&
11601       N->getOpcode() == ISD::SHL)
11602     return PerformSHLCombine(N, DAG);
11603
11604   // On X86 with SSE2 support, we can transform this to a vector shift if
11605   // all elements are shifted by the same amount.  We can't do this in legalize
11606   // because the a constant vector is typically transformed to a constant pool
11607   // so we have no knowledge of the shift amount.
11608   if (!Subtarget->hasSSE2())
11609     return SDValue();
11610
11611   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11612     return SDValue();
11613
11614   SDValue ShAmtOp = N->getOperand(1);
11615   EVT EltVT = VT.getVectorElementType();
11616   DebugLoc DL = N->getDebugLoc();
11617   SDValue BaseShAmt = SDValue();
11618   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11619     unsigned NumElts = VT.getVectorNumElements();
11620     unsigned i = 0;
11621     for (; i != NumElts; ++i) {
11622       SDValue Arg = ShAmtOp.getOperand(i);
11623       if (Arg.getOpcode() == ISD::UNDEF) continue;
11624       BaseShAmt = Arg;
11625       break;
11626     }
11627     for (; i != NumElts; ++i) {
11628       SDValue Arg = ShAmtOp.getOperand(i);
11629       if (Arg.getOpcode() == ISD::UNDEF) continue;
11630       if (Arg != BaseShAmt) {
11631         return SDValue();
11632       }
11633     }
11634   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11635              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11636     SDValue InVec = ShAmtOp.getOperand(0);
11637     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11638       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11639       unsigned i = 0;
11640       for (; i != NumElts; ++i) {
11641         SDValue Arg = InVec.getOperand(i);
11642         if (Arg.getOpcode() == ISD::UNDEF) continue;
11643         BaseShAmt = Arg;
11644         break;
11645       }
11646     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11647        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11648          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11649          if (C->getZExtValue() == SplatIdx)
11650            BaseShAmt = InVec.getOperand(1);
11651        }
11652     }
11653     if (BaseShAmt.getNode() == 0)
11654       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11655                               DAG.getIntPtrConstant(0));
11656   } else
11657     return SDValue();
11658
11659   // The shift amount is an i32.
11660   if (EltVT.bitsGT(MVT::i32))
11661     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11662   else if (EltVT.bitsLT(MVT::i32))
11663     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11664
11665   // The shift amount is identical so we can do a vector shift.
11666   SDValue  ValOp = N->getOperand(0);
11667   switch (N->getOpcode()) {
11668   default:
11669     llvm_unreachable("Unknown shift opcode!");
11670     break;
11671   case ISD::SHL:
11672     if (VT == MVT::v2i64)
11673       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11674                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11675                          ValOp, BaseShAmt);
11676     if (VT == MVT::v4i32)
11677       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11678                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11679                          ValOp, BaseShAmt);
11680     if (VT == MVT::v8i16)
11681       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11682                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11683                          ValOp, BaseShAmt);
11684     break;
11685   case ISD::SRA:
11686     if (VT == MVT::v4i32)
11687       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11688                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11689                          ValOp, BaseShAmt);
11690     if (VT == MVT::v8i16)
11691       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11692                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11693                          ValOp, BaseShAmt);
11694     break;
11695   case ISD::SRL:
11696     if (VT == MVT::v2i64)
11697       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11698                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11699                          ValOp, BaseShAmt);
11700     if (VT == MVT::v4i32)
11701       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11702                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11703                          ValOp, BaseShAmt);
11704     if (VT ==  MVT::v8i16)
11705       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11706                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11707                          ValOp, BaseShAmt);
11708     break;
11709   }
11710   return SDValue();
11711 }
11712
11713
11714 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11715                                  TargetLowering::DAGCombinerInfo &DCI,
11716                                  const X86Subtarget *Subtarget) {
11717   if (DCI.isBeforeLegalizeOps())
11718     return SDValue();
11719
11720   // Want to form PANDN nodes, in the hopes of then easily combining them with
11721   // OR and AND nodes to form PBLEND/PSIGN.
11722   EVT VT = N->getValueType(0);
11723   if (VT != MVT::v2i64)
11724     return SDValue();
11725
11726   SDValue N0 = N->getOperand(0);
11727   SDValue N1 = N->getOperand(1);
11728   DebugLoc DL = N->getDebugLoc();
11729
11730   // Check LHS for vnot
11731   if (N0.getOpcode() == ISD::XOR &&
11732       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11733     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11734
11735   // Check RHS for vnot
11736   if (N1.getOpcode() == ISD::XOR &&
11737       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11738     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11739
11740   return SDValue();
11741 }
11742
11743 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11744                                 TargetLowering::DAGCombinerInfo &DCI,
11745                                 const X86Subtarget *Subtarget) {
11746   if (DCI.isBeforeLegalizeOps())
11747     return SDValue();
11748
11749   EVT VT = N->getValueType(0);
11750   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11751     return SDValue();
11752
11753   SDValue N0 = N->getOperand(0);
11754   SDValue N1 = N->getOperand(1);
11755
11756   // look for psign/blend
11757   if (Subtarget->hasSSSE3()) {
11758     if (VT == MVT::v2i64) {
11759       // Canonicalize pandn to RHS
11760       if (N0.getOpcode() == X86ISD::PANDN)
11761         std::swap(N0, N1);
11762       // or (and (m, x), (pandn m, y))
11763       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11764         SDValue Mask = N1.getOperand(0);
11765         SDValue X    = N1.getOperand(1);
11766         SDValue Y;
11767         if (N0.getOperand(0) == Mask)
11768           Y = N0.getOperand(1);
11769         if (N0.getOperand(1) == Mask)
11770           Y = N0.getOperand(0);
11771
11772         // Check to see if the mask appeared in both the AND and PANDN and
11773         if (!Y.getNode())
11774           return SDValue();
11775
11776         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11777         if (Mask.getOpcode() != ISD::BITCAST ||
11778             X.getOpcode() != ISD::BITCAST ||
11779             Y.getOpcode() != ISD::BITCAST)
11780           return SDValue();
11781
11782         // Look through mask bitcast.
11783         Mask = Mask.getOperand(0);
11784         EVT MaskVT = Mask.getValueType();
11785
11786         // Validate that the Mask operand is a vector sra node.  The sra node
11787         // will be an intrinsic.
11788         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11789           return SDValue();
11790
11791         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11792         // there is no psrai.b
11793         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11794         case Intrinsic::x86_sse2_psrai_w:
11795         case Intrinsic::x86_sse2_psrai_d:
11796           break;
11797         default: return SDValue();
11798         }
11799
11800         // Check that the SRA is all signbits.
11801         SDValue SraC = Mask.getOperand(2);
11802         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11803         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11804         if ((SraAmt + 1) != EltBits)
11805           return SDValue();
11806
11807         DebugLoc DL = N->getDebugLoc();
11808
11809         // Now we know we at least have a plendvb with the mask val.  See if
11810         // we can form a psignb/w/d.
11811         // psign = x.type == y.type == mask.type && y = sub(0, x);
11812         X = X.getOperand(0);
11813         Y = Y.getOperand(0);
11814         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11815             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11816             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11817           unsigned Opc = 0;
11818           switch (EltBits) {
11819           case 8: Opc = X86ISD::PSIGNB; break;
11820           case 16: Opc = X86ISD::PSIGNW; break;
11821           case 32: Opc = X86ISD::PSIGND; break;
11822           default: break;
11823           }
11824           if (Opc) {
11825             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11826             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11827           }
11828         }
11829         // PBLENDVB only available on SSE 4.1
11830         if (!Subtarget->hasSSE41())
11831           return SDValue();
11832
11833         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11834         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11835         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11836         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11837         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11838       }
11839     }
11840   }
11841
11842   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11843   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11844     std::swap(N0, N1);
11845   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11846     return SDValue();
11847   if (!N0.hasOneUse() || !N1.hasOneUse())
11848     return SDValue();
11849
11850   SDValue ShAmt0 = N0.getOperand(1);
11851   if (ShAmt0.getValueType() != MVT::i8)
11852     return SDValue();
11853   SDValue ShAmt1 = N1.getOperand(1);
11854   if (ShAmt1.getValueType() != MVT::i8)
11855     return SDValue();
11856   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11857     ShAmt0 = ShAmt0.getOperand(0);
11858   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11859     ShAmt1 = ShAmt1.getOperand(0);
11860
11861   DebugLoc DL = N->getDebugLoc();
11862   unsigned Opc = X86ISD::SHLD;
11863   SDValue Op0 = N0.getOperand(0);
11864   SDValue Op1 = N1.getOperand(0);
11865   if (ShAmt0.getOpcode() == ISD::SUB) {
11866     Opc = X86ISD::SHRD;
11867     std::swap(Op0, Op1);
11868     std::swap(ShAmt0, ShAmt1);
11869   }
11870
11871   unsigned Bits = VT.getSizeInBits();
11872   if (ShAmt1.getOpcode() == ISD::SUB) {
11873     SDValue Sum = ShAmt1.getOperand(0);
11874     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11875       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11876       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11877         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11878       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11879         return DAG.getNode(Opc, DL, VT,
11880                            Op0, Op1,
11881                            DAG.getNode(ISD::TRUNCATE, DL,
11882                                        MVT::i8, ShAmt0));
11883     }
11884   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11885     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11886     if (ShAmt0C &&
11887         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11888       return DAG.getNode(Opc, DL, VT,
11889                          N0.getOperand(0), N1.getOperand(0),
11890                          DAG.getNode(ISD::TRUNCATE, DL,
11891                                        MVT::i8, ShAmt0));
11892   }
11893
11894   return SDValue();
11895 }
11896
11897 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11898 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11899                                    const X86Subtarget *Subtarget) {
11900   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11901   // the FP state in cases where an emms may be missing.
11902   // A preferable solution to the general problem is to figure out the right
11903   // places to insert EMMS.  This qualifies as a quick hack.
11904
11905   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11906   StoreSDNode *St = cast<StoreSDNode>(N);
11907   EVT VT = St->getValue().getValueType();
11908   if (VT.getSizeInBits() != 64)
11909     return SDValue();
11910
11911   const Function *F = DAG.getMachineFunction().getFunction();
11912   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11913   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11914     && Subtarget->hasSSE2();
11915   if ((VT.isVector() ||
11916        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11917       isa<LoadSDNode>(St->getValue()) &&
11918       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11919       St->getChain().hasOneUse() && !St->isVolatile()) {
11920     SDNode* LdVal = St->getValue().getNode();
11921     LoadSDNode *Ld = 0;
11922     int TokenFactorIndex = -1;
11923     SmallVector<SDValue, 8> Ops;
11924     SDNode* ChainVal = St->getChain().getNode();
11925     // Must be a store of a load.  We currently handle two cases:  the load
11926     // is a direct child, and it's under an intervening TokenFactor.  It is
11927     // possible to dig deeper under nested TokenFactors.
11928     if (ChainVal == LdVal)
11929       Ld = cast<LoadSDNode>(St->getChain());
11930     else if (St->getValue().hasOneUse() &&
11931              ChainVal->getOpcode() == ISD::TokenFactor) {
11932       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11933         if (ChainVal->getOperand(i).getNode() == LdVal) {
11934           TokenFactorIndex = i;
11935           Ld = cast<LoadSDNode>(St->getValue());
11936         } else
11937           Ops.push_back(ChainVal->getOperand(i));
11938       }
11939     }
11940
11941     if (!Ld || !ISD::isNormalLoad(Ld))
11942       return SDValue();
11943
11944     // If this is not the MMX case, i.e. we are just turning i64 load/store
11945     // into f64 load/store, avoid the transformation if there are multiple
11946     // uses of the loaded value.
11947     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11948       return SDValue();
11949
11950     DebugLoc LdDL = Ld->getDebugLoc();
11951     DebugLoc StDL = N->getDebugLoc();
11952     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11953     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11954     // pair instead.
11955     if (Subtarget->is64Bit() || F64IsLegal) {
11956       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11957       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11958                                   Ld->getPointerInfo(), Ld->isVolatile(),
11959                                   Ld->isNonTemporal(), Ld->getAlignment());
11960       SDValue NewChain = NewLd.getValue(1);
11961       if (TokenFactorIndex != -1) {
11962         Ops.push_back(NewChain);
11963         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11964                                Ops.size());
11965       }
11966       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11967                           St->getPointerInfo(),
11968                           St->isVolatile(), St->isNonTemporal(),
11969                           St->getAlignment());
11970     }
11971
11972     // Otherwise, lower to two pairs of 32-bit loads / stores.
11973     SDValue LoAddr = Ld->getBasePtr();
11974     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11975                                  DAG.getConstant(4, MVT::i32));
11976
11977     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11978                                Ld->getPointerInfo(),
11979                                Ld->isVolatile(), Ld->isNonTemporal(),
11980                                Ld->getAlignment());
11981     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11982                                Ld->getPointerInfo().getWithOffset(4),
11983                                Ld->isVolatile(), Ld->isNonTemporal(),
11984                                MinAlign(Ld->getAlignment(), 4));
11985
11986     SDValue NewChain = LoLd.getValue(1);
11987     if (TokenFactorIndex != -1) {
11988       Ops.push_back(LoLd);
11989       Ops.push_back(HiLd);
11990       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11991                              Ops.size());
11992     }
11993
11994     LoAddr = St->getBasePtr();
11995     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11996                          DAG.getConstant(4, MVT::i32));
11997
11998     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11999                                 St->getPointerInfo(),
12000                                 St->isVolatile(), St->isNonTemporal(),
12001                                 St->getAlignment());
12002     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12003                                 St->getPointerInfo().getWithOffset(4),
12004                                 St->isVolatile(),
12005                                 St->isNonTemporal(),
12006                                 MinAlign(St->getAlignment(), 4));
12007     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12008   }
12009   return SDValue();
12010 }
12011
12012 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12013 /// X86ISD::FXOR nodes.
12014 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12015   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12016   // F[X]OR(0.0, x) -> x
12017   // F[X]OR(x, 0.0) -> x
12018   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12019     if (C->getValueAPF().isPosZero())
12020       return N->getOperand(1);
12021   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12022     if (C->getValueAPF().isPosZero())
12023       return N->getOperand(0);
12024   return SDValue();
12025 }
12026
12027 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12028 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12029   // FAND(0.0, x) -> 0.0
12030   // FAND(x, 0.0) -> 0.0
12031   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12032     if (C->getValueAPF().isPosZero())
12033       return N->getOperand(0);
12034   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12035     if (C->getValueAPF().isPosZero())
12036       return N->getOperand(1);
12037   return SDValue();
12038 }
12039
12040 static SDValue PerformBTCombine(SDNode *N,
12041                                 SelectionDAG &DAG,
12042                                 TargetLowering::DAGCombinerInfo &DCI) {
12043   // BT ignores high bits in the bit index operand.
12044   SDValue Op1 = N->getOperand(1);
12045   if (Op1.hasOneUse()) {
12046     unsigned BitWidth = Op1.getValueSizeInBits();
12047     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12048     APInt KnownZero, KnownOne;
12049     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12050                                           !DCI.isBeforeLegalizeOps());
12051     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12052     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12053         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12054       DCI.CommitTargetLoweringOpt(TLO);
12055   }
12056   return SDValue();
12057 }
12058
12059 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12060   SDValue Op = N->getOperand(0);
12061   if (Op.getOpcode() == ISD::BITCAST)
12062     Op = Op.getOperand(0);
12063   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12064   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12065       VT.getVectorElementType().getSizeInBits() ==
12066       OpVT.getVectorElementType().getSizeInBits()) {
12067     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12068   }
12069   return SDValue();
12070 }
12071
12072 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12073   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12074   //           (and (i32 x86isd::setcc_carry), 1)
12075   // This eliminates the zext. This transformation is necessary because
12076   // ISD::SETCC is always legalized to i8.
12077   DebugLoc dl = N->getDebugLoc();
12078   SDValue N0 = N->getOperand(0);
12079   EVT VT = N->getValueType(0);
12080   if (N0.getOpcode() == ISD::AND &&
12081       N0.hasOneUse() &&
12082       N0.getOperand(0).hasOneUse()) {
12083     SDValue N00 = N0.getOperand(0);
12084     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12085       return SDValue();
12086     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12087     if (!C || C->getZExtValue() != 1)
12088       return SDValue();
12089     return DAG.getNode(ISD::AND, dl, VT,
12090                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12091                                    N00.getOperand(0), N00.getOperand(1)),
12092                        DAG.getConstant(1, VT));
12093   }
12094
12095   return SDValue();
12096 }
12097
12098 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12099 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12100   unsigned X86CC = N->getConstantOperandVal(0);
12101   SDValue EFLAG = N->getOperand(1);
12102   DebugLoc DL = N->getDebugLoc();
12103
12104   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12105   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12106   // cases.
12107   if (X86CC == X86::COND_B)
12108     return DAG.getNode(ISD::AND, DL, MVT::i8,
12109                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12110                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12111                        DAG.getConstant(1, MVT::i8));
12112
12113   return SDValue();
12114 }
12115
12116 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12117 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12118                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12119   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12120   // the result is either zero or one (depending on the input carry bit).
12121   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12122   if (X86::isZeroNode(N->getOperand(0)) &&
12123       X86::isZeroNode(N->getOperand(1)) &&
12124       // We don't have a good way to replace an EFLAGS use, so only do this when
12125       // dead right now.
12126       SDValue(N, 1).use_empty()) {
12127     DebugLoc DL = N->getDebugLoc();
12128     EVT VT = N->getValueType(0);
12129     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12130     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12131                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12132                                            DAG.getConstant(X86::COND_B,MVT::i8),
12133                                            N->getOperand(2)),
12134                                DAG.getConstant(1, VT));
12135     return DCI.CombineTo(N, Res1, CarryOut);
12136   }
12137
12138   return SDValue();
12139 }
12140
12141 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12142 //      (add Y, (setne X, 0)) -> sbb -1, Y
12143 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12144 //      (sub (setne X, 0), Y) -> adc -1, Y
12145 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12146   DebugLoc DL = N->getDebugLoc();
12147
12148   // Look through ZExts.
12149   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12150   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12151     return SDValue();
12152
12153   SDValue SetCC = Ext.getOperand(0);
12154   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12155     return SDValue();
12156
12157   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12158   if (CC != X86::COND_E && CC != X86::COND_NE)
12159     return SDValue();
12160
12161   SDValue Cmp = SetCC.getOperand(1);
12162   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12163       !X86::isZeroNode(Cmp.getOperand(1)) ||
12164       !Cmp.getOperand(0).getValueType().isInteger())
12165     return SDValue();
12166
12167   SDValue CmpOp0 = Cmp.getOperand(0);
12168   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12169                                DAG.getConstant(1, CmpOp0.getValueType()));
12170
12171   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12172   if (CC == X86::COND_NE)
12173     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12174                        DL, OtherVal.getValueType(), OtherVal,
12175                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12176   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12177                      DL, OtherVal.getValueType(), OtherVal,
12178                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12179 }
12180
12181 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12182                                              DAGCombinerInfo &DCI) const {
12183   SelectionDAG &DAG = DCI.DAG;
12184   switch (N->getOpcode()) {
12185   default: break;
12186   case ISD::EXTRACT_VECTOR_ELT:
12187     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12188   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12189   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12190   case ISD::ADD:
12191   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12192   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12193   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12194   case ISD::SHL:
12195   case ISD::SRA:
12196   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12197   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12198   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12199   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12200   case X86ISD::FXOR:
12201   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12202   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12203   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12204   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12205   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12206   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12207   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12208   case X86ISD::SHUFPD:
12209   case X86ISD::PALIGN:
12210   case X86ISD::PUNPCKHBW:
12211   case X86ISD::PUNPCKHWD:
12212   case X86ISD::PUNPCKHDQ:
12213   case X86ISD::PUNPCKHQDQ:
12214   case X86ISD::UNPCKHPS:
12215   case X86ISD::UNPCKHPD:
12216   case X86ISD::PUNPCKLBW:
12217   case X86ISD::PUNPCKLWD:
12218   case X86ISD::PUNPCKLDQ:
12219   case X86ISD::PUNPCKLQDQ:
12220   case X86ISD::UNPCKLPS:
12221   case X86ISD::UNPCKLPD:
12222   case X86ISD::VUNPCKLPS:
12223   case X86ISD::VUNPCKLPD:
12224   case X86ISD::VUNPCKLPSY:
12225   case X86ISD::VUNPCKLPDY:
12226   case X86ISD::MOVHLPS:
12227   case X86ISD::MOVLHPS:
12228   case X86ISD::PSHUFD:
12229   case X86ISD::PSHUFHW:
12230   case X86ISD::PSHUFLW:
12231   case X86ISD::MOVSS:
12232   case X86ISD::MOVSD:
12233   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12234   }
12235
12236   return SDValue();
12237 }
12238
12239 /// isTypeDesirableForOp - Return true if the target has native support for
12240 /// the specified value type and it is 'desirable' to use the type for the
12241 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12242 /// instruction encodings are longer and some i16 instructions are slow.
12243 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12244   if (!isTypeLegal(VT))
12245     return false;
12246   if (VT != MVT::i16)
12247     return true;
12248
12249   switch (Opc) {
12250   default:
12251     return true;
12252   case ISD::LOAD:
12253   case ISD::SIGN_EXTEND:
12254   case ISD::ZERO_EXTEND:
12255   case ISD::ANY_EXTEND:
12256   case ISD::SHL:
12257   case ISD::SRL:
12258   case ISD::SUB:
12259   case ISD::ADD:
12260   case ISD::MUL:
12261   case ISD::AND:
12262   case ISD::OR:
12263   case ISD::XOR:
12264     return false;
12265   }
12266 }
12267
12268 /// IsDesirableToPromoteOp - This method query the target whether it is
12269 /// beneficial for dag combiner to promote the specified node. If true, it
12270 /// should return the desired promotion type by reference.
12271 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12272   EVT VT = Op.getValueType();
12273   if (VT != MVT::i16)
12274     return false;
12275
12276   bool Promote = false;
12277   bool Commute = false;
12278   switch (Op.getOpcode()) {
12279   default: break;
12280   case ISD::LOAD: {
12281     LoadSDNode *LD = cast<LoadSDNode>(Op);
12282     // If the non-extending load has a single use and it's not live out, then it
12283     // might be folded.
12284     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12285                                                      Op.hasOneUse()*/) {
12286       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12287              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12288         // The only case where we'd want to promote LOAD (rather then it being
12289         // promoted as an operand is when it's only use is liveout.
12290         if (UI->getOpcode() != ISD::CopyToReg)
12291           return false;
12292       }
12293     }
12294     Promote = true;
12295     break;
12296   }
12297   case ISD::SIGN_EXTEND:
12298   case ISD::ZERO_EXTEND:
12299   case ISD::ANY_EXTEND:
12300     Promote = true;
12301     break;
12302   case ISD::SHL:
12303   case ISD::SRL: {
12304     SDValue N0 = Op.getOperand(0);
12305     // Look out for (store (shl (load), x)).
12306     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12307       return false;
12308     Promote = true;
12309     break;
12310   }
12311   case ISD::ADD:
12312   case ISD::MUL:
12313   case ISD::AND:
12314   case ISD::OR:
12315   case ISD::XOR:
12316     Commute = true;
12317     // fallthrough
12318   case ISD::SUB: {
12319     SDValue N0 = Op.getOperand(0);
12320     SDValue N1 = Op.getOperand(1);
12321     if (!Commute && MayFoldLoad(N1))
12322       return false;
12323     // Avoid disabling potential load folding opportunities.
12324     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12325       return false;
12326     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12327       return false;
12328     Promote = true;
12329   }
12330   }
12331
12332   PVT = MVT::i32;
12333   return Promote;
12334 }
12335
12336 //===----------------------------------------------------------------------===//
12337 //                           X86 Inline Assembly Support
12338 //===----------------------------------------------------------------------===//
12339
12340 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12341   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12342
12343   std::string AsmStr = IA->getAsmString();
12344
12345   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12346   SmallVector<StringRef, 4> AsmPieces;
12347   SplitString(AsmStr, AsmPieces, ";\n");
12348
12349   switch (AsmPieces.size()) {
12350   default: return false;
12351   case 1:
12352     AsmStr = AsmPieces[0];
12353     AsmPieces.clear();
12354     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12355
12356     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12357     // we will turn this bswap into something that will be lowered to logical ops
12358     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12359     // so don't worry about this.
12360     // bswap $0
12361     if (AsmPieces.size() == 2 &&
12362         (AsmPieces[0] == "bswap" ||
12363          AsmPieces[0] == "bswapq" ||
12364          AsmPieces[0] == "bswapl") &&
12365         (AsmPieces[1] == "$0" ||
12366          AsmPieces[1] == "${0:q}")) {
12367       // No need to check constraints, nothing other than the equivalent of
12368       // "=r,0" would be valid here.
12369       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12370       if (!Ty || Ty->getBitWidth() % 16 != 0)
12371         return false;
12372       return IntrinsicLowering::LowerToByteSwap(CI);
12373     }
12374     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12375     if (CI->getType()->isIntegerTy(16) &&
12376         AsmPieces.size() == 3 &&
12377         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12378         AsmPieces[1] == "$$8," &&
12379         AsmPieces[2] == "${0:w}" &&
12380         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12381       AsmPieces.clear();
12382       const std::string &ConstraintsStr = IA->getConstraintString();
12383       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12384       std::sort(AsmPieces.begin(), AsmPieces.end());
12385       if (AsmPieces.size() == 4 &&
12386           AsmPieces[0] == "~{cc}" &&
12387           AsmPieces[1] == "~{dirflag}" &&
12388           AsmPieces[2] == "~{flags}" &&
12389           AsmPieces[3] == "~{fpsr}") {
12390         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12391         if (!Ty || Ty->getBitWidth() % 16 != 0)
12392           return false;
12393         return IntrinsicLowering::LowerToByteSwap(CI);
12394       }
12395     }
12396     break;
12397   case 3:
12398     if (CI->getType()->isIntegerTy(32) &&
12399         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12400       SmallVector<StringRef, 4> Words;
12401       SplitString(AsmPieces[0], Words, " \t,");
12402       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12403           Words[2] == "${0:w}") {
12404         Words.clear();
12405         SplitString(AsmPieces[1], Words, " \t,");
12406         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12407             Words[2] == "$0") {
12408           Words.clear();
12409           SplitString(AsmPieces[2], Words, " \t,");
12410           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12411               Words[2] == "${0:w}") {
12412             AsmPieces.clear();
12413             const std::string &ConstraintsStr = IA->getConstraintString();
12414             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12415             std::sort(AsmPieces.begin(), AsmPieces.end());
12416             if (AsmPieces.size() == 4 &&
12417                 AsmPieces[0] == "~{cc}" &&
12418                 AsmPieces[1] == "~{dirflag}" &&
12419                 AsmPieces[2] == "~{flags}" &&
12420                 AsmPieces[3] == "~{fpsr}") {
12421               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12422               if (!Ty || Ty->getBitWidth() % 16 != 0)
12423                 return false;
12424               return IntrinsicLowering::LowerToByteSwap(CI);
12425             }
12426           }
12427         }
12428       }
12429     }
12430
12431     if (CI->getType()->isIntegerTy(64)) {
12432       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12433       if (Constraints.size() >= 2 &&
12434           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12435           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12436         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12437         SmallVector<StringRef, 4> Words;
12438         SplitString(AsmPieces[0], Words, " \t");
12439         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12440           Words.clear();
12441           SplitString(AsmPieces[1], Words, " \t");
12442           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12443             Words.clear();
12444             SplitString(AsmPieces[2], Words, " \t,");
12445             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12446                 Words[2] == "%edx") {
12447               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12448               if (!Ty || Ty->getBitWidth() % 16 != 0)
12449                 return false;
12450               return IntrinsicLowering::LowerToByteSwap(CI);
12451             }
12452           }
12453         }
12454       }
12455     }
12456     break;
12457   }
12458   return false;
12459 }
12460
12461
12462
12463 /// getConstraintType - Given a constraint letter, return the type of
12464 /// constraint it is for this target.
12465 X86TargetLowering::ConstraintType
12466 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12467   if (Constraint.size() == 1) {
12468     switch (Constraint[0]) {
12469     case 'R':
12470     case 'q':
12471     case 'Q':
12472     case 'f':
12473     case 't':
12474     case 'u':
12475     case 'y':
12476     case 'x':
12477     case 'Y':
12478       return C_RegisterClass;
12479     case 'a':
12480     case 'b':
12481     case 'c':
12482     case 'd':
12483     case 'S':
12484     case 'D':
12485     case 'A':
12486       return C_Register;
12487     case 'I':
12488     case 'J':
12489     case 'K':
12490     case 'L':
12491     case 'M':
12492     case 'N':
12493     case 'G':
12494     case 'C':
12495     case 'e':
12496     case 'Z':
12497       return C_Other;
12498     default:
12499       break;
12500     }
12501   }
12502   return TargetLowering::getConstraintType(Constraint);
12503 }
12504
12505 /// Examine constraint type and operand type and determine a weight value.
12506 /// This object must already have been set up with the operand type
12507 /// and the current alternative constraint selected.
12508 TargetLowering::ConstraintWeight
12509   X86TargetLowering::getSingleConstraintMatchWeight(
12510     AsmOperandInfo &info, const char *constraint) const {
12511   ConstraintWeight weight = CW_Invalid;
12512   Value *CallOperandVal = info.CallOperandVal;
12513     // If we don't have a value, we can't do a match,
12514     // but allow it at the lowest weight.
12515   if (CallOperandVal == NULL)
12516     return CW_Default;
12517   const Type *type = CallOperandVal->getType();
12518   // Look at the constraint type.
12519   switch (*constraint) {
12520   default:
12521     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12522   case 'R':
12523   case 'q':
12524   case 'Q':
12525   case 'a':
12526   case 'b':
12527   case 'c':
12528   case 'd':
12529   case 'S':
12530   case 'D':
12531   case 'A':
12532     if (CallOperandVal->getType()->isIntegerTy())
12533       weight = CW_SpecificReg;
12534     break;
12535   case 'f':
12536   case 't':
12537   case 'u':
12538       if (type->isFloatingPointTy())
12539         weight = CW_SpecificReg;
12540       break;
12541   case 'y':
12542       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12543         weight = CW_SpecificReg;
12544       break;
12545   case 'x':
12546   case 'Y':
12547     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12548       weight = CW_Register;
12549     break;
12550   case 'I':
12551     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12552       if (C->getZExtValue() <= 31)
12553         weight = CW_Constant;
12554     }
12555     break;
12556   case 'J':
12557     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12558       if (C->getZExtValue() <= 63)
12559         weight = CW_Constant;
12560     }
12561     break;
12562   case 'K':
12563     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12564       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12565         weight = CW_Constant;
12566     }
12567     break;
12568   case 'L':
12569     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12570       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12571         weight = CW_Constant;
12572     }
12573     break;
12574   case 'M':
12575     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12576       if (C->getZExtValue() <= 3)
12577         weight = CW_Constant;
12578     }
12579     break;
12580   case 'N':
12581     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12582       if (C->getZExtValue() <= 0xff)
12583         weight = CW_Constant;
12584     }
12585     break;
12586   case 'G':
12587   case 'C':
12588     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12589       weight = CW_Constant;
12590     }
12591     break;
12592   case 'e':
12593     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12594       if ((C->getSExtValue() >= -0x80000000LL) &&
12595           (C->getSExtValue() <= 0x7fffffffLL))
12596         weight = CW_Constant;
12597     }
12598     break;
12599   case 'Z':
12600     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12601       if (C->getZExtValue() <= 0xffffffff)
12602         weight = CW_Constant;
12603     }
12604     break;
12605   }
12606   return weight;
12607 }
12608
12609 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12610 /// with another that has more specific requirements based on the type of the
12611 /// corresponding operand.
12612 const char *X86TargetLowering::
12613 LowerXConstraint(EVT ConstraintVT) const {
12614   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12615   // 'f' like normal targets.
12616   if (ConstraintVT.isFloatingPoint()) {
12617     if (Subtarget->hasXMMInt())
12618       return "Y";
12619     if (Subtarget->hasXMM())
12620       return "x";
12621   }
12622
12623   return TargetLowering::LowerXConstraint(ConstraintVT);
12624 }
12625
12626 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12627 /// vector.  If it is invalid, don't add anything to Ops.
12628 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12629                                                      char Constraint,
12630                                                      std::vector<SDValue>&Ops,
12631                                                      SelectionDAG &DAG) const {
12632   SDValue Result(0, 0);
12633
12634   switch (Constraint) {
12635   default: break;
12636   case 'I':
12637     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12638       if (C->getZExtValue() <= 31) {
12639         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12640         break;
12641       }
12642     }
12643     return;
12644   case 'J':
12645     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12646       if (C->getZExtValue() <= 63) {
12647         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12648         break;
12649       }
12650     }
12651     return;
12652   case 'K':
12653     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12654       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12655         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12656         break;
12657       }
12658     }
12659     return;
12660   case 'N':
12661     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12662       if (C->getZExtValue() <= 255) {
12663         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12664         break;
12665       }
12666     }
12667     return;
12668   case 'e': {
12669     // 32-bit signed value
12670     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12671       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12672                                            C->getSExtValue())) {
12673         // Widen to 64 bits here to get it sign extended.
12674         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12675         break;
12676       }
12677     // FIXME gcc accepts some relocatable values here too, but only in certain
12678     // memory models; it's complicated.
12679     }
12680     return;
12681   }
12682   case 'Z': {
12683     // 32-bit unsigned value
12684     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12685       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12686                                            C->getZExtValue())) {
12687         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12688         break;
12689       }
12690     }
12691     // FIXME gcc accepts some relocatable values here too, but only in certain
12692     // memory models; it's complicated.
12693     return;
12694   }
12695   case 'i': {
12696     // Literal immediates are always ok.
12697     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12698       // Widen to 64 bits here to get it sign extended.
12699       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12700       break;
12701     }
12702
12703     // In any sort of PIC mode addresses need to be computed at runtime by
12704     // adding in a register or some sort of table lookup.  These can't
12705     // be used as immediates.
12706     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12707       return;
12708
12709     // If we are in non-pic codegen mode, we allow the address of a global (with
12710     // an optional displacement) to be used with 'i'.
12711     GlobalAddressSDNode *GA = 0;
12712     int64_t Offset = 0;
12713
12714     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12715     while (1) {
12716       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12717         Offset += GA->getOffset();
12718         break;
12719       } else if (Op.getOpcode() == ISD::ADD) {
12720         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12721           Offset += C->getZExtValue();
12722           Op = Op.getOperand(0);
12723           continue;
12724         }
12725       } else if (Op.getOpcode() == ISD::SUB) {
12726         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12727           Offset += -C->getZExtValue();
12728           Op = Op.getOperand(0);
12729           continue;
12730         }
12731       }
12732
12733       // Otherwise, this isn't something we can handle, reject it.
12734       return;
12735     }
12736
12737     const GlobalValue *GV = GA->getGlobal();
12738     // If we require an extra load to get this address, as in PIC mode, we
12739     // can't accept it.
12740     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12741                                                         getTargetMachine())))
12742       return;
12743
12744     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12745                                         GA->getValueType(0), Offset);
12746     break;
12747   }
12748   }
12749
12750   if (Result.getNode()) {
12751     Ops.push_back(Result);
12752     return;
12753   }
12754   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12755 }
12756
12757 std::vector<unsigned> X86TargetLowering::
12758 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12759                                   EVT VT) const {
12760   if (Constraint.size() == 1) {
12761     // FIXME: not handling fp-stack yet!
12762     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12763     default: break;  // Unknown constraint letter
12764     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12765       if (Subtarget->is64Bit()) {
12766         if (VT == MVT::i32)
12767           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12768                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12769                                        X86::R10D,X86::R11D,X86::R12D,
12770                                        X86::R13D,X86::R14D,X86::R15D,
12771                                        X86::EBP, X86::ESP, 0);
12772         else if (VT == MVT::i16)
12773           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12774                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12775                                        X86::R10W,X86::R11W,X86::R12W,
12776                                        X86::R13W,X86::R14W,X86::R15W,
12777                                        X86::BP,  X86::SP, 0);
12778         else if (VT == MVT::i8)
12779           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12780                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12781                                        X86::R10B,X86::R11B,X86::R12B,
12782                                        X86::R13B,X86::R14B,X86::R15B,
12783                                        X86::BPL, X86::SPL, 0);
12784
12785         else if (VT == MVT::i64)
12786           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12787                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12788                                        X86::R10, X86::R11, X86::R12,
12789                                        X86::R13, X86::R14, X86::R15,
12790                                        X86::RBP, X86::RSP, 0);
12791
12792         break;
12793       }
12794       // 32-bit fallthrough
12795     case 'Q':   // Q_REGS
12796       if (VT == MVT::i32)
12797         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12798       else if (VT == MVT::i16)
12799         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12800       else if (VT == MVT::i8)
12801         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12802       else if (VT == MVT::i64)
12803         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12804       break;
12805     }
12806   }
12807
12808   return std::vector<unsigned>();
12809 }
12810
12811 std::pair<unsigned, const TargetRegisterClass*>
12812 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12813                                                 EVT VT) const {
12814   // First, see if this is a constraint that directly corresponds to an LLVM
12815   // register class.
12816   if (Constraint.size() == 1) {
12817     // GCC Constraint Letters
12818     switch (Constraint[0]) {
12819     default: break;
12820     case 'r':   // GENERAL_REGS
12821     case 'l':   // INDEX_REGS
12822       if (VT == MVT::i8)
12823         return std::make_pair(0U, X86::GR8RegisterClass);
12824       if (VT == MVT::i16)
12825         return std::make_pair(0U, X86::GR16RegisterClass);
12826       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12827         return std::make_pair(0U, X86::GR32RegisterClass);
12828       return std::make_pair(0U, X86::GR64RegisterClass);
12829     case 'R':   // LEGACY_REGS
12830       if (VT == MVT::i8)
12831         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12832       if (VT == MVT::i16)
12833         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12834       if (VT == MVT::i32 || !Subtarget->is64Bit())
12835         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12836       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12837     case 'f':  // FP Stack registers.
12838       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12839       // value to the correct fpstack register class.
12840       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12841         return std::make_pair(0U, X86::RFP32RegisterClass);
12842       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12843         return std::make_pair(0U, X86::RFP64RegisterClass);
12844       return std::make_pair(0U, X86::RFP80RegisterClass);
12845     case 'y':   // MMX_REGS if MMX allowed.
12846       if (!Subtarget->hasMMX()) break;
12847       return std::make_pair(0U, X86::VR64RegisterClass);
12848     case 'Y':   // SSE_REGS if SSE2 allowed
12849       if (!Subtarget->hasXMMInt()) break;
12850       // FALL THROUGH.
12851     case 'x':   // SSE_REGS if SSE1 allowed
12852       if (!Subtarget->hasXMM()) break;
12853
12854       switch (VT.getSimpleVT().SimpleTy) {
12855       default: break;
12856       // Scalar SSE types.
12857       case MVT::f32:
12858       case MVT::i32:
12859         return std::make_pair(0U, X86::FR32RegisterClass);
12860       case MVT::f64:
12861       case MVT::i64:
12862         return std::make_pair(0U, X86::FR64RegisterClass);
12863       // Vector types.
12864       case MVT::v16i8:
12865       case MVT::v8i16:
12866       case MVT::v4i32:
12867       case MVT::v2i64:
12868       case MVT::v4f32:
12869       case MVT::v2f64:
12870         return std::make_pair(0U, X86::VR128RegisterClass);
12871       }
12872       break;
12873     }
12874   }
12875
12876   // Use the default implementation in TargetLowering to convert the register
12877   // constraint into a member of a register class.
12878   std::pair<unsigned, const TargetRegisterClass*> Res;
12879   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12880
12881   // Not found as a standard register?
12882   if (Res.second == 0) {
12883     // Map st(0) -> st(7) -> ST0
12884     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12885         tolower(Constraint[1]) == 's' &&
12886         tolower(Constraint[2]) == 't' &&
12887         Constraint[3] == '(' &&
12888         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12889         Constraint[5] == ')' &&
12890         Constraint[6] == '}') {
12891
12892       Res.first = X86::ST0+Constraint[4]-'0';
12893       Res.second = X86::RFP80RegisterClass;
12894       return Res;
12895     }
12896
12897     // GCC allows "st(0)" to be called just plain "st".
12898     if (StringRef("{st}").equals_lower(Constraint)) {
12899       Res.first = X86::ST0;
12900       Res.second = X86::RFP80RegisterClass;
12901       return Res;
12902     }
12903
12904     // flags -> EFLAGS
12905     if (StringRef("{flags}").equals_lower(Constraint)) {
12906       Res.first = X86::EFLAGS;
12907       Res.second = X86::CCRRegisterClass;
12908       return Res;
12909     }
12910
12911     // 'A' means EAX + EDX.
12912     if (Constraint == "A") {
12913       Res.first = X86::EAX;
12914       Res.second = X86::GR32_ADRegisterClass;
12915       return Res;
12916     }
12917     return Res;
12918   }
12919
12920   // Otherwise, check to see if this is a register class of the wrong value
12921   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12922   // turn into {ax},{dx}.
12923   if (Res.second->hasType(VT))
12924     return Res;   // Correct type already, nothing to do.
12925
12926   // All of the single-register GCC register classes map their values onto
12927   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12928   // really want an 8-bit or 32-bit register, map to the appropriate register
12929   // class and return the appropriate register.
12930   if (Res.second == X86::GR16RegisterClass) {
12931     if (VT == MVT::i8) {
12932       unsigned DestReg = 0;
12933       switch (Res.first) {
12934       default: break;
12935       case X86::AX: DestReg = X86::AL; break;
12936       case X86::DX: DestReg = X86::DL; break;
12937       case X86::CX: DestReg = X86::CL; break;
12938       case X86::BX: DestReg = X86::BL; break;
12939       }
12940       if (DestReg) {
12941         Res.first = DestReg;
12942         Res.second = X86::GR8RegisterClass;
12943       }
12944     } else if (VT == MVT::i32) {
12945       unsigned DestReg = 0;
12946       switch (Res.first) {
12947       default: break;
12948       case X86::AX: DestReg = X86::EAX; break;
12949       case X86::DX: DestReg = X86::EDX; break;
12950       case X86::CX: DestReg = X86::ECX; break;
12951       case X86::BX: DestReg = X86::EBX; break;
12952       case X86::SI: DestReg = X86::ESI; break;
12953       case X86::DI: DestReg = X86::EDI; break;
12954       case X86::BP: DestReg = X86::EBP; break;
12955       case X86::SP: DestReg = X86::ESP; break;
12956       }
12957       if (DestReg) {
12958         Res.first = DestReg;
12959         Res.second = X86::GR32RegisterClass;
12960       }
12961     } else if (VT == MVT::i64) {
12962       unsigned DestReg = 0;
12963       switch (Res.first) {
12964       default: break;
12965       case X86::AX: DestReg = X86::RAX; break;
12966       case X86::DX: DestReg = X86::RDX; break;
12967       case X86::CX: DestReg = X86::RCX; break;
12968       case X86::BX: DestReg = X86::RBX; break;
12969       case X86::SI: DestReg = X86::RSI; break;
12970       case X86::DI: DestReg = X86::RDI; break;
12971       case X86::BP: DestReg = X86::RBP; break;
12972       case X86::SP: DestReg = X86::RSP; break;
12973       }
12974       if (DestReg) {
12975         Res.first = DestReg;
12976         Res.second = X86::GR64RegisterClass;
12977       }
12978     }
12979   } else if (Res.second == X86::FR32RegisterClass ||
12980              Res.second == X86::FR64RegisterClass ||
12981              Res.second == X86::VR128RegisterClass) {
12982     // Handle references to XMM physical registers that got mapped into the
12983     // wrong class.  This can happen with constraints like {xmm0} where the
12984     // target independent register mapper will just pick the first match it can
12985     // find, ignoring the required type.
12986     if (VT == MVT::f32)
12987       Res.second = X86::FR32RegisterClass;
12988     else if (VT == MVT::f64)
12989       Res.second = X86::FR64RegisterClass;
12990     else if (X86::VR128RegisterClass->hasType(VT))
12991       Res.second = X86::VR128RegisterClass;
12992   }
12993
12994   return Res;
12995 }