Add support for 256-bit versions of VPERMIL instruction. This is a new
[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   EVT ElVT = VT.getVectorElementType();
89   int Factor = VT.getSizeInBits()/128;
90   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
91                                   VT.getVectorNumElements()/Factor);
92
93   // Extract from UNDEF is UNDEF.
94   if (Vec.getOpcode() == ISD::UNDEF)
95     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
96
97   if (isa<ConstantSDNode>(Idx)) {
98     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
99
100     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
101     // we can match to VEXTRACTF128.
102     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
103
104     // This is the index of the first element of the 128-bit chunk
105     // we want.
106     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107                                  * ElemsPerChunk);
108
109     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
110     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
111                                  VecIdx);
112
113     return Result;
114   }
115
116   return SDValue();
117 }
118
119 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
120 /// sets things up to match to an AVX VINSERTF128 instruction or a
121 /// simple superregister reference.  Idx is an index in the 128 bits
122 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
123 /// lowering INSERT_VECTOR_ELT operations easier.
124 static SDValue Insert128BitVector(SDValue Result,
125                                   SDValue Vec,
126                                   SDValue Idx,
127                                   SelectionDAG &DAG,
128                                   DebugLoc dl) {
129   if (isa<ConstantSDNode>(Idx)) {
130     EVT VT = Vec.getValueType();
131     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
132
133     EVT ElVT = VT.getVectorElementType();
134     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
135     EVT ResultVT = Result.getValueType();
136
137     // Insert the relevant 128 bits.
138     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
139
140     // This is the index of the first element of the 128-bit chunk
141     // we want.
142     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143                                  * ElemsPerChunk);
144
145     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
146     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
147                          VecIdx);
148     return Result;
149   }
150
151   return SDValue();
152 }
153
154 /// Given two vectors, concat them.
155 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
156   DebugLoc dl = Lower.getDebugLoc();
157
158   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
159
160   EVT VT = EVT::getVectorVT(*DAG.getContext(),
161                             Lower.getValueType().getVectorElementType(),
162                             Lower.getValueType().getVectorNumElements() * 2);
163
164   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
165   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
166
167   // Insert the upper subvector.
168   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
169                                    DAG.getConstant(
170                                      // This is half the length of the result
171                                      // vector.  Start inserting the upper 128
172                                      // bits here.
173                                      Lower.getValueType().getVectorNumElements(),
174                                      MVT::i32),
175                                    DAG, dl);
176
177   // Insert the lower subvector.
178   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
179   return Vec;
180 }
181
182 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
183   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
184   bool is64Bit = Subtarget->is64Bit();
185
186   if (Subtarget->isTargetEnvMacho()) {
187     if (is64Bit)
188       return new X8664_MachoTargetObjectFile();
189     return new TargetLoweringObjectFileMachO();
190   }
191
192   if (Subtarget->isTargetELF())
193     return new TargetLoweringObjectFileELF();
194   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasXMMInt();
203   X86ScalarSSEf32 = Subtarget->hasXMM();
204   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
205
206   RegInfo = TM.getRegisterInfo();
207   TD = getTargetData();
208
209   // Set up the TargetLowering object.
210   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
211
212   // X86 is weird, it always uses i8 for shift amounts and setcc results.
213   setBooleanContents(ZeroOrOneBooleanContent);
214
215   // For 64-bit since we have so many registers use the ILP scheduler, for
216   // 32-bit code use the register pressure specific scheduling.
217   if (Subtarget->is64Bit())
218     setSchedulingPreference(Sched::ILP);
219   else
220     setSchedulingPreference(Sched::RegPressure);
221   setStackPointerRegisterToSaveRestore(X86StackPtr);
222
223   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
224     // Setup Windows compiler runtime calls.
225     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
226     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
227     setLibcallName(RTLIB::SREM_I64, "_allrem");
228     setLibcallName(RTLIB::UREM_I64, "_aullrem");
229     setLibcallName(RTLIB::MUL_I64, "_allmul");
230     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
231     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
232     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
233     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
234     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
235     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
237     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
238     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
239   }
240
241   if (Subtarget->isTargetDarwin()) {
242     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
243     setUseUnderscoreSetJmp(false);
244     setUseUnderscoreLongJmp(false);
245   } else if (Subtarget->isTargetMingw()) {
246     // MS runtime is weird: it exports _setjmp, but longjmp!
247     setUseUnderscoreSetJmp(true);
248     setUseUnderscoreLongJmp(false);
249   } else {
250     setUseUnderscoreSetJmp(true);
251     setUseUnderscoreLongJmp(true);
252   }
253
254   // Set up the register classes.
255   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
256   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
257   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
258   if (Subtarget->is64Bit())
259     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
260
261   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
262
263   // We don't accept any truncstore of integer registers.
264   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
265   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
266   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
267   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
268   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
269   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
270
271   // SETOEQ and SETUNE require checking two conditions.
272   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
273   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
274   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
275   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
276   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
277   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
278
279   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
280   // operation.
281   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
282   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
283   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
284
285   if (Subtarget->is64Bit()) {
286     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
287     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
288   } else if (!UseSoftFloat) {
289     // We have an algorithm for SSE2->double, and we turn this into a
290     // 64-bit FILD followed by conditional FADD for other targets.
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
292     // We have an algorithm for SSE2, and we turn this into a 64-bit
293     // FILD for other targets.
294     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
295   }
296
297   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
298   // this operation.
299   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
300   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
301
302   if (!UseSoftFloat) {
303     // SSE has no i16 to fp conversion, only i32
304     if (X86ScalarSSEf32) {
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
306       // f32 and f64 cases are Legal, f80 case is not
307       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
308     } else {
309       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
311     }
312   } else {
313     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
314     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
315   }
316
317   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
318   // are Legal, f80 is custom lowered.
319   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
320   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
321
322   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
323   // this operation.
324   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
325   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
326
327   if (X86ScalarSSEf32) {
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
329     // f32 and f64 cases are Legal, f80 case is not
330     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
331   } else {
332     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
334   }
335
336   // Handle FP_TO_UINT by promoting the destination to a larger signed
337   // conversion.
338   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
339   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
340   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
341
342   if (Subtarget->is64Bit()) {
343     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
344     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
345   } else if (!UseSoftFloat) {
346     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
347       // Expand FP_TO_UINT into a select.
348       // FIXME: We would like to use a Custom expander here eventually to do
349       // the optimal thing for SSE vs. the default expansion in the legalizer.
350       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
351     else
352       // With SSE3 we can use fisttpll to convert to a signed i64; without
353       // SSE, we're stuck with a fistpll.
354       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
355   }
356
357   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
358   if (!X86ScalarSSEf64) {
359     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
360     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
361     if (Subtarget->is64Bit()) {
362       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
363       // Without SSE, i64->f64 goes through memory.
364       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
365     }
366   }
367
368   // Scalar integer divide and remainder are lowered to use operations that
369   // produce two results, to match the available instructions. This exposes
370   // the two-result form to trivial CSE, which is able to combine x/y and x%y
371   // into a single instruction.
372   //
373   // Scalar integer multiply-high is also lowered to use two-result
374   // operations, to match the available instructions. However, plain multiply
375   // (low) operations are left as Legal, as there are single-result
376   // instructions for this in x86. Using the two-result multiply instructions
377   // when both high and low results are needed must be arranged by dagcombine.
378   for (unsigned i = 0, e = 4; i != e; ++i) {
379     MVT VT = IntVTs[i];
380     setOperationAction(ISD::MULHS, VT, Expand);
381     setOperationAction(ISD::MULHU, VT, Expand);
382     setOperationAction(ISD::SDIV, VT, Expand);
383     setOperationAction(ISD::UDIV, VT, Expand);
384     setOperationAction(ISD::SREM, VT, Expand);
385     setOperationAction(ISD::UREM, VT, Expand);
386
387     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
388     setOperationAction(ISD::ADDC, VT, Custom);
389     setOperationAction(ISD::ADDE, VT, Custom);
390     setOperationAction(ISD::SUBC, VT, Custom);
391     setOperationAction(ISD::SUBE, VT, Custom);
392   }
393
394   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
395   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
396   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
397   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
398   if (Subtarget->is64Bit())
399     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
401   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
402   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
403   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
404   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
405   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
406   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
407   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
408
409   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
410   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
411   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
412   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
413   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
414   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
418   }
419
420   if (Subtarget->hasPOPCNT()) {
421     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
422   } else {
423     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
424     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
425     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
426     if (Subtarget->is64Bit())
427       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
428   }
429
430   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
431   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
432
433   // These should be promoted to a larger select which is supported.
434   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
435   // X86 wants to expand cmov itself.
436   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
437   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
439   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
443   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
448   if (Subtarget->is64Bit()) {
449     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
450     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
451   }
452   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
453
454   // Darwin ABI issue.
455   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
456   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
457   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
458   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
459   if (Subtarget->is64Bit())
460     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
461   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
462   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
463   if (Subtarget->is64Bit()) {
464     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
465     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
466     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
467     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
468     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
469   }
470   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
471   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
472   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
473   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
474   if (Subtarget->is64Bit()) {
475     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
476     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
477     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
478   }
479
480   if (Subtarget->hasXMM())
481     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
482
483   // We may not have a libcall for MEMBARRIER so we should lower this.
484   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
485
486   // On X86 and X86-64, atomic operations are lowered to locked instructions.
487   // Locked instructions, in turn, have implicit fence semantics (all memory
488   // operations are flushed before issuing the locked instruction, and they
489   // are not buffered), so we can fold away the common pattern of
490   // fence-atomic-fence.
491   setShouldFoldAtomicFences(true);
492
493   // Expand certain atomics
494   for (unsigned i = 0, e = 4; i != e; ++i) {
495     MVT VT = IntVTs[i];
496     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
497     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
498   }
499
500   if (!Subtarget->is64Bit()) {
501     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
508   }
509
510   // FIXME - use subtarget debug flags
511   if (!Subtarget->isTargetDarwin() &&
512       !Subtarget->isTargetELF() &&
513       !Subtarget->isTargetCygMing()) {
514     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
518   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
519   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
520   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
521   if (Subtarget->is64Bit()) {
522     setExceptionPointerRegister(X86::RAX);
523     setExceptionSelectorRegister(X86::RDX);
524   } else {
525     setExceptionPointerRegister(X86::EAX);
526     setExceptionSelectorRegister(X86::EDX);
527   }
528   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
529   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
530
531   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
532
533   setOperationAction(ISD::TRAP, MVT::Other, Legal);
534
535   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
536   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
537   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
538   if (Subtarget->is64Bit()) {
539     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
540     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
541   } else {
542     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
543     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
544   }
545
546   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
547   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
548   setOperationAction(ISD::DYNAMIC_STACKALLOC,
549                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
550                      (Subtarget->isTargetCOFF()
551                       && !Subtarget->isTargetEnvMacho()
552                       ? Custom : Expand));
553
554   if (!UseSoftFloat && X86ScalarSSEf64) {
555     // f32 and f64 use SSE.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
558     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
559
560     // Use ANDPD to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f64, Custom);
562     setOperationAction(ISD::FABS , MVT::f32, Custom);
563
564     // Use XORP to simulate FNEG.
565     setOperationAction(ISD::FNEG , MVT::f64, Custom);
566     setOperationAction(ISD::FNEG , MVT::f32, Custom);
567
568     // Use ANDPD and ORPD to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // Lower this to FGETSIGNx86 plus an AND.
573     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
574     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
575
576     // We don't support sin/cos/fmod
577     setOperationAction(ISD::FSIN , MVT::f64, Expand);
578     setOperationAction(ISD::FCOS , MVT::f64, Expand);
579     setOperationAction(ISD::FSIN , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS , MVT::f32, Expand);
581
582     // Expand FP immediates into loads from the stack, except for the special
583     // cases we handle.
584     addLegalFPImmediate(APFloat(+0.0)); // xorpd
585     addLegalFPImmediate(APFloat(+0.0f)); // xorps
586   } else if (!UseSoftFloat && X86ScalarSSEf32) {
587     // Use SSE for f32, x87 for f64.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
590     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
591
592     // Use ANDPS to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f32, Custom);
597
598     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
599
600     // Use ANDPS and ORPS to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // We don't support sin/cos/fmod
605     setOperationAction(ISD::FSIN , MVT::f32, Expand);
606     setOperationAction(ISD::FCOS , MVT::f32, Expand);
607
608     // Special cases we handle for FP constants.
609     addLegalFPImmediate(APFloat(+0.0f)); // xorps
610     addLegalFPImmediate(APFloat(+0.0)); // FLD0
611     addLegalFPImmediate(APFloat(+1.0)); // FLD1
612     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
613     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
614
615     if (!UnsafeFPMath) {
616       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
617       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
618     }
619   } else if (!UseSoftFloat) {
620     // f32 and f64 in x87.
621     // Set up the FP register classes.
622     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
623     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
624
625     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
626     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
627     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
629
630     if (!UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634     addLegalFPImmediate(APFloat(+0.0)); // FLD0
635     addLegalFPImmediate(APFloat(+1.0)); // FLD1
636     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
637     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
638     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
639     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
640     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
641     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
642   }
643
644   // We don't support FMA.
645   setOperationAction(ISD::FMA, MVT::f64, Expand);
646   setOperationAction(ISD::FMA, MVT::f32, Expand);
647
648   // Long double always uses X87.
649   if (!UseSoftFloat) {
650     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
651     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
652     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
653     {
654       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
655       addLegalFPImmediate(TmpFlt);  // FLD0
656       TmpFlt.changeSign();
657       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
658
659       bool ignored;
660       APFloat TmpFlt2(+1.0);
661       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
662                       &ignored);
663       addLegalFPImmediate(TmpFlt2);  // FLD1
664       TmpFlt2.changeSign();
665       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
666     }
667
668     if (!UnsafeFPMath) {
669       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
670       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
671     }
672
673     setOperationAction(ISD::FMA, MVT::f80, Expand);
674   }
675
676   // Always use a library call for pow.
677   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
679   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
680
681   setOperationAction(ISD::FLOG, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
683   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP, MVT::f80, Expand);
685   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
686
687   // First set operation action for all vector types to either promote
688   // (for widening) or expand (for scalarization). Then we will selectively
689   // turn on ones that can be effectively codegen'd.
690   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
691        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
692     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
707     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
710     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
742     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
746     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
747          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
748       setTruncStoreAction((MVT::SimpleValueType)VT,
749                           (MVT::SimpleValueType)InnerVT, Expand);
750     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
752     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!UseSoftFloat && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
765   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
767   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
768   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
769   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
770   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
771   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
772   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
773   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
774   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
775   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
776   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
777   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
778   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
779   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
783   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
784   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
785   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
786   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
788   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
792   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
793
794   if (!UseSoftFloat && Subtarget->hasXMM()) {
795     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
796
797     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
802     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
803     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
804     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
805     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
806     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
807     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
808     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
809   }
810
811   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
812     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
813
814     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
815     // registers cannot be used even for integer operations.
816     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
819     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
820
821     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
822     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
823     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
824     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
826     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
827     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
828     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
829     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
830     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
831     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
835     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
836     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
837
838     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
841     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
842
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
853     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
854
855     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
856     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
857       EVT VT = (MVT::SimpleValueType)i;
858       // Do not attempt to custom lower non-power-of-2 vectors
859       if (!isPowerOf2_32(VT.getVectorNumElements()))
860         continue;
861       // Do not attempt to custom lower non-128-bit vectors
862       if (!VT.is128BitVector())
863         continue;
864       setOperationAction(ISD::BUILD_VECTOR,
865                          VT.getSimpleVT().SimpleTy, Custom);
866       setOperationAction(ISD::VECTOR_SHUFFLE,
867                          VT.getSimpleVT().SimpleTy, Custom);
868       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
869                          VT.getSimpleVT().SimpleTy, Custom);
870     }
871
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
877     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
878
879     if (Subtarget->is64Bit()) {
880       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
881       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
882     }
883
884     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
885     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
886       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
887       EVT VT = SVT;
888
889       // Do not attempt to promote non-128-bit vectors
890       if (!VT.is128BitVector())
891         continue;
892
893       setOperationAction(ISD::AND,    SVT, Promote);
894       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
895       setOperationAction(ISD::OR,     SVT, Promote);
896       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
897       setOperationAction(ISD::XOR,    SVT, Promote);
898       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
899       setOperationAction(ISD::LOAD,   SVT, Promote);
900       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
901       setOperationAction(ISD::SELECT, SVT, Promote);
902       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
903     }
904
905     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
906
907     // Custom lower v2i64 and v2f64 selects.
908     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
909     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
910     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
911     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
912
913     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
914     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
915   }
916
917   if (Subtarget->hasSSE41()) {
918     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
923     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
924     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
925     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
926     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
927     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
928
929     // FIXME: Do we need to handle scalar-to-vector here?
930     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
931
932     // Can turn SHL into an integer multiply.
933     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
934     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
935
936     // i8 and i16 vectors are custom , because the source register and source
937     // source memory operand types are not the same width.  f32 vectors are
938     // custom since the immediate controlling the insert encodes additional
939     // information.
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
944
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
949
950     if (Subtarget->is64Bit()) {
951       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
952       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
953     }
954   }
955
956   if (Subtarget->hasSSE2()) {
957     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
958     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
959     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
960
961     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
962     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
963     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
964
965     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
966     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
967   }
968
969   if (Subtarget->hasSSE42())
970     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
971
972   if (!UseSoftFloat && Subtarget->hasAVX()) {
973     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
977     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
978
979     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower several nodes for 256-bit types.
998     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
999                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1000       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1001       EVT VT = SVT;
1002
1003       // Extract subvector is special because the value type
1004       // (result) is 128-bit but the source is 256-bit wide.
1005       if (VT.is128BitVector())
1006         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1007
1008       // Do not attempt to custom lower other non-256-bit vectors
1009       if (!VT.is256BitVector())
1010         continue;
1011
1012       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1013       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1014       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1015       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1016       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1017       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1018     }
1019
1020     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1021     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1022       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1023       EVT VT = SVT;
1024
1025       // Do not attempt to promote non-256-bit vectors
1026       if (!VT.is256BitVector())
1027         continue;
1028
1029       setOperationAction(ISD::AND,    SVT, Promote);
1030       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1031       setOperationAction(ISD::OR,     SVT, Promote);
1032       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1033       setOperationAction(ISD::XOR,    SVT, Promote);
1034       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1035       setOperationAction(ISD::LOAD,   SVT, Promote);
1036       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1037       setOperationAction(ISD::SELECT, SVT, Promote);
1038       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1039     }
1040   }
1041
1042   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1043   // of this type with custom code.
1044   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1045          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1046     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1047   }
1048
1049   // We want to custom lower some of our intrinsics.
1050   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1051
1052
1053   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1054   // handle type legalization for these operations here.
1055   //
1056   // FIXME: We really should do custom legalization for addition and
1057   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1058   // than generic legalization for 64-bit multiplication-with-overflow, though.
1059   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1060     // Add/Sub/Mul with overflow operations are custom lowered.
1061     MVT VT = IntVTs[i];
1062     setOperationAction(ISD::SADDO, VT, Custom);
1063     setOperationAction(ISD::UADDO, VT, Custom);
1064     setOperationAction(ISD::SSUBO, VT, Custom);
1065     setOperationAction(ISD::USUBO, VT, Custom);
1066     setOperationAction(ISD::SMULO, VT, Custom);
1067     setOperationAction(ISD::UMULO, VT, Custom);
1068   }
1069
1070   // There are no 8-bit 3-address imul/mul instructions
1071   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1072   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1073
1074   if (!Subtarget->is64Bit()) {
1075     // These libcalls are not available in 32-bit.
1076     setLibcallName(RTLIB::SHL_I128, 0);
1077     setLibcallName(RTLIB::SRL_I128, 0);
1078     setLibcallName(RTLIB::SRA_I128, 0);
1079   }
1080
1081   // We have target-specific dag combine patterns for the following nodes:
1082   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1083   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1084   setTargetDAGCombine(ISD::BUILD_VECTOR);
1085   setTargetDAGCombine(ISD::SELECT);
1086   setTargetDAGCombine(ISD::SHL);
1087   setTargetDAGCombine(ISD::SRA);
1088   setTargetDAGCombine(ISD::SRL);
1089   setTargetDAGCombine(ISD::OR);
1090   setTargetDAGCombine(ISD::AND);
1091   setTargetDAGCombine(ISD::ADD);
1092   setTargetDAGCombine(ISD::SUB);
1093   setTargetDAGCombine(ISD::STORE);
1094   setTargetDAGCombine(ISD::ZERO_EXTEND);
1095   setTargetDAGCombine(ISD::SINT_TO_FP);
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(Type *Ty, unsigned &MaxAlign) {
1124   if (MaxAlign == 16)
1125     return;
1126   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127     if (VTy->getBitWidth() == 128)
1128       MaxAlign = 16;
1129   } else if (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 (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(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,
1319                                   MachineFunction &MF, bool isVarArg,
1320                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1321                         LLVMContext &Context) const {
1322   SmallVector<CCValAssign, 16> RVLocs;
1323   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1324                  RVLocs, Context);
1325   return CCInfo.CheckReturn(Outs, RetCC_X86);
1326 }
1327
1328 SDValue
1329 X86TargetLowering::LowerReturn(SDValue Chain,
1330                                CallingConv::ID CallConv, bool isVarArg,
1331                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1332                                const SmallVectorImpl<SDValue> &OutVals,
1333                                DebugLoc dl, SelectionDAG &DAG) const {
1334   MachineFunction &MF = DAG.getMachineFunction();
1335   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1336
1337   SmallVector<CCValAssign, 16> RVLocs;
1338   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1339                  RVLocs, *DAG.getContext());
1340   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1341
1342   // Add the regs to the liveout set for the function.
1343   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1344   for (unsigned i = 0; i != RVLocs.size(); ++i)
1345     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1346       MRI.addLiveOut(RVLocs[i].getLocReg());
1347
1348   SDValue Flag;
1349
1350   SmallVector<SDValue, 6> RetOps;
1351   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1352   // Operand #1 = Bytes To Pop
1353   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1354                    MVT::i16));
1355
1356   // Copy the result values into the output registers.
1357   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1358     CCValAssign &VA = RVLocs[i];
1359     assert(VA.isRegLoc() && "Can only return in registers!");
1360     SDValue ValToCopy = OutVals[i];
1361     EVT ValVT = ValToCopy.getValueType();
1362
1363     // If this is x86-64, and we disabled SSE, we can't return FP values,
1364     // or SSE or MMX vectors.
1365     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1366          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1367           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1368       report_fatal_error("SSE register return with SSE disabled");
1369     }
1370     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1371     // llvm-gcc has never done it right and no one has noticed, so this
1372     // should be OK for now.
1373     if (ValVT == MVT::f64 &&
1374         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1375       report_fatal_error("SSE2 register return with SSE2 disabled");
1376
1377     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1378     // the RET instruction and handled by the FP Stackifier.
1379     if (VA.getLocReg() == X86::ST0 ||
1380         VA.getLocReg() == X86::ST1) {
1381       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1382       // change the value to the FP stack register class.
1383       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1384         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1385       RetOps.push_back(ValToCopy);
1386       // Don't emit a copytoreg.
1387       continue;
1388     }
1389
1390     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1391     // which is returned in RAX / RDX.
1392     if (Subtarget->is64Bit()) {
1393       if (ValVT == MVT::x86mmx) {
1394         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1395           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1396           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1397                                   ValToCopy);
1398           // If we don't have SSE2 available, convert to v4f32 so the generated
1399           // register is legal.
1400           if (!Subtarget->hasSSE2())
1401             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1402         }
1403       }
1404     }
1405
1406     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1407     Flag = Chain.getValue(1);
1408   }
1409
1410   // The x86-64 ABI for returning structs by value requires that we copy
1411   // the sret argument into %rax for the return. We saved the argument into
1412   // a virtual register in the entry block, so now we copy the value out
1413   // and into %rax.
1414   if (Subtarget->is64Bit() &&
1415       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1416     MachineFunction &MF = DAG.getMachineFunction();
1417     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1418     unsigned Reg = FuncInfo->getSRetReturnReg();
1419     assert(Reg &&
1420            "SRetReturnReg should have been set in LowerFormalArguments().");
1421     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1422
1423     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1424     Flag = Chain.getValue(1);
1425
1426     // RAX now acts like a return value.
1427     MRI.addLiveOut(X86::RAX);
1428   }
1429
1430   RetOps[0] = Chain;  // Update chain.
1431
1432   // Add the flag if we have it.
1433   if (Flag.getNode())
1434     RetOps.push_back(Flag);
1435
1436   return DAG.getNode(X86ISD::RET_FLAG, dl,
1437                      MVT::Other, &RetOps[0], RetOps.size());
1438 }
1439
1440 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1441   if (N->getNumValues() != 1)
1442     return false;
1443   if (!N->hasNUsesOfValue(1, 0))
1444     return false;
1445
1446   SDNode *Copy = *N->use_begin();
1447   if (Copy->getOpcode() != ISD::CopyToReg &&
1448       Copy->getOpcode() != ISD::FP_EXTEND)
1449     return false;
1450
1451   bool HasRet = false;
1452   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1453        UI != UE; ++UI) {
1454     if (UI->getOpcode() != X86ISD::RET_FLAG)
1455       return false;
1456     HasRet = true;
1457   }
1458
1459   return HasRet;
1460 }
1461
1462 EVT
1463 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1464                                             ISD::NodeType ExtendKind) const {
1465   MVT ReturnMVT;
1466   // TODO: Is this also valid on 32-bit?
1467   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1468     ReturnMVT = MVT::i8;
1469   else
1470     ReturnMVT = MVT::i32;
1471
1472   EVT MinVT = getRegisterType(Context, ReturnMVT);
1473   return VT.bitsLT(MinVT) ? MinVT : VT;
1474 }
1475
1476 /// LowerCallResult - Lower the result values of a call into the
1477 /// appropriate copies out of appropriate physical registers.
1478 ///
1479 SDValue
1480 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1481                                    CallingConv::ID CallConv, bool isVarArg,
1482                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1483                                    DebugLoc dl, SelectionDAG &DAG,
1484                                    SmallVectorImpl<SDValue> &InVals) const {
1485
1486   // Assign locations to each value returned by this call.
1487   SmallVector<CCValAssign, 16> RVLocs;
1488   bool Is64Bit = Subtarget->is64Bit();
1489   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1490                  getTargetMachine(), RVLocs, *DAG.getContext());
1491   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1492
1493   // Copy all of the result registers out of their specified physreg.
1494   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1495     CCValAssign &VA = RVLocs[i];
1496     EVT CopyVT = VA.getValVT();
1497
1498     // If this is x86-64, and we disabled SSE, we can't return FP values
1499     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1500         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1501       report_fatal_error("SSE register return with SSE disabled");
1502     }
1503
1504     SDValue Val;
1505
1506     // If this is a call to a function that returns an fp value on the floating
1507     // point stack, we must guarantee the the value is popped from the stack, so
1508     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1509     // if the return value is not used. We use the FpPOP_RETVAL instruction
1510     // instead.
1511     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1512       // If we prefer to use the value in xmm registers, copy it out as f80 and
1513       // use a truncate to move it from fp stack reg to xmm reg.
1514       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1515       SDValue Ops[] = { Chain, InFlag };
1516       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1517                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1518       Val = Chain.getValue(0);
1519
1520       // Round the f80 to the right size, which also moves it to the appropriate
1521       // xmm register.
1522       if (CopyVT != VA.getValVT())
1523         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1524                           // This truncation won't change the value.
1525                           DAG.getIntPtrConstant(1));
1526     } else {
1527       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1528                                  CopyVT, InFlag).getValue(1);
1529       Val = Chain.getValue(0);
1530     }
1531     InFlag = Chain.getValue(2);
1532     InVals.push_back(Val);
1533   }
1534
1535   return Chain;
1536 }
1537
1538
1539 //===----------------------------------------------------------------------===//
1540 //                C & StdCall & Fast Calling Convention implementation
1541 //===----------------------------------------------------------------------===//
1542 //  StdCall calling convention seems to be standard for many Windows' API
1543 //  routines and around. It differs from C calling convention just a little:
1544 //  callee should clean up the stack, not caller. Symbols should be also
1545 //  decorated in some fancy way :) It doesn't support any vector arguments.
1546 //  For info on fast calling convention see Fast Calling Convention (tail call)
1547 //  implementation LowerX86_32FastCCCallTo.
1548
1549 /// CallIsStructReturn - Determines whether a call uses struct return
1550 /// semantics.
1551 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1552   if (Outs.empty())
1553     return false;
1554
1555   return Outs[0].Flags.isSRet();
1556 }
1557
1558 /// ArgsAreStructReturn - Determines whether a function uses struct
1559 /// return semantics.
1560 static bool
1561 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1562   if (Ins.empty())
1563     return false;
1564
1565   return Ins[0].Flags.isSRet();
1566 }
1567
1568 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1569 /// by "Src" to address "Dst" with size and alignment information specified by
1570 /// the specific parameter attribute. The copy will be passed as a byval
1571 /// function parameter.
1572 static SDValue
1573 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1574                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1575                           DebugLoc dl) {
1576   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1577
1578   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1579                        /*isVolatile*/false, /*AlwaysInline=*/true,
1580                        MachinePointerInfo(), MachinePointerInfo());
1581 }
1582
1583 /// IsTailCallConvention - Return true if the calling convention is one that
1584 /// supports tail call optimization.
1585 static bool IsTailCallConvention(CallingConv::ID CC) {
1586   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1587 }
1588
1589 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1590   if (!CI->isTailCall())
1591     return false;
1592
1593   CallSite CS(CI);
1594   CallingConv::ID CalleeCC = CS.getCallingConv();
1595   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1596     return false;
1597
1598   return true;
1599 }
1600
1601 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1602 /// a tailcall target by changing its ABI.
1603 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1604   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1605 }
1606
1607 SDValue
1608 X86TargetLowering::LowerMemArgument(SDValue Chain,
1609                                     CallingConv::ID CallConv,
1610                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1611                                     DebugLoc dl, SelectionDAG &DAG,
1612                                     const CCValAssign &VA,
1613                                     MachineFrameInfo *MFI,
1614                                     unsigned i) const {
1615   // Create the nodes corresponding to a load from this parameter slot.
1616   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1617   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1618   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1619   EVT ValVT;
1620
1621   // If value is passed by pointer we have address passed instead of the value
1622   // itself.
1623   if (VA.getLocInfo() == CCValAssign::Indirect)
1624     ValVT = VA.getLocVT();
1625   else
1626     ValVT = VA.getValVT();
1627
1628   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1629   // changed with more analysis.
1630   // In case of tail call optimization mark all arguments mutable. Since they
1631   // could be overwritten by lowering of arguments in case of a tail call.
1632   if (Flags.isByVal()) {
1633     unsigned Bytes = Flags.getByValSize();
1634     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1635     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1636     return DAG.getFrameIndex(FI, getPointerTy());
1637   } else {
1638     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1639                                     VA.getLocMemOffset(), isImmutable);
1640     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1641     return DAG.getLoad(ValVT, dl, Chain, FIN,
1642                        MachinePointerInfo::getFixedStack(FI),
1643                        false, false, 0);
1644   }
1645 }
1646
1647 SDValue
1648 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1649                                         CallingConv::ID CallConv,
1650                                         bool isVarArg,
1651                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1652                                         DebugLoc dl,
1653                                         SelectionDAG &DAG,
1654                                         SmallVectorImpl<SDValue> &InVals)
1655                                           const {
1656   MachineFunction &MF = DAG.getMachineFunction();
1657   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1658
1659   const Function* Fn = MF.getFunction();
1660   if (Fn->hasExternalLinkage() &&
1661       Subtarget->isTargetCygMing() &&
1662       Fn->getName() == "main")
1663     FuncInfo->setForceFramePointer(true);
1664
1665   MachineFrameInfo *MFI = MF.getFrameInfo();
1666   bool Is64Bit = Subtarget->is64Bit();
1667   bool IsWin64 = Subtarget->isTargetWin64();
1668
1669   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1670          "Var args not supported with calling convention fastcc or ghc");
1671
1672   // Assign locations to all of the incoming arguments.
1673   SmallVector<CCValAssign, 16> ArgLocs;
1674   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1675                  ArgLocs, *DAG.getContext());
1676
1677   // Allocate shadow area for Win64
1678   if (IsWin64) {
1679     CCInfo.AllocateStack(32, 8);
1680   }
1681
1682   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1683
1684   unsigned LastVal = ~0U;
1685   SDValue ArgValue;
1686   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1687     CCValAssign &VA = ArgLocs[i];
1688     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1689     // places.
1690     assert(VA.getValNo() != LastVal &&
1691            "Don't support value assigned to multiple locs yet");
1692     LastVal = VA.getValNo();
1693
1694     if (VA.isRegLoc()) {
1695       EVT RegVT = VA.getLocVT();
1696       TargetRegisterClass *RC = NULL;
1697       if (RegVT == MVT::i32)
1698         RC = X86::GR32RegisterClass;
1699       else if (Is64Bit && RegVT == MVT::i64)
1700         RC = X86::GR64RegisterClass;
1701       else if (RegVT == MVT::f32)
1702         RC = X86::FR32RegisterClass;
1703       else if (RegVT == MVT::f64)
1704         RC = X86::FR64RegisterClass;
1705       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1706         RC = X86::VR256RegisterClass;
1707       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1708         RC = X86::VR128RegisterClass;
1709       else if (RegVT == MVT::x86mmx)
1710         RC = X86::VR64RegisterClass;
1711       else
1712         llvm_unreachable("Unknown argument type!");
1713
1714       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1715       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1716
1717       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1718       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1719       // right size.
1720       if (VA.getLocInfo() == CCValAssign::SExt)
1721         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1722                                DAG.getValueType(VA.getValVT()));
1723       else if (VA.getLocInfo() == CCValAssign::ZExt)
1724         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1725                                DAG.getValueType(VA.getValVT()));
1726       else if (VA.getLocInfo() == CCValAssign::BCvt)
1727         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1728
1729       if (VA.isExtInLoc()) {
1730         // Handle MMX values passed in XMM regs.
1731         if (RegVT.isVector()) {
1732           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1733                                  ArgValue);
1734         } else
1735           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1736       }
1737     } else {
1738       assert(VA.isMemLoc());
1739       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1740     }
1741
1742     // If value is passed via pointer - do a load.
1743     if (VA.getLocInfo() == CCValAssign::Indirect)
1744       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1745                              MachinePointerInfo(), false, false, 0);
1746
1747     InVals.push_back(ArgValue);
1748   }
1749
1750   // The x86-64 ABI for returning structs by value requires that we copy
1751   // the sret argument into %rax for the return. Save the argument into
1752   // a virtual register so that we can access it from the return points.
1753   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1754     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1755     unsigned Reg = FuncInfo->getSRetReturnReg();
1756     if (!Reg) {
1757       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1758       FuncInfo->setSRetReturnReg(Reg);
1759     }
1760     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1761     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1762   }
1763
1764   unsigned StackSize = CCInfo.getNextStackOffset();
1765   // Align stack specially for tail calls.
1766   if (FuncIsMadeTailCallSafe(CallConv))
1767     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1768
1769   // If the function takes variable number of arguments, make a frame index for
1770   // the start of the first vararg value... for expansion of llvm.va_start.
1771   if (isVarArg) {
1772     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1773                     CallConv != CallingConv::X86_ThisCall)) {
1774       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1775     }
1776     if (Is64Bit) {
1777       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1778
1779       // FIXME: We should really autogenerate these arrays
1780       static const unsigned GPR64ArgRegsWin64[] = {
1781         X86::RCX, X86::RDX, X86::R8,  X86::R9
1782       };
1783       static const unsigned GPR64ArgRegs64Bit[] = {
1784         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1785       };
1786       static const unsigned XMMArgRegs64Bit[] = {
1787         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1788         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1789       };
1790       const unsigned *GPR64ArgRegs;
1791       unsigned NumXMMRegs = 0;
1792
1793       if (IsWin64) {
1794         // The XMM registers which might contain var arg parameters are shadowed
1795         // in their paired GPR.  So we only need to save the GPR to their home
1796         // slots.
1797         TotalNumIntRegs = 4;
1798         GPR64ArgRegs = GPR64ArgRegsWin64;
1799       } else {
1800         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1801         GPR64ArgRegs = GPR64ArgRegs64Bit;
1802
1803         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1804       }
1805       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1806                                                        TotalNumIntRegs);
1807
1808       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1809       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1810              "SSE register cannot be used when SSE is disabled!");
1811       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1812              "SSE register cannot be used when SSE is disabled!");
1813       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1814         // Kernel mode asks for SSE to be disabled, so don't push them
1815         // on the stack.
1816         TotalNumXMMRegs = 0;
1817
1818       if (IsWin64) {
1819         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1820         // Get to the caller-allocated home save location.  Add 8 to account
1821         // for the return address.
1822         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1823         FuncInfo->setRegSaveFrameIndex(
1824           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1825         // Fixup to set vararg frame on shadow area (4 x i64).
1826         if (NumIntRegs < 4)
1827           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1828       } else {
1829         // For X86-64, if there are vararg parameters that are passed via
1830         // registers, then we must store them to their spots on the stack so they
1831         // may be loaded by deferencing the result of va_next.
1832         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1833         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1834         FuncInfo->setRegSaveFrameIndex(
1835           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1836                                false));
1837       }
1838
1839       // Store the integer parameter registers.
1840       SmallVector<SDValue, 8> MemOps;
1841       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1842                                         getPointerTy());
1843       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1844       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1845         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1846                                   DAG.getIntPtrConstant(Offset));
1847         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1848                                      X86::GR64RegisterClass);
1849         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1850         SDValue Store =
1851           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1852                        MachinePointerInfo::getFixedStack(
1853                          FuncInfo->getRegSaveFrameIndex(), Offset),
1854                        false, false, 0);
1855         MemOps.push_back(Store);
1856         Offset += 8;
1857       }
1858
1859       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1860         // Now store the XMM (fp + vector) parameter registers.
1861         SmallVector<SDValue, 11> SaveXMMOps;
1862         SaveXMMOps.push_back(Chain);
1863
1864         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1865         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1866         SaveXMMOps.push_back(ALVal);
1867
1868         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1869                                FuncInfo->getRegSaveFrameIndex()));
1870         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1871                                FuncInfo->getVarArgsFPOffset()));
1872
1873         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1874           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1875                                        X86::VR128RegisterClass);
1876           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1877           SaveXMMOps.push_back(Val);
1878         }
1879         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1880                                      MVT::Other,
1881                                      &SaveXMMOps[0], SaveXMMOps.size()));
1882       }
1883
1884       if (!MemOps.empty())
1885         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1886                             &MemOps[0], MemOps.size());
1887     }
1888   }
1889
1890   // Some CCs need callee pop.
1891   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1892     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1893   } else {
1894     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1895     // If this is an sret function, the return should pop the hidden pointer.
1896     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1897       FuncInfo->setBytesToPopOnReturn(4);
1898   }
1899
1900   if (!Is64Bit) {
1901     // RegSaveFrameIndex is X86-64 only.
1902     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1903     if (CallConv == CallingConv::X86_FastCall ||
1904         CallConv == CallingConv::X86_ThisCall)
1905       // fastcc functions can't have varargs.
1906       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1907   }
1908
1909   return Chain;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1914                                     SDValue StackPtr, SDValue Arg,
1915                                     DebugLoc dl, SelectionDAG &DAG,
1916                                     const CCValAssign &VA,
1917                                     ISD::ArgFlagsTy Flags) const {
1918   unsigned LocMemOffset = VA.getLocMemOffset();
1919   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1920   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1921   if (Flags.isByVal())
1922     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1923
1924   return DAG.getStore(Chain, dl, Arg, PtrOff,
1925                       MachinePointerInfo::getStack(LocMemOffset),
1926                       false, false, 0);
1927 }
1928
1929 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1930 /// optimization is performed and it is required.
1931 SDValue
1932 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1933                                            SDValue &OutRetAddr, SDValue Chain,
1934                                            bool IsTailCall, bool Is64Bit,
1935                                            int FPDiff, DebugLoc dl) const {
1936   // Adjust the Return address stack slot.
1937   EVT VT = getPointerTy();
1938   OutRetAddr = getReturnAddressFrameIndex(DAG);
1939
1940   // Load the "old" Return address.
1941   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1942                            false, false, 0);
1943   return SDValue(OutRetAddr.getNode(), 1);
1944 }
1945
1946 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1947 /// optimization is performed and it is required (FPDiff!=0).
1948 static SDValue
1949 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1950                          SDValue Chain, SDValue RetAddrFrIdx,
1951                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1952   // Store the return address to the appropriate stack slot.
1953   if (!FPDiff) return Chain;
1954   // Calculate the new stack slot for the return address.
1955   int SlotSize = Is64Bit ? 8 : 4;
1956   int NewReturnAddrFI =
1957     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1958   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1959   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1960   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1961                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1962                        false, false, 0);
1963   return Chain;
1964 }
1965
1966 SDValue
1967 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1968                              CallingConv::ID CallConv, bool isVarArg,
1969                              bool &isTailCall,
1970                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1971                              const SmallVectorImpl<SDValue> &OutVals,
1972                              const SmallVectorImpl<ISD::InputArg> &Ins,
1973                              DebugLoc dl, SelectionDAG &DAG,
1974                              SmallVectorImpl<SDValue> &InVals) const {
1975   MachineFunction &MF = DAG.getMachineFunction();
1976   bool Is64Bit        = Subtarget->is64Bit();
1977   bool IsWin64        = Subtarget->isTargetWin64();
1978   bool IsStructRet    = CallIsStructReturn(Outs);
1979   bool IsSibcall      = false;
1980
1981   if (isTailCall) {
1982     // Check if it's really possible to do a tail call.
1983     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1984                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1985                                                    Outs, OutVals, Ins, DAG);
1986
1987     // Sibcalls are automatically detected tailcalls which do not require
1988     // ABI changes.
1989     if (!GuaranteedTailCallOpt && isTailCall)
1990       IsSibcall = true;
1991
1992     if (isTailCall)
1993       ++NumTailCalls;
1994   }
1995
1996   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1997          "Var args not supported with calling convention fastcc or ghc");
1998
1999   // Analyze operands of the call, assigning locations to each operand.
2000   SmallVector<CCValAssign, 16> ArgLocs;
2001   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2002                  ArgLocs, *DAG.getContext());
2003
2004   // Allocate shadow area for Win64
2005   if (IsWin64) {
2006     CCInfo.AllocateStack(32, 8);
2007   }
2008
2009   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2010
2011   // Get a count of how many bytes are to be pushed on the stack.
2012   unsigned NumBytes = CCInfo.getNextStackOffset();
2013   if (IsSibcall)
2014     // This is a sibcall. The memory operands are available in caller's
2015     // own caller's stack.
2016     NumBytes = 0;
2017   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2018     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2019
2020   int FPDiff = 0;
2021   if (isTailCall && !IsSibcall) {
2022     // Lower arguments at fp - stackoffset + fpdiff.
2023     unsigned NumBytesCallerPushed =
2024       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2025     FPDiff = NumBytesCallerPushed - NumBytes;
2026
2027     // Set the delta of movement of the returnaddr stackslot.
2028     // But only set if delta is greater than previous delta.
2029     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2030       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2031   }
2032
2033   if (!IsSibcall)
2034     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2035
2036   SDValue RetAddrFrIdx;
2037   // Load return address for tail calls.
2038   if (isTailCall && FPDiff)
2039     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2040                                     Is64Bit, FPDiff, dl);
2041
2042   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2043   SmallVector<SDValue, 8> MemOpChains;
2044   SDValue StackPtr;
2045
2046   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2047   // of tail call optimization arguments are handle later.
2048   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2049     CCValAssign &VA = ArgLocs[i];
2050     EVT RegVT = VA.getLocVT();
2051     SDValue Arg = OutVals[i];
2052     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2053     bool isByVal = Flags.isByVal();
2054
2055     // Promote the value if needed.
2056     switch (VA.getLocInfo()) {
2057     default: llvm_unreachable("Unknown loc info!");
2058     case CCValAssign::Full: break;
2059     case CCValAssign::SExt:
2060       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2061       break;
2062     case CCValAssign::ZExt:
2063       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2064       break;
2065     case CCValAssign::AExt:
2066       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2067         // Special case: passing MMX values in XMM registers.
2068         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2069         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2070         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2071       } else
2072         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2073       break;
2074     case CCValAssign::BCvt:
2075       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2076       break;
2077     case CCValAssign::Indirect: {
2078       // Store the argument.
2079       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2080       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2081       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2082                            MachinePointerInfo::getFixedStack(FI),
2083                            false, false, 0);
2084       Arg = SpillSlot;
2085       break;
2086     }
2087     }
2088
2089     if (VA.isRegLoc()) {
2090       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2091       if (isVarArg && IsWin64) {
2092         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2093         // shadow reg if callee is a varargs function.
2094         unsigned ShadowReg = 0;
2095         switch (VA.getLocReg()) {
2096         case X86::XMM0: ShadowReg = X86::RCX; break;
2097         case X86::XMM1: ShadowReg = X86::RDX; break;
2098         case X86::XMM2: ShadowReg = X86::R8; break;
2099         case X86::XMM3: ShadowReg = X86::R9; break;
2100         }
2101         if (ShadowReg)
2102           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2103       }
2104     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2105       assert(VA.isMemLoc());
2106       if (StackPtr.getNode() == 0)
2107         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2108       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2109                                              dl, DAG, VA, Flags));
2110     }
2111   }
2112
2113   if (!MemOpChains.empty())
2114     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115                         &MemOpChains[0], MemOpChains.size());
2116
2117   // Build a sequence of copy-to-reg nodes chained together with token chain
2118   // and flag operands which copy the outgoing args into registers.
2119   SDValue InFlag;
2120   // Tail call byval lowering might overwrite argument registers so in case of
2121   // tail call optimization the copies to registers are lowered later.
2122   if (!isTailCall)
2123     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2124       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2125                                RegsToPass[i].second, InFlag);
2126       InFlag = Chain.getValue(1);
2127     }
2128
2129   if (Subtarget->isPICStyleGOT()) {
2130     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2131     // GOT pointer.
2132     if (!isTailCall) {
2133       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2134                                DAG.getNode(X86ISD::GlobalBaseReg,
2135                                            DebugLoc(), getPointerTy()),
2136                                InFlag);
2137       InFlag = Chain.getValue(1);
2138     } else {
2139       // If we are tail calling and generating PIC/GOT style code load the
2140       // address of the callee into ECX. The value in ecx is used as target of
2141       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2142       // for tail calls on PIC/GOT architectures. Normally we would just put the
2143       // address of GOT into ebx and then call target@PLT. But for tail calls
2144       // ebx would be restored (since ebx is callee saved) before jumping to the
2145       // target@PLT.
2146
2147       // Note: The actual moving to ECX is done further down.
2148       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2149       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2150           !G->getGlobal()->hasProtectedVisibility())
2151         Callee = LowerGlobalAddress(Callee, DAG);
2152       else if (isa<ExternalSymbolSDNode>(Callee))
2153         Callee = LowerExternalSymbol(Callee, DAG);
2154     }
2155   }
2156
2157   if (Is64Bit && isVarArg && !IsWin64) {
2158     // From AMD64 ABI document:
2159     // For calls that may call functions that use varargs or stdargs
2160     // (prototype-less calls or calls to functions containing ellipsis (...) in
2161     // the declaration) %al is used as hidden argument to specify the number
2162     // of SSE registers used. The contents of %al do not need to match exactly
2163     // the number of registers, but must be an ubound on the number of SSE
2164     // registers used and is in the range 0 - 8 inclusive.
2165
2166     // Count the number of XMM registers allocated.
2167     static const unsigned XMMArgRegs[] = {
2168       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2169       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2170     };
2171     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2172     assert((Subtarget->hasXMM() || !NumXMMRegs)
2173            && "SSE registers cannot be used when SSE is disabled");
2174
2175     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2176                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2177     InFlag = Chain.getValue(1);
2178   }
2179
2180
2181   // For tail calls lower the arguments to the 'real' stack slot.
2182   if (isTailCall) {
2183     // Force all the incoming stack arguments to be loaded from the stack
2184     // before any new outgoing arguments are stored to the stack, because the
2185     // outgoing stack slots may alias the incoming argument stack slots, and
2186     // the alias isn't otherwise explicit. This is slightly more conservative
2187     // than necessary, because it means that each store effectively depends
2188     // on every argument instead of just those arguments it would clobber.
2189     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2190
2191     SmallVector<SDValue, 8> MemOpChains2;
2192     SDValue FIN;
2193     int FI = 0;
2194     // Do not flag preceding copytoreg stuff together with the following stuff.
2195     InFlag = SDValue();
2196     if (GuaranteedTailCallOpt) {
2197       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2198         CCValAssign &VA = ArgLocs[i];
2199         if (VA.isRegLoc())
2200           continue;
2201         assert(VA.isMemLoc());
2202         SDValue Arg = OutVals[i];
2203         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2204         // Create frame index.
2205         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2206         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2207         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2208         FIN = DAG.getFrameIndex(FI, getPointerTy());
2209
2210         if (Flags.isByVal()) {
2211           // Copy relative to framepointer.
2212           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2213           if (StackPtr.getNode() == 0)
2214             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2215                                           getPointerTy());
2216           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2217
2218           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2219                                                            ArgChain,
2220                                                            Flags, DAG, dl));
2221         } else {
2222           // Store relative to framepointer.
2223           MemOpChains2.push_back(
2224             DAG.getStore(ArgChain, dl, Arg, FIN,
2225                          MachinePointerInfo::getFixedStack(FI),
2226                          false, false, 0));
2227         }
2228       }
2229     }
2230
2231     if (!MemOpChains2.empty())
2232       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2233                           &MemOpChains2[0], MemOpChains2.size());
2234
2235     // Copy arguments to their registers.
2236     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2237       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2238                                RegsToPass[i].second, InFlag);
2239       InFlag = Chain.getValue(1);
2240     }
2241     InFlag =SDValue();
2242
2243     // Store the return address to the appropriate stack slot.
2244     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2245                                      FPDiff, dl);
2246   }
2247
2248   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2249     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2250     // In the 64-bit large code model, we have to make all calls
2251     // through a register, since the call instruction's 32-bit
2252     // pc-relative offset may not be large enough to hold the whole
2253     // address.
2254   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2255     // If the callee is a GlobalAddress node (quite common, every direct call
2256     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2257     // it.
2258
2259     // We should use extra load for direct calls to dllimported functions in
2260     // non-JIT mode.
2261     const GlobalValue *GV = G->getGlobal();
2262     if (!GV->hasDLLImportLinkage()) {
2263       unsigned char OpFlags = 0;
2264       bool ExtraLoad = false;
2265       unsigned WrapperKind = ISD::DELETED_NODE;
2266
2267       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2268       // external symbols most go through the PLT in PIC mode.  If the symbol
2269       // has hidden or protected visibility, or if it is static or local, then
2270       // we don't need to use the PLT - we can directly call it.
2271       if (Subtarget->isTargetELF() &&
2272           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2273           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2274         OpFlags = X86II::MO_PLT;
2275       } else if (Subtarget->isPICStyleStubAny() &&
2276                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2277                  (!Subtarget->getTargetTriple().isMacOSX() ||
2278                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2279         // PC-relative references to external symbols should go through $stub,
2280         // unless we're building with the leopard linker or later, which
2281         // automatically synthesizes these stubs.
2282         OpFlags = X86II::MO_DARWIN_STUB;
2283       } else if (Subtarget->isPICStyleRIPRel() &&
2284                  isa<Function>(GV) &&
2285                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2286         // If the function is marked as non-lazy, generate an indirect call
2287         // which loads from the GOT directly. This avoids runtime overhead
2288         // at the cost of eager binding (and one extra byte of encoding).
2289         OpFlags = X86II::MO_GOTPCREL;
2290         WrapperKind = X86ISD::WrapperRIP;
2291         ExtraLoad = true;
2292       }
2293
2294       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2295                                           G->getOffset(), OpFlags);
2296
2297       // Add a wrapper if needed.
2298       if (WrapperKind != ISD::DELETED_NODE)
2299         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2300       // Add extra indirection if needed.
2301       if (ExtraLoad)
2302         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2303                              MachinePointerInfo::getGOT(),
2304                              false, false, 0);
2305     }
2306   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2307     unsigned char OpFlags = 0;
2308
2309     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2310     // external symbols should go through the PLT.
2311     if (Subtarget->isTargetELF() &&
2312         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2313       OpFlags = X86II::MO_PLT;
2314     } else if (Subtarget->isPICStyleStubAny() &&
2315                (!Subtarget->getTargetTriple().isMacOSX() ||
2316                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2317       // PC-relative references to external symbols should go through $stub,
2318       // unless we're building with the leopard linker or later, which
2319       // automatically synthesizes these stubs.
2320       OpFlags = X86II::MO_DARWIN_STUB;
2321     }
2322
2323     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2324                                          OpFlags);
2325   }
2326
2327   // Returns a chain & a flag for retval copy to use.
2328   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2329   SmallVector<SDValue, 8> Ops;
2330
2331   if (!IsSibcall && isTailCall) {
2332     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2333                            DAG.getIntPtrConstant(0, true), InFlag);
2334     InFlag = Chain.getValue(1);
2335   }
2336
2337   Ops.push_back(Chain);
2338   Ops.push_back(Callee);
2339
2340   if (isTailCall)
2341     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2342
2343   // Add argument registers to the end of the list so that they are known live
2344   // into the call.
2345   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2346     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2347                                   RegsToPass[i].second.getValueType()));
2348
2349   // Add an implicit use GOT pointer in EBX.
2350   if (!isTailCall && Subtarget->isPICStyleGOT())
2351     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2352
2353   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2354   if (Is64Bit && isVarArg && !IsWin64)
2355     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2356
2357   if (InFlag.getNode())
2358     Ops.push_back(InFlag);
2359
2360   if (isTailCall) {
2361     // We used to do:
2362     //// If this is the first return lowered for this function, add the regs
2363     //// to the liveout set for the function.
2364     // This isn't right, although it's probably harmless on x86; liveouts
2365     // should be computed from returns not tail calls.  Consider a void
2366     // function making a tail call to a function returning int.
2367     return DAG.getNode(X86ISD::TC_RETURN, dl,
2368                        NodeTys, &Ops[0], Ops.size());
2369   }
2370
2371   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2372   InFlag = Chain.getValue(1);
2373
2374   // Create the CALLSEQ_END node.
2375   unsigned NumBytesForCalleeToPush;
2376   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2377     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2378   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2379     // If this is a call to a struct-return function, the callee
2380     // pops the hidden struct pointer, so we have to push it back.
2381     // This is common for Darwin/X86, Linux & Mingw32 targets.
2382     NumBytesForCalleeToPush = 4;
2383   else
2384     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2385
2386   // Returns a flag for retval copy to use.
2387   if (!IsSibcall) {
2388     Chain = DAG.getCALLSEQ_END(Chain,
2389                                DAG.getIntPtrConstant(NumBytes, true),
2390                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2391                                                      true),
2392                                InFlag);
2393     InFlag = Chain.getValue(1);
2394   }
2395
2396   // Handle result values, copying them out of physregs into vregs that we
2397   // return.
2398   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2399                          Ins, dl, DAG, InVals);
2400 }
2401
2402
2403 //===----------------------------------------------------------------------===//
2404 //                Fast Calling Convention (tail call) implementation
2405 //===----------------------------------------------------------------------===//
2406
2407 //  Like std call, callee cleans arguments, convention except that ECX is
2408 //  reserved for storing the tail called function address. Only 2 registers are
2409 //  free for argument passing (inreg). Tail call optimization is performed
2410 //  provided:
2411 //                * tailcallopt is enabled
2412 //                * caller/callee are fastcc
2413 //  On X86_64 architecture with GOT-style position independent code only local
2414 //  (within module) calls are supported at the moment.
2415 //  To keep the stack aligned according to platform abi the function
2416 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2417 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2418 //  If a tail called function callee has more arguments than the caller the
2419 //  caller needs to make sure that there is room to move the RETADDR to. This is
2420 //  achieved by reserving an area the size of the argument delta right after the
2421 //  original REtADDR, but before the saved framepointer or the spilled registers
2422 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2423 //  stack layout:
2424 //    arg1
2425 //    arg2
2426 //    RETADDR
2427 //    [ new RETADDR
2428 //      move area ]
2429 //    (possible EBP)
2430 //    ESI
2431 //    EDI
2432 //    local1 ..
2433
2434 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2435 /// for a 16 byte align requirement.
2436 unsigned
2437 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2438                                                SelectionDAG& DAG) const {
2439   MachineFunction &MF = DAG.getMachineFunction();
2440   const TargetMachine &TM = MF.getTarget();
2441   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2442   unsigned StackAlignment = TFI.getStackAlignment();
2443   uint64_t AlignMask = StackAlignment - 1;
2444   int64_t Offset = StackSize;
2445   uint64_t SlotSize = TD->getPointerSize();
2446   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2447     // Number smaller than 12 so just add the difference.
2448     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2449   } else {
2450     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2451     Offset = ((~AlignMask) & Offset) + StackAlignment +
2452       (StackAlignment-SlotSize);
2453   }
2454   return Offset;
2455 }
2456
2457 /// MatchingStackOffset - Return true if the given stack call argument is
2458 /// already available in the same position (relatively) of the caller's
2459 /// incoming argument stack.
2460 static
2461 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2462                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2463                          const X86InstrInfo *TII) {
2464   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2465   int FI = INT_MAX;
2466   if (Arg.getOpcode() == ISD::CopyFromReg) {
2467     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2468     if (!TargetRegisterInfo::isVirtualRegister(VR))
2469       return false;
2470     MachineInstr *Def = MRI->getVRegDef(VR);
2471     if (!Def)
2472       return false;
2473     if (!Flags.isByVal()) {
2474       if (!TII->isLoadFromStackSlot(Def, FI))
2475         return false;
2476     } else {
2477       unsigned Opcode = Def->getOpcode();
2478       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2479           Def->getOperand(1).isFI()) {
2480         FI = Def->getOperand(1).getIndex();
2481         Bytes = Flags.getByValSize();
2482       } else
2483         return false;
2484     }
2485   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2486     if (Flags.isByVal())
2487       // ByVal argument is passed in as a pointer but it's now being
2488       // dereferenced. e.g.
2489       // define @foo(%struct.X* %A) {
2490       //   tail call @bar(%struct.X* byval %A)
2491       // }
2492       return false;
2493     SDValue Ptr = Ld->getBasePtr();
2494     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2495     if (!FINode)
2496       return false;
2497     FI = FINode->getIndex();
2498   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2499     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2500     FI = FINode->getIndex();
2501     Bytes = Flags.getByValSize();
2502   } else
2503     return false;
2504
2505   assert(FI != INT_MAX);
2506   if (!MFI->isFixedObjectIndex(FI))
2507     return false;
2508   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2509 }
2510
2511 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2512 /// for tail call optimization. Targets which want to do tail call
2513 /// optimization should implement this function.
2514 bool
2515 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2516                                                      CallingConv::ID CalleeCC,
2517                                                      bool isVarArg,
2518                                                      bool isCalleeStructRet,
2519                                                      bool isCallerStructRet,
2520                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2521                                     const SmallVectorImpl<SDValue> &OutVals,
2522                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2523                                                      SelectionDAG& DAG) const {
2524   if (!IsTailCallConvention(CalleeCC) &&
2525       CalleeCC != CallingConv::C)
2526     return false;
2527
2528   // If -tailcallopt is specified, make fastcc functions tail-callable.
2529   const MachineFunction &MF = DAG.getMachineFunction();
2530   const Function *CallerF = DAG.getMachineFunction().getFunction();
2531   CallingConv::ID CallerCC = CallerF->getCallingConv();
2532   bool CCMatch = CallerCC == CalleeCC;
2533
2534   if (GuaranteedTailCallOpt) {
2535     if (IsTailCallConvention(CalleeCC) && CCMatch)
2536       return true;
2537     return false;
2538   }
2539
2540   // Look for obvious safe cases to perform tail call optimization that do not
2541   // require ABI changes. This is what gcc calls sibcall.
2542
2543   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2544   // emit a special epilogue.
2545   if (RegInfo->needsStackRealignment(MF))
2546     return false;
2547
2548   // Also avoid sibcall optimization if either caller or callee uses struct
2549   // return semantics.
2550   if (isCalleeStructRet || isCallerStructRet)
2551     return false;
2552
2553   // An stdcall caller is expected to clean up its arguments; the callee
2554   // isn't going to do that.
2555   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2556     return false;
2557
2558   // Do not sibcall optimize vararg calls unless all arguments are passed via
2559   // registers.
2560   if (isVarArg && !Outs.empty()) {
2561
2562     // Optimizing for varargs on Win64 is unlikely to be safe without
2563     // additional testing.
2564     if (Subtarget->isTargetWin64())
2565       return false;
2566
2567     SmallVector<CCValAssign, 16> ArgLocs;
2568     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2569                    getTargetMachine(), ArgLocs, *DAG.getContext());
2570
2571     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2572     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2573       if (!ArgLocs[i].isRegLoc())
2574         return false;
2575   }
2576
2577   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2578   // Therefore if it's not used by the call it is not safe to optimize this into
2579   // a sibcall.
2580   bool Unused = false;
2581   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2582     if (!Ins[i].Used) {
2583       Unused = true;
2584       break;
2585     }
2586   }
2587   if (Unused) {
2588     SmallVector<CCValAssign, 16> RVLocs;
2589     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2590                    getTargetMachine(), RVLocs, *DAG.getContext());
2591     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2592     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2593       CCValAssign &VA = RVLocs[i];
2594       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2595         return false;
2596     }
2597   }
2598
2599   // If the calling conventions do not match, then we'd better make sure the
2600   // results are returned in the same way as what the caller expects.
2601   if (!CCMatch) {
2602     SmallVector<CCValAssign, 16> RVLocs1;
2603     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2604                     getTargetMachine(), RVLocs1, *DAG.getContext());
2605     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2606
2607     SmallVector<CCValAssign, 16> RVLocs2;
2608     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2609                     getTargetMachine(), RVLocs2, *DAG.getContext());
2610     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2611
2612     if (RVLocs1.size() != RVLocs2.size())
2613       return false;
2614     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2615       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2616         return false;
2617       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2618         return false;
2619       if (RVLocs1[i].isRegLoc()) {
2620         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2621           return false;
2622       } else {
2623         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2624           return false;
2625       }
2626     }
2627   }
2628
2629   // If the callee takes no arguments then go on to check the results of the
2630   // call.
2631   if (!Outs.empty()) {
2632     // Check if stack adjustment is needed. For now, do not do this if any
2633     // argument is passed on the stack.
2634     SmallVector<CCValAssign, 16> ArgLocs;
2635     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2636                    getTargetMachine(), ArgLocs, *DAG.getContext());
2637
2638     // Allocate shadow area for Win64
2639     if (Subtarget->isTargetWin64()) {
2640       CCInfo.AllocateStack(32, 8);
2641     }
2642
2643     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2644     if (CCInfo.getNextStackOffset()) {
2645       MachineFunction &MF = DAG.getMachineFunction();
2646       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2647         return false;
2648
2649       // Check if the arguments are already laid out in the right way as
2650       // the caller's fixed stack objects.
2651       MachineFrameInfo *MFI = MF.getFrameInfo();
2652       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2653       const X86InstrInfo *TII =
2654         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2655       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2656         CCValAssign &VA = ArgLocs[i];
2657         SDValue Arg = OutVals[i];
2658         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2659         if (VA.getLocInfo() == CCValAssign::Indirect)
2660           return false;
2661         if (!VA.isRegLoc()) {
2662           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2663                                    MFI, MRI, TII))
2664             return false;
2665         }
2666       }
2667     }
2668
2669     // If the tailcall address may be in a register, then make sure it's
2670     // possible to register allocate for it. In 32-bit, the call address can
2671     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2672     // callee-saved registers are restored. These happen to be the same
2673     // registers used to pass 'inreg' arguments so watch out for those.
2674     if (!Subtarget->is64Bit() &&
2675         !isa<GlobalAddressSDNode>(Callee) &&
2676         !isa<ExternalSymbolSDNode>(Callee)) {
2677       unsigned NumInRegs = 0;
2678       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2679         CCValAssign &VA = ArgLocs[i];
2680         if (!VA.isRegLoc())
2681           continue;
2682         unsigned Reg = VA.getLocReg();
2683         switch (Reg) {
2684         default: break;
2685         case X86::EAX: case X86::EDX: case X86::ECX:
2686           if (++NumInRegs == 3)
2687             return false;
2688           break;
2689         }
2690       }
2691     }
2692   }
2693
2694   return true;
2695 }
2696
2697 FastISel *
2698 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2699   return X86::createFastISel(funcInfo);
2700 }
2701
2702
2703 //===----------------------------------------------------------------------===//
2704 //                           Other Lowering Hooks
2705 //===----------------------------------------------------------------------===//
2706
2707 static bool MayFoldLoad(SDValue Op) {
2708   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2709 }
2710
2711 static bool MayFoldIntoStore(SDValue Op) {
2712   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2713 }
2714
2715 static bool isTargetShuffle(unsigned Opcode) {
2716   switch(Opcode) {
2717   default: return false;
2718   case X86ISD::PSHUFD:
2719   case X86ISD::PSHUFHW:
2720   case X86ISD::PSHUFLW:
2721   case X86ISD::SHUFPD:
2722   case X86ISD::PALIGN:
2723   case X86ISD::SHUFPS:
2724   case X86ISD::MOVLHPS:
2725   case X86ISD::MOVLHPD:
2726   case X86ISD::MOVHLPS:
2727   case X86ISD::MOVLPS:
2728   case X86ISD::MOVLPD:
2729   case X86ISD::MOVSHDUP:
2730   case X86ISD::MOVSLDUP:
2731   case X86ISD::MOVDDUP:
2732   case X86ISD::MOVSS:
2733   case X86ISD::MOVSD:
2734   case X86ISD::UNPCKLPS:
2735   case X86ISD::UNPCKLPD:
2736   case X86ISD::VUNPCKLPS:
2737   case X86ISD::VUNPCKLPD:
2738   case X86ISD::VUNPCKLPSY:
2739   case X86ISD::VUNPCKLPDY:
2740   case X86ISD::PUNPCKLWD:
2741   case X86ISD::PUNPCKLBW:
2742   case X86ISD::PUNPCKLDQ:
2743   case X86ISD::PUNPCKLQDQ:
2744   case X86ISD::UNPCKHPS:
2745   case X86ISD::UNPCKHPD:
2746   case X86ISD::PUNPCKHWD:
2747   case X86ISD::PUNPCKHBW:
2748   case X86ISD::PUNPCKHDQ:
2749   case X86ISD::PUNPCKHQDQ:
2750   case X86ISD::VPERMIL:
2751     return true;
2752   }
2753   return false;
2754 }
2755
2756 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2757                                                SDValue V1, SelectionDAG &DAG) {
2758   switch(Opc) {
2759   default: llvm_unreachable("Unknown x86 shuffle node");
2760   case X86ISD::MOVSHDUP:
2761   case X86ISD::MOVSLDUP:
2762   case X86ISD::MOVDDUP:
2763     return DAG.getNode(Opc, dl, VT, V1);
2764   }
2765
2766   return SDValue();
2767 }
2768
2769 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2770                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2771   switch(Opc) {
2772   default: llvm_unreachable("Unknown x86 shuffle node");
2773   case X86ISD::PSHUFD:
2774   case X86ISD::PSHUFHW:
2775   case X86ISD::PSHUFLW:
2776   case X86ISD::VPERMIL:
2777     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2778   }
2779
2780   return SDValue();
2781 }
2782
2783 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2784                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2785   switch(Opc) {
2786   default: llvm_unreachable("Unknown x86 shuffle node");
2787   case X86ISD::PALIGN:
2788   case X86ISD::SHUFPD:
2789   case X86ISD::SHUFPS:
2790     return DAG.getNode(Opc, dl, VT, V1, V2,
2791                        DAG.getConstant(TargetMask, MVT::i8));
2792   }
2793   return SDValue();
2794 }
2795
2796 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2797                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2798   switch(Opc) {
2799   default: llvm_unreachable("Unknown x86 shuffle node");
2800   case X86ISD::MOVLHPS:
2801   case X86ISD::MOVLHPD:
2802   case X86ISD::MOVHLPS:
2803   case X86ISD::MOVLPS:
2804   case X86ISD::MOVLPD:
2805   case X86ISD::MOVSS:
2806   case X86ISD::MOVSD:
2807   case X86ISD::UNPCKLPS:
2808   case X86ISD::UNPCKLPD:
2809   case X86ISD::VUNPCKLPS:
2810   case X86ISD::VUNPCKLPD:
2811   case X86ISD::VUNPCKLPSY:
2812   case X86ISD::VUNPCKLPDY:
2813   case X86ISD::PUNPCKLWD:
2814   case X86ISD::PUNPCKLBW:
2815   case X86ISD::PUNPCKLDQ:
2816   case X86ISD::PUNPCKLQDQ:
2817   case X86ISD::UNPCKHPS:
2818   case X86ISD::UNPCKHPD:
2819   case X86ISD::PUNPCKHWD:
2820   case X86ISD::PUNPCKHBW:
2821   case X86ISD::PUNPCKHDQ:
2822   case X86ISD::PUNPCKHQDQ:
2823     return DAG.getNode(Opc, dl, VT, V1, V2);
2824   }
2825   return SDValue();
2826 }
2827
2828 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2829   MachineFunction &MF = DAG.getMachineFunction();
2830   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2831   int ReturnAddrIndex = FuncInfo->getRAIndex();
2832
2833   if (ReturnAddrIndex == 0) {
2834     // Set up a frame object for the return address.
2835     uint64_t SlotSize = TD->getPointerSize();
2836     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2837                                                            false);
2838     FuncInfo->setRAIndex(ReturnAddrIndex);
2839   }
2840
2841   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2842 }
2843
2844
2845 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2846                                        bool hasSymbolicDisplacement) {
2847   // Offset should fit into 32 bit immediate field.
2848   if (!isInt<32>(Offset))
2849     return false;
2850
2851   // If we don't have a symbolic displacement - we don't have any extra
2852   // restrictions.
2853   if (!hasSymbolicDisplacement)
2854     return true;
2855
2856   // FIXME: Some tweaks might be needed for medium code model.
2857   if (M != CodeModel::Small && M != CodeModel::Kernel)
2858     return false;
2859
2860   // For small code model we assume that latest object is 16MB before end of 31
2861   // bits boundary. We may also accept pretty large negative constants knowing
2862   // that all objects are in the positive half of address space.
2863   if (M == CodeModel::Small && Offset < 16*1024*1024)
2864     return true;
2865
2866   // For kernel code model we know that all object resist in the negative half
2867   // of 32bits address space. We may not accept negative offsets, since they may
2868   // be just off and we may accept pretty large positive ones.
2869   if (M == CodeModel::Kernel && Offset > 0)
2870     return true;
2871
2872   return false;
2873 }
2874
2875 /// isCalleePop - Determines whether the callee is required to pop its
2876 /// own arguments. Callee pop is necessary to support tail calls.
2877 bool X86::isCalleePop(CallingConv::ID CallingConv,
2878                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2879   if (IsVarArg)
2880     return false;
2881
2882   switch (CallingConv) {
2883   default:
2884     return false;
2885   case CallingConv::X86_StdCall:
2886     return !is64Bit;
2887   case CallingConv::X86_FastCall:
2888     return !is64Bit;
2889   case CallingConv::X86_ThisCall:
2890     return !is64Bit;
2891   case CallingConv::Fast:
2892     return TailCallOpt;
2893   case CallingConv::GHC:
2894     return TailCallOpt;
2895   }
2896 }
2897
2898 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2899 /// specific condition code, returning the condition code and the LHS/RHS of the
2900 /// comparison to make.
2901 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2902                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2903   if (!isFP) {
2904     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2905       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2906         // X > -1   -> X == 0, jump !sign.
2907         RHS = DAG.getConstant(0, RHS.getValueType());
2908         return X86::COND_NS;
2909       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2910         // X < 0   -> X == 0, jump on sign.
2911         return X86::COND_S;
2912       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2913         // X < 1   -> X <= 0
2914         RHS = DAG.getConstant(0, RHS.getValueType());
2915         return X86::COND_LE;
2916       }
2917     }
2918
2919     switch (SetCCOpcode) {
2920     default: llvm_unreachable("Invalid integer condition!");
2921     case ISD::SETEQ:  return X86::COND_E;
2922     case ISD::SETGT:  return X86::COND_G;
2923     case ISD::SETGE:  return X86::COND_GE;
2924     case ISD::SETLT:  return X86::COND_L;
2925     case ISD::SETLE:  return X86::COND_LE;
2926     case ISD::SETNE:  return X86::COND_NE;
2927     case ISD::SETULT: return X86::COND_B;
2928     case ISD::SETUGT: return X86::COND_A;
2929     case ISD::SETULE: return X86::COND_BE;
2930     case ISD::SETUGE: return X86::COND_AE;
2931     }
2932   }
2933
2934   // First determine if it is required or is profitable to flip the operands.
2935
2936   // If LHS is a foldable load, but RHS is not, flip the condition.
2937   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2938       !ISD::isNON_EXTLoad(RHS.getNode())) {
2939     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2940     std::swap(LHS, RHS);
2941   }
2942
2943   switch (SetCCOpcode) {
2944   default: break;
2945   case ISD::SETOLT:
2946   case ISD::SETOLE:
2947   case ISD::SETUGT:
2948   case ISD::SETUGE:
2949     std::swap(LHS, RHS);
2950     break;
2951   }
2952
2953   // On a floating point condition, the flags are set as follows:
2954   // ZF  PF  CF   op
2955   //  0 | 0 | 0 | X > Y
2956   //  0 | 0 | 1 | X < Y
2957   //  1 | 0 | 0 | X == Y
2958   //  1 | 1 | 1 | unordered
2959   switch (SetCCOpcode) {
2960   default: llvm_unreachable("Condcode should be pre-legalized away");
2961   case ISD::SETUEQ:
2962   case ISD::SETEQ:   return X86::COND_E;
2963   case ISD::SETOLT:              // flipped
2964   case ISD::SETOGT:
2965   case ISD::SETGT:   return X86::COND_A;
2966   case ISD::SETOLE:              // flipped
2967   case ISD::SETOGE:
2968   case ISD::SETGE:   return X86::COND_AE;
2969   case ISD::SETUGT:              // flipped
2970   case ISD::SETULT:
2971   case ISD::SETLT:   return X86::COND_B;
2972   case ISD::SETUGE:              // flipped
2973   case ISD::SETULE:
2974   case ISD::SETLE:   return X86::COND_BE;
2975   case ISD::SETONE:
2976   case ISD::SETNE:   return X86::COND_NE;
2977   case ISD::SETUO:   return X86::COND_P;
2978   case ISD::SETO:    return X86::COND_NP;
2979   case ISD::SETOEQ:
2980   case ISD::SETUNE:  return X86::COND_INVALID;
2981   }
2982 }
2983
2984 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2985 /// code. Current x86 isa includes the following FP cmov instructions:
2986 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2987 static bool hasFPCMov(unsigned X86CC) {
2988   switch (X86CC) {
2989   default:
2990     return false;
2991   case X86::COND_B:
2992   case X86::COND_BE:
2993   case X86::COND_E:
2994   case X86::COND_P:
2995   case X86::COND_A:
2996   case X86::COND_AE:
2997   case X86::COND_NE:
2998   case X86::COND_NP:
2999     return true;
3000   }
3001 }
3002
3003 /// isFPImmLegal - Returns true if the target can instruction select the
3004 /// specified FP immediate natively. If false, the legalizer will
3005 /// materialize the FP immediate as a load from a constant pool.
3006 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3007   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3008     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3009       return true;
3010   }
3011   return false;
3012 }
3013
3014 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3015 /// the specified range (L, H].
3016 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3017   return (Val < 0) || (Val >= Low && Val < Hi);
3018 }
3019
3020 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3021 /// specified value.
3022 static bool isUndefOrEqual(int Val, int CmpVal) {
3023   if (Val < 0 || Val == CmpVal)
3024     return true;
3025   return false;
3026 }
3027
3028 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3029 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3030 /// the second operand.
3031 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3032   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3033     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3034   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3035     return (Mask[0] < 2 && Mask[1] < 2);
3036   return false;
3037 }
3038
3039 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3040   SmallVector<int, 8> M;
3041   N->getMask(M);
3042   return ::isPSHUFDMask(M, N->getValueType(0));
3043 }
3044
3045 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3046 /// is suitable for input to PSHUFHW.
3047 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3048   if (VT != MVT::v8i16)
3049     return false;
3050
3051   // Lower quadword copied in order or undef.
3052   for (int i = 0; i != 4; ++i)
3053     if (Mask[i] >= 0 && Mask[i] != i)
3054       return false;
3055
3056   // Upper quadword shuffled.
3057   for (int i = 4; i != 8; ++i)
3058     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3059       return false;
3060
3061   return true;
3062 }
3063
3064 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3065   SmallVector<int, 8> M;
3066   N->getMask(M);
3067   return ::isPSHUFHWMask(M, N->getValueType(0));
3068 }
3069
3070 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3071 /// is suitable for input to PSHUFLW.
3072 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3073   if (VT != MVT::v8i16)
3074     return false;
3075
3076   // Upper quadword copied in order.
3077   for (int i = 4; i != 8; ++i)
3078     if (Mask[i] >= 0 && Mask[i] != i)
3079       return false;
3080
3081   // Lower quadword shuffled.
3082   for (int i = 0; i != 4; ++i)
3083     if (Mask[i] >= 4)
3084       return false;
3085
3086   return true;
3087 }
3088
3089 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3090   SmallVector<int, 8> M;
3091   N->getMask(M);
3092   return ::isPSHUFLWMask(M, N->getValueType(0));
3093 }
3094
3095 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3096 /// is suitable for input to PALIGNR.
3097 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3098                           bool hasSSSE3) {
3099   int i, e = VT.getVectorNumElements();
3100
3101   // Do not handle v2i64 / v2f64 shuffles with palignr.
3102   if (e < 4 || !hasSSSE3)
3103     return false;
3104
3105   for (i = 0; i != e; ++i)
3106     if (Mask[i] >= 0)
3107       break;
3108
3109   // All undef, not a palignr.
3110   if (i == e)
3111     return false;
3112
3113   // Determine if it's ok to perform a palignr with only the LHS, since we
3114   // don't have access to the actual shuffle elements to see if RHS is undef.
3115   bool Unary = Mask[i] < (int)e;
3116   bool NeedsUnary = false;
3117
3118   int s = Mask[i] - i;
3119
3120   // Check the rest of the elements to see if they are consecutive.
3121   for (++i; i != e; ++i) {
3122     int m = Mask[i];
3123     if (m < 0)
3124       continue;
3125
3126     Unary = Unary && (m < (int)e);
3127     NeedsUnary = NeedsUnary || (m < s);
3128
3129     if (NeedsUnary && !Unary)
3130       return false;
3131     if (Unary && m != ((s+i) & (e-1)))
3132       return false;
3133     if (!Unary && m != (s+i))
3134       return false;
3135   }
3136   return true;
3137 }
3138
3139 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3140   SmallVector<int, 8> M;
3141   N->getMask(M);
3142   return ::isPALIGNRMask(M, N->getValueType(0), true);
3143 }
3144
3145 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3146 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3147 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3148   int NumElems = VT.getVectorNumElements();
3149   if (NumElems != 2 && NumElems != 4)
3150     return false;
3151
3152   int Half = NumElems / 2;
3153   for (int i = 0; i < Half; ++i)
3154     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3155       return false;
3156   for (int i = Half; i < NumElems; ++i)
3157     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3158       return false;
3159
3160   return true;
3161 }
3162
3163 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3164   SmallVector<int, 8> M;
3165   N->getMask(M);
3166   return ::isSHUFPMask(M, N->getValueType(0));
3167 }
3168
3169 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3170 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3171 /// half elements to come from vector 1 (which would equal the dest.) and
3172 /// the upper half to come from vector 2.
3173 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3174   int NumElems = VT.getVectorNumElements();
3175
3176   if (NumElems != 2 && NumElems != 4)
3177     return false;
3178
3179   int Half = NumElems / 2;
3180   for (int i = 0; i < Half; ++i)
3181     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3182       return false;
3183   for (int i = Half; i < NumElems; ++i)
3184     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3185       return false;
3186   return true;
3187 }
3188
3189 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3190   SmallVector<int, 8> M;
3191   N->getMask(M);
3192   return isCommutedSHUFPMask(M, N->getValueType(0));
3193 }
3194
3195 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3196 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3197 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3198   if (N->getValueType(0).getVectorNumElements() != 4)
3199     return false;
3200
3201   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3202   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3203          isUndefOrEqual(N->getMaskElt(1), 7) &&
3204          isUndefOrEqual(N->getMaskElt(2), 2) &&
3205          isUndefOrEqual(N->getMaskElt(3), 3);
3206 }
3207
3208 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3209 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3210 /// <2, 3, 2, 3>
3211 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3212   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3213
3214   if (NumElems != 4)
3215     return false;
3216
3217   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3218   isUndefOrEqual(N->getMaskElt(1), 3) &&
3219   isUndefOrEqual(N->getMaskElt(2), 2) &&
3220   isUndefOrEqual(N->getMaskElt(3), 3);
3221 }
3222
3223 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3224 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3225 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3226   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3227
3228   if (NumElems != 2 && NumElems != 4)
3229     return false;
3230
3231   for (unsigned i = 0; i < NumElems/2; ++i)
3232     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3233       return false;
3234
3235   for (unsigned i = NumElems/2; i < NumElems; ++i)
3236     if (!isUndefOrEqual(N->getMaskElt(i), i))
3237       return false;
3238
3239   return true;
3240 }
3241
3242 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3243 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3244 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3245   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3246
3247   if ((NumElems != 2 && NumElems != 4)
3248       || N->getValueType(0).getSizeInBits() > 128)
3249     return false;
3250
3251   for (unsigned i = 0; i < NumElems/2; ++i)
3252     if (!isUndefOrEqual(N->getMaskElt(i), i))
3253       return false;
3254
3255   for (unsigned i = 0; i < NumElems/2; ++i)
3256     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3257       return false;
3258
3259   return true;
3260 }
3261
3262 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3263 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3264 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3265                          bool V2IsSplat = false) {
3266   int NumElts = VT.getVectorNumElements();
3267   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3268     return false;
3269
3270   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3271   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3272   // sections.
3273   unsigned NumSections = VT.getSizeInBits() / 128;
3274   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3275   unsigned NumSectionElts = NumElts / NumSections;
3276
3277   unsigned Start = 0;
3278   unsigned End = NumSectionElts;
3279   for (unsigned s = 0; s < NumSections; ++s) {
3280     for (unsigned i = Start, j = s * NumSectionElts;
3281          i != End;
3282          i += 2, ++j) {
3283       int BitI  = Mask[i];
3284       int BitI1 = Mask[i+1];
3285       if (!isUndefOrEqual(BitI, j))
3286         return false;
3287       if (V2IsSplat) {
3288         if (!isUndefOrEqual(BitI1, NumElts))
3289           return false;
3290       } else {
3291         if (!isUndefOrEqual(BitI1, j + NumElts))
3292           return false;
3293       }
3294     }
3295     // Process the next 128 bits.
3296     Start += NumSectionElts;
3297     End += NumSectionElts;
3298   }
3299
3300   return true;
3301 }
3302
3303 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3304   SmallVector<int, 8> M;
3305   N->getMask(M);
3306   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3307 }
3308
3309 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3310 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3311 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3312                          bool V2IsSplat = false) {
3313   int NumElts = VT.getVectorNumElements();
3314   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3315     return false;
3316
3317   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3318     int BitI  = Mask[i];
3319     int BitI1 = Mask[i+1];
3320     if (!isUndefOrEqual(BitI, j + NumElts/2))
3321       return false;
3322     if (V2IsSplat) {
3323       if (isUndefOrEqual(BitI1, NumElts))
3324         return false;
3325     } else {
3326       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3327         return false;
3328     }
3329   }
3330   return true;
3331 }
3332
3333 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3334   SmallVector<int, 8> M;
3335   N->getMask(M);
3336   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3337 }
3338
3339 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3340 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3341 /// <0, 0, 1, 1>
3342 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3343   int NumElems = VT.getVectorNumElements();
3344   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3345     return false;
3346
3347   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3348   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3349   // sections.
3350   unsigned NumSections = VT.getSizeInBits() / 128;
3351   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3352   unsigned NumSectionElts = NumElems / NumSections;
3353
3354   for (unsigned s = 0; s < NumSections; ++s) {
3355     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3356          i != NumSectionElts * (s + 1);
3357          i += 2, ++j) {
3358       int BitI  = Mask[i];
3359       int BitI1 = Mask[i+1];
3360
3361       if (!isUndefOrEqual(BitI, j))
3362         return false;
3363       if (!isUndefOrEqual(BitI1, j))
3364         return false;
3365     }
3366   }
3367
3368   return true;
3369 }
3370
3371 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3372   SmallVector<int, 8> M;
3373   N->getMask(M);
3374   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3375 }
3376
3377 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3378 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3379 /// <2, 2, 3, 3>
3380 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3381   int NumElems = VT.getVectorNumElements();
3382   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3383     return false;
3384
3385   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3386     int BitI  = Mask[i];
3387     int BitI1 = Mask[i+1];
3388     if (!isUndefOrEqual(BitI, j))
3389       return false;
3390     if (!isUndefOrEqual(BitI1, j))
3391       return false;
3392   }
3393   return true;
3394 }
3395
3396 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3397   SmallVector<int, 8> M;
3398   N->getMask(M);
3399   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3400 }
3401
3402 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3403 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3404 /// MOVSD, and MOVD, i.e. setting the lowest element.
3405 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3406   if (VT.getVectorElementType().getSizeInBits() < 32)
3407     return false;
3408
3409   int NumElts = VT.getVectorNumElements();
3410
3411   if (!isUndefOrEqual(Mask[0], NumElts))
3412     return false;
3413
3414   for (int i = 1; i < NumElts; ++i)
3415     if (!isUndefOrEqual(Mask[i], i))
3416       return false;
3417
3418   return true;
3419 }
3420
3421 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3422   SmallVector<int, 8> M;
3423   N->getMask(M);
3424   return ::isMOVLMask(M, N->getValueType(0));
3425 }
3426
3427 /// isVPERMILMask - Return true if the specified VECTOR_SHUFFLE operand
3428 /// specifies a shuffle of elements that is suitable for input to VPERMIL*.
3429 static bool isVPERMILMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3430   unsigned NumElts = VT.getVectorNumElements();
3431   unsigned NumLanes = VT.getSizeInBits()/128;
3432
3433   // Match any permutation of 128-bit vector with 32/64-bit types
3434   if (NumLanes == 1) {
3435     if (NumElts == 4 || NumElts == 2)
3436       return true;
3437     return false;
3438   }
3439
3440   // Only match 256-bit with 32/64-bit types
3441   if (NumElts != 8 && NumElts != 4)
3442     return false;
3443
3444   // The mask on the high lane should be the same as the low. Actually,
3445   // they can differ if any of the corresponding index in a lane is undef.
3446   int LaneSize = NumElts/NumLanes;
3447   for (int i = 0; i < LaneSize; ++i) {
3448     int HighElt = i+LaneSize;
3449     if (Mask[i] < 0 || Mask[HighElt] < 0)
3450       continue;
3451
3452     if (Mask[HighElt]-Mask[i] != LaneSize)
3453       return false;
3454   }
3455
3456   return true;
3457 }
3458
3459 /// getShuffleVPERMILImmediateediate - Return the appropriate immediate to shuffle
3460 /// the specified VECTOR_MASK mask with VPERMIL* instructions.
3461 static unsigned getShuffleVPERMILImmediate(SDNode *N) {
3462   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3463   EVT VT = SVOp->getValueType(0);
3464
3465   int NumElts = VT.getVectorNumElements();
3466   int NumLanes = VT.getSizeInBits()/128;
3467
3468   unsigned Mask = 0;
3469   for (int i = 0; i < NumElts/NumLanes /* lane size */; ++i)
3470     Mask |= SVOp->getMaskElt(i) << (i*2);
3471
3472   return Mask;
3473 }
3474
3475 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3476 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3477 /// element of vector 2 and the other elements to come from vector 1 in order.
3478 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3479                                bool V2IsSplat = false, bool V2IsUndef = false) {
3480   int NumOps = VT.getVectorNumElements();
3481   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3482     return false;
3483
3484   if (!isUndefOrEqual(Mask[0], 0))
3485     return false;
3486
3487   for (int i = 1; i < NumOps; ++i)
3488     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3489           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3490           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3491       return false;
3492
3493   return true;
3494 }
3495
3496 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3497                            bool V2IsUndef = false) {
3498   SmallVector<int, 8> M;
3499   N->getMask(M);
3500   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3501 }
3502
3503 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3504 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3505 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3506   if (N->getValueType(0).getVectorNumElements() != 4)
3507     return false;
3508
3509   // Expect 1, 1, 3, 3
3510   for (unsigned i = 0; i < 2; ++i) {
3511     int Elt = N->getMaskElt(i);
3512     if (Elt >= 0 && Elt != 1)
3513       return false;
3514   }
3515
3516   bool HasHi = false;
3517   for (unsigned i = 2; i < 4; ++i) {
3518     int Elt = N->getMaskElt(i);
3519     if (Elt >= 0 && Elt != 3)
3520       return false;
3521     if (Elt == 3)
3522       HasHi = true;
3523   }
3524   // Don't use movshdup if it can be done with a shufps.
3525   // FIXME: verify that matching u, u, 3, 3 is what we want.
3526   return HasHi;
3527 }
3528
3529 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3530 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3531 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3532   if (N->getValueType(0).getVectorNumElements() != 4)
3533     return false;
3534
3535   // Expect 0, 0, 2, 2
3536   for (unsigned i = 0; i < 2; ++i)
3537     if (N->getMaskElt(i) > 0)
3538       return false;
3539
3540   bool HasHi = false;
3541   for (unsigned i = 2; i < 4; ++i) {
3542     int Elt = N->getMaskElt(i);
3543     if (Elt >= 0 && Elt != 2)
3544       return false;
3545     if (Elt == 2)
3546       HasHi = true;
3547   }
3548   // Don't use movsldup if it can be done with a shufps.
3549   return HasHi;
3550 }
3551
3552 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3553 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3554 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3555   int e = N->getValueType(0).getVectorNumElements() / 2;
3556
3557   for (int i = 0; i < e; ++i)
3558     if (!isUndefOrEqual(N->getMaskElt(i), i))
3559       return false;
3560   for (int i = 0; i < e; ++i)
3561     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3562       return false;
3563   return true;
3564 }
3565
3566 /// isVEXTRACTF128Index - Return true if the specified
3567 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3568 /// suitable for input to VEXTRACTF128.
3569 bool X86::isVEXTRACTF128Index(SDNode *N) {
3570   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3571     return false;
3572
3573   // The index should be aligned on a 128-bit boundary.
3574   uint64_t Index =
3575     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3576
3577   unsigned VL = N->getValueType(0).getVectorNumElements();
3578   unsigned VBits = N->getValueType(0).getSizeInBits();
3579   unsigned ElSize = VBits / VL;
3580   bool Result = (Index * ElSize) % 128 == 0;
3581
3582   return Result;
3583 }
3584
3585 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3586 /// operand specifies a subvector insert that is suitable for input to
3587 /// VINSERTF128.
3588 bool X86::isVINSERTF128Index(SDNode *N) {
3589   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3590     return false;
3591
3592   // The index should be aligned on a 128-bit boundary.
3593   uint64_t Index =
3594     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3595
3596   unsigned VL = N->getValueType(0).getVectorNumElements();
3597   unsigned VBits = N->getValueType(0).getSizeInBits();
3598   unsigned ElSize = VBits / VL;
3599   bool Result = (Index * ElSize) % 128 == 0;
3600
3601   return Result;
3602 }
3603
3604 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3605 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3606 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3607   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3608   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3609
3610   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3611   unsigned Mask = 0;
3612   for (int i = 0; i < NumOperands; ++i) {
3613     int Val = SVOp->getMaskElt(NumOperands-i-1);
3614     if (Val < 0) Val = 0;
3615     if (Val >= NumOperands) Val -= NumOperands;
3616     Mask |= Val;
3617     if (i != NumOperands - 1)
3618       Mask <<= Shift;
3619   }
3620   return Mask;
3621 }
3622
3623 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3624 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3625 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3626   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3627   unsigned Mask = 0;
3628   // 8 nodes, but we only care about the last 4.
3629   for (unsigned i = 7; i >= 4; --i) {
3630     int Val = SVOp->getMaskElt(i);
3631     if (Val >= 0)
3632       Mask |= (Val - 4);
3633     if (i != 4)
3634       Mask <<= 2;
3635   }
3636   return Mask;
3637 }
3638
3639 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3640 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3641 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3642   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3643   unsigned Mask = 0;
3644   // 8 nodes, but we only care about the first 4.
3645   for (int i = 3; i >= 0; --i) {
3646     int Val = SVOp->getMaskElt(i);
3647     if (Val >= 0)
3648       Mask |= Val;
3649     if (i != 0)
3650       Mask <<= 2;
3651   }
3652   return Mask;
3653 }
3654
3655 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3656 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3657 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3658   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3659   EVT VVT = N->getValueType(0);
3660   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3661   int Val = 0;
3662
3663   unsigned i, e;
3664   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3665     Val = SVOp->getMaskElt(i);
3666     if (Val >= 0)
3667       break;
3668   }
3669   return (Val - i) * EltSize;
3670 }
3671
3672 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3673 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3674 /// instructions.
3675 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3676   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3677     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3678
3679   uint64_t Index =
3680     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3681
3682   EVT VecVT = N->getOperand(0).getValueType();
3683   EVT ElVT = VecVT.getVectorElementType();
3684
3685   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3686   return Index / NumElemsPerChunk;
3687 }
3688
3689 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3690 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3691 /// instructions.
3692 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3693   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3694     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3695
3696   uint64_t Index =
3697     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3698
3699   EVT VecVT = N->getValueType(0);
3700   EVT ElVT = VecVT.getVectorElementType();
3701
3702   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3703   return Index / NumElemsPerChunk;
3704 }
3705
3706 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3707 /// constant +0.0.
3708 bool X86::isZeroNode(SDValue Elt) {
3709   return ((isa<ConstantSDNode>(Elt) &&
3710            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3711           (isa<ConstantFPSDNode>(Elt) &&
3712            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3713 }
3714
3715 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3716 /// their permute mask.
3717 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3718                                     SelectionDAG &DAG) {
3719   EVT VT = SVOp->getValueType(0);
3720   unsigned NumElems = VT.getVectorNumElements();
3721   SmallVector<int, 8> MaskVec;
3722
3723   for (unsigned i = 0; i != NumElems; ++i) {
3724     int idx = SVOp->getMaskElt(i);
3725     if (idx < 0)
3726       MaskVec.push_back(idx);
3727     else if (idx < (int)NumElems)
3728       MaskVec.push_back(idx + NumElems);
3729     else
3730       MaskVec.push_back(idx - NumElems);
3731   }
3732   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3733                               SVOp->getOperand(0), &MaskVec[0]);
3734 }
3735
3736 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3737 /// the two vector operands have swapped position.
3738 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3739   unsigned NumElems = VT.getVectorNumElements();
3740   for (unsigned i = 0; i != NumElems; ++i) {
3741     int idx = Mask[i];
3742     if (idx < 0)
3743       continue;
3744     else if (idx < (int)NumElems)
3745       Mask[i] = idx + NumElems;
3746     else
3747       Mask[i] = idx - NumElems;
3748   }
3749 }
3750
3751 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3752 /// match movhlps. The lower half elements should come from upper half of
3753 /// V1 (and in order), and the upper half elements should come from the upper
3754 /// half of V2 (and in order).
3755 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3756   if (Op->getValueType(0).getVectorNumElements() != 4)
3757     return false;
3758   for (unsigned i = 0, e = 2; i != e; ++i)
3759     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3760       return false;
3761   for (unsigned i = 2; i != 4; ++i)
3762     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3763       return false;
3764   return true;
3765 }
3766
3767 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3768 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3769 /// required.
3770 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3771   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3772     return false;
3773   N = N->getOperand(0).getNode();
3774   if (!ISD::isNON_EXTLoad(N))
3775     return false;
3776   if (LD)
3777     *LD = cast<LoadSDNode>(N);
3778   return true;
3779 }
3780
3781 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3782 /// match movlp{s|d}. The lower half elements should come from lower half of
3783 /// V1 (and in order), and the upper half elements should come from the upper
3784 /// half of V2 (and in order). And since V1 will become the source of the
3785 /// MOVLP, it must be either a vector load or a scalar load to vector.
3786 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3787                                ShuffleVectorSDNode *Op) {
3788   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3789     return false;
3790   // Is V2 is a vector load, don't do this transformation. We will try to use
3791   // load folding shufps op.
3792   if (ISD::isNON_EXTLoad(V2))
3793     return false;
3794
3795   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3796
3797   if (NumElems != 2 && NumElems != 4)
3798     return false;
3799   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3800     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3801       return false;
3802   for (unsigned i = NumElems/2; i != NumElems; ++i)
3803     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3804       return false;
3805   return true;
3806 }
3807
3808 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3809 /// all the same.
3810 static bool isSplatVector(SDNode *N) {
3811   if (N->getOpcode() != ISD::BUILD_VECTOR)
3812     return false;
3813
3814   SDValue SplatValue = N->getOperand(0);
3815   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3816     if (N->getOperand(i) != SplatValue)
3817       return false;
3818   return true;
3819 }
3820
3821 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3822 /// to an zero vector.
3823 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3824 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3825   SDValue V1 = N->getOperand(0);
3826   SDValue V2 = N->getOperand(1);
3827   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3828   for (unsigned i = 0; i != NumElems; ++i) {
3829     int Idx = N->getMaskElt(i);
3830     if (Idx >= (int)NumElems) {
3831       unsigned Opc = V2.getOpcode();
3832       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3833         continue;
3834       if (Opc != ISD::BUILD_VECTOR ||
3835           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3836         return false;
3837     } else if (Idx >= 0) {
3838       unsigned Opc = V1.getOpcode();
3839       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3840         continue;
3841       if (Opc != ISD::BUILD_VECTOR ||
3842           !X86::isZeroNode(V1.getOperand(Idx)))
3843         return false;
3844     }
3845   }
3846   return true;
3847 }
3848
3849 /// getZeroVector - Returns a vector of specified type with all zero elements.
3850 ///
3851 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3852                              DebugLoc dl) {
3853   assert(VT.isVector() && "Expected a vector type");
3854
3855   // Always build SSE zero vectors as <4 x i32> bitcasted
3856   // to their dest type. This ensures they get CSE'd.
3857   SDValue Vec;
3858   if (VT.getSizeInBits() == 128) {  // SSE
3859     if (HasSSE2) {  // SSE2
3860       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3861       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3862     } else { // SSE1
3863       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3864       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3865     }
3866   } else if (VT.getSizeInBits() == 256) { // AVX
3867     // 256-bit logic and arithmetic instructions in AVX are
3868     // all floating-point, no support for integer ops. Default
3869     // to emitting fp zeroed vectors then.
3870     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3871     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3872     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3873   }
3874   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3875 }
3876
3877 /// getOnesVector - Returns a vector of specified type with all bits set.
3878 /// Always build ones vectors as <4 x i32> or <8 x i32> bitcasted to
3879 /// their original type, ensuring they get CSE'd.
3880 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3881   assert(VT.isVector() && "Expected a vector type");
3882   assert((VT.is128BitVector() || VT.is256BitVector())
3883          && "Expected a 128-bit or 256-bit vector type");
3884
3885   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3886
3887   SDValue Vec;
3888   if (VT.is256BitVector()) {
3889     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3890     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
3891   } else
3892     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3893   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3894 }
3895
3896 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3897 /// that point to V2 points to its first element.
3898 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3899   EVT VT = SVOp->getValueType(0);
3900   unsigned NumElems = VT.getVectorNumElements();
3901
3902   bool Changed = false;
3903   SmallVector<int, 8> MaskVec;
3904   SVOp->getMask(MaskVec);
3905
3906   for (unsigned i = 0; i != NumElems; ++i) {
3907     if (MaskVec[i] > (int)NumElems) {
3908       MaskVec[i] = NumElems;
3909       Changed = true;
3910     }
3911   }
3912   if (Changed)
3913     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3914                                 SVOp->getOperand(1), &MaskVec[0]);
3915   return SDValue(SVOp, 0);
3916 }
3917
3918 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3919 /// operation of specified width.
3920 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3921                        SDValue V2) {
3922   unsigned NumElems = VT.getVectorNumElements();
3923   SmallVector<int, 8> Mask;
3924   Mask.push_back(NumElems);
3925   for (unsigned i = 1; i != NumElems; ++i)
3926     Mask.push_back(i);
3927   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3928 }
3929
3930 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3931 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3932                           SDValue V2) {
3933   unsigned NumElems = VT.getVectorNumElements();
3934   SmallVector<int, 8> Mask;
3935   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3936     Mask.push_back(i);
3937     Mask.push_back(i + NumElems);
3938   }
3939   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3940 }
3941
3942 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
3943 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3944                           SDValue V2) {
3945   unsigned NumElems = VT.getVectorNumElements();
3946   unsigned Half = NumElems/2;
3947   SmallVector<int, 8> Mask;
3948   for (unsigned i = 0; i != Half; ++i) {
3949     Mask.push_back(i + Half);
3950     Mask.push_back(i + NumElems + Half);
3951   }
3952   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3953 }
3954
3955 // PromoteSplatv8v16 - All i16 and i8 vector types can't be used directly by
3956 // a generic shuffle instruction because the target has no such instructions.
3957 // Generate shuffles which repeat i16 and i8 several times until they can be
3958 // represented by v4f32 and then be manipulated by target suported shuffles.
3959 static SDValue PromoteSplatv8v16(SDValue V, SelectionDAG &DAG, int &EltNo) {
3960   EVT VT = V.getValueType();
3961   int NumElems = VT.getVectorNumElements();
3962   DebugLoc dl = V.getDebugLoc();
3963
3964   while (NumElems > 4) {
3965     if (EltNo < NumElems/2) {
3966       V = getUnpackl(DAG, dl, VT, V, V);
3967     } else {
3968       V = getUnpackh(DAG, dl, VT, V, V);
3969       EltNo -= NumElems/2;
3970     }
3971     NumElems >>= 1;
3972   }
3973   return V;
3974 }
3975
3976 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
3977 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
3978   EVT VT = V.getValueType();
3979   DebugLoc dl = V.getDebugLoc();
3980   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
3981          && "Vector size not supported");
3982
3983   bool Is128 = VT.getSizeInBits() == 128;
3984   EVT NVT = Is128 ? MVT::v4f32 : MVT::v8f32;
3985   V = DAG.getNode(ISD::BITCAST, dl, NVT, V);
3986
3987   if (Is128) {
3988     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3989     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3990   } else {
3991     // The second half of indicies refer to the higher part, which is a
3992     // duplication of the lower one. This makes this shuffle a perfect match
3993     // for the VPERM instruction.
3994     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
3995                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
3996     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3997   }
3998
3999   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4000 }
4001
4002 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32 and
4003 /// v8i32, v16i16 or v32i8 to v8f32.
4004 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4005   EVT SrcVT = SV->getValueType(0);
4006   SDValue V1 = SV->getOperand(0);
4007   DebugLoc dl = SV->getDebugLoc();
4008
4009   int EltNo = SV->getSplatIndex();
4010   int NumElems = SrcVT.getVectorNumElements();
4011   unsigned Size = SrcVT.getSizeInBits();
4012
4013   // Extract the 128-bit part containing the splat element and update
4014   // the splat element index when it refers to the higher register.
4015   if (Size == 256) {
4016     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4017     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4018     if (Idx > 0)
4019       EltNo -= NumElems/2;
4020   }
4021
4022   // Make this 128-bit vector duplicate i8 and i16 elements
4023   if (NumElems > 4)
4024     V1 = PromoteSplatv8v16(V1, DAG, EltNo);
4025
4026   // Recreate the 256-bit vector and place the same 128-bit vector
4027   // into the low and high part. This is necessary because we want
4028   // to use VPERM to shuffle the v8f32 vector, and VPERM only shuffles
4029   // inside each separate v4f32 lane.
4030   if (Size == 256) {
4031     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4032                          DAG.getConstant(0, MVT::i32), DAG, dl);
4033     V1 = Insert128BitVector(InsV, V1,
4034                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4035   }
4036
4037   return getLegalSplat(DAG, V1, EltNo);
4038 }
4039
4040 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4041 /// vector of zero or undef vector.  This produces a shuffle where the low
4042 /// element of V2 is swizzled into the zero/undef vector, landing at element
4043 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4044 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4045                                              bool isZero, bool HasSSE2,
4046                                              SelectionDAG &DAG) {
4047   EVT VT = V2.getValueType();
4048   SDValue V1 = isZero
4049     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4050   unsigned NumElems = VT.getVectorNumElements();
4051   SmallVector<int, 16> MaskVec;
4052   for (unsigned i = 0; i != NumElems; ++i)
4053     // If this is the insertion idx, put the low elt of V2 here.
4054     MaskVec.push_back(i == Idx ? NumElems : i);
4055   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4056 }
4057
4058 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4059 /// element of the result of the vector shuffle.
4060 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4061                                    unsigned Depth) {
4062   if (Depth == 6)
4063     return SDValue();  // Limit search depth.
4064
4065   SDValue V = SDValue(N, 0);
4066   EVT VT = V.getValueType();
4067   unsigned Opcode = V.getOpcode();
4068
4069   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4070   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4071     Index = SV->getMaskElt(Index);
4072
4073     if (Index < 0)
4074       return DAG.getUNDEF(VT.getVectorElementType());
4075
4076     int NumElems = VT.getVectorNumElements();
4077     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4078     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4079   }
4080
4081   // Recurse into target specific vector shuffles to find scalars.
4082   if (isTargetShuffle(Opcode)) {
4083     int NumElems = VT.getVectorNumElements();
4084     SmallVector<unsigned, 16> ShuffleMask;
4085     SDValue ImmN;
4086
4087     switch(Opcode) {
4088     case X86ISD::SHUFPS:
4089     case X86ISD::SHUFPD:
4090       ImmN = N->getOperand(N->getNumOperands()-1);
4091       DecodeSHUFPSMask(NumElems,
4092                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4093                        ShuffleMask);
4094       break;
4095     case X86ISD::PUNPCKHBW:
4096     case X86ISD::PUNPCKHWD:
4097     case X86ISD::PUNPCKHDQ:
4098     case X86ISD::PUNPCKHQDQ:
4099       DecodePUNPCKHMask(NumElems, ShuffleMask);
4100       break;
4101     case X86ISD::UNPCKHPS:
4102     case X86ISD::UNPCKHPD:
4103       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4104       break;
4105     case X86ISD::PUNPCKLBW:
4106     case X86ISD::PUNPCKLWD:
4107     case X86ISD::PUNPCKLDQ:
4108     case X86ISD::PUNPCKLQDQ:
4109       DecodePUNPCKLMask(VT, ShuffleMask);
4110       break;
4111     case X86ISD::UNPCKLPS:
4112     case X86ISD::UNPCKLPD:
4113     case X86ISD::VUNPCKLPS:
4114     case X86ISD::VUNPCKLPD:
4115     case X86ISD::VUNPCKLPSY:
4116     case X86ISD::VUNPCKLPDY:
4117       DecodeUNPCKLPMask(VT, ShuffleMask);
4118       break;
4119     case X86ISD::MOVHLPS:
4120       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4121       break;
4122     case X86ISD::MOVLHPS:
4123       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4124       break;
4125     case X86ISD::PSHUFD:
4126       ImmN = N->getOperand(N->getNumOperands()-1);
4127       DecodePSHUFMask(NumElems,
4128                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4129                       ShuffleMask);
4130       break;
4131     case X86ISD::PSHUFHW:
4132       ImmN = N->getOperand(N->getNumOperands()-1);
4133       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4134                         ShuffleMask);
4135       break;
4136     case X86ISD::PSHUFLW:
4137       ImmN = N->getOperand(N->getNumOperands()-1);
4138       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4139                         ShuffleMask);
4140       break;
4141     case X86ISD::MOVSS:
4142     case X86ISD::MOVSD: {
4143       // The index 0 always comes from the first element of the second source,
4144       // this is why MOVSS and MOVSD are used in the first place. The other
4145       // elements come from the other positions of the first source vector.
4146       unsigned OpNum = (Index == 0) ? 1 : 0;
4147       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4148                                  Depth+1);
4149     }
4150     case X86ISD::VPERMIL:
4151       ImmN = N->getOperand(N->getNumOperands()-1);
4152       DecodeVPERMILMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4153                         ShuffleMask);
4154     default:
4155       assert("not implemented for target shuffle node");
4156       return SDValue();
4157     }
4158
4159     Index = ShuffleMask[Index];
4160     if (Index < 0)
4161       return DAG.getUNDEF(VT.getVectorElementType());
4162
4163     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4164     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4165                                Depth+1);
4166   }
4167
4168   // Actual nodes that may contain scalar elements
4169   if (Opcode == ISD::BITCAST) {
4170     V = V.getOperand(0);
4171     EVT SrcVT = V.getValueType();
4172     unsigned NumElems = VT.getVectorNumElements();
4173
4174     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4175       return SDValue();
4176   }
4177
4178   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4179     return (Index == 0) ? V.getOperand(0)
4180                           : DAG.getUNDEF(VT.getVectorElementType());
4181
4182   if (V.getOpcode() == ISD::BUILD_VECTOR)
4183     return V.getOperand(Index);
4184
4185   return SDValue();
4186 }
4187
4188 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4189 /// shuffle operation which come from a consecutively from a zero. The
4190 /// search can start in two different directions, from left or right.
4191 static
4192 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4193                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4194   int i = 0;
4195
4196   while (i < NumElems) {
4197     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4198     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4199     if (!(Elt.getNode() &&
4200          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4201       break;
4202     ++i;
4203   }
4204
4205   return i;
4206 }
4207
4208 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4209 /// MaskE correspond consecutively to elements from one of the vector operands,
4210 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4211 static
4212 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4213                               int OpIdx, int NumElems, unsigned &OpNum) {
4214   bool SeenV1 = false;
4215   bool SeenV2 = false;
4216
4217   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4218     int Idx = SVOp->getMaskElt(i);
4219     // Ignore undef indicies
4220     if (Idx < 0)
4221       continue;
4222
4223     if (Idx < NumElems)
4224       SeenV1 = true;
4225     else
4226       SeenV2 = true;
4227
4228     // Only accept consecutive elements from the same vector
4229     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4230       return false;
4231   }
4232
4233   OpNum = SeenV1 ? 0 : 1;
4234   return true;
4235 }
4236
4237 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4238 /// logical left shift of a vector.
4239 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4240                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4241   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4242   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4243               false /* check zeros from right */, DAG);
4244   unsigned OpSrc;
4245
4246   if (!NumZeros)
4247     return false;
4248
4249   // Considering the elements in the mask that are not consecutive zeros,
4250   // check if they consecutively come from only one of the source vectors.
4251   //
4252   //               V1 = {X, A, B, C}     0
4253   //                         \  \  \    /
4254   //   vector_shuffle V1, V2 <1, 2, 3, X>
4255   //
4256   if (!isShuffleMaskConsecutive(SVOp,
4257             0,                   // Mask Start Index
4258             NumElems-NumZeros-1, // Mask End Index
4259             NumZeros,            // Where to start looking in the src vector
4260             NumElems,            // Number of elements in vector
4261             OpSrc))              // Which source operand ?
4262     return false;
4263
4264   isLeft = false;
4265   ShAmt = NumZeros;
4266   ShVal = SVOp->getOperand(OpSrc);
4267   return true;
4268 }
4269
4270 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4271 /// logical left shift of a vector.
4272 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4273                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4274   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4275   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4276               true /* check zeros from left */, DAG);
4277   unsigned OpSrc;
4278
4279   if (!NumZeros)
4280     return false;
4281
4282   // Considering the elements in the mask that are not consecutive zeros,
4283   // check if they consecutively come from only one of the source vectors.
4284   //
4285   //                           0    { A, B, X, X } = V2
4286   //                          / \    /  /
4287   //   vector_shuffle V1, V2 <X, X, 4, 5>
4288   //
4289   if (!isShuffleMaskConsecutive(SVOp,
4290             NumZeros,     // Mask Start Index
4291             NumElems-1,   // Mask End Index
4292             0,            // Where to start looking in the src vector
4293             NumElems,     // Number of elements in vector
4294             OpSrc))       // Which source operand ?
4295     return false;
4296
4297   isLeft = true;
4298   ShAmt = NumZeros;
4299   ShVal = SVOp->getOperand(OpSrc);
4300   return true;
4301 }
4302
4303 /// isVectorShift - Returns true if the shuffle can be implemented as a
4304 /// logical left or right shift of a vector.
4305 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4306                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4307   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4308       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4309     return true;
4310
4311   return false;
4312 }
4313
4314 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4315 ///
4316 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4317                                        unsigned NumNonZero, unsigned NumZero,
4318                                        SelectionDAG &DAG,
4319                                        const TargetLowering &TLI) {
4320   if (NumNonZero > 8)
4321     return SDValue();
4322
4323   DebugLoc dl = Op.getDebugLoc();
4324   SDValue V(0, 0);
4325   bool First = true;
4326   for (unsigned i = 0; i < 16; ++i) {
4327     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4328     if (ThisIsNonZero && First) {
4329       if (NumZero)
4330         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4331       else
4332         V = DAG.getUNDEF(MVT::v8i16);
4333       First = false;
4334     }
4335
4336     if ((i & 1) != 0) {
4337       SDValue ThisElt(0, 0), LastElt(0, 0);
4338       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4339       if (LastIsNonZero) {
4340         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4341                               MVT::i16, Op.getOperand(i-1));
4342       }
4343       if (ThisIsNonZero) {
4344         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4345         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4346                               ThisElt, DAG.getConstant(8, MVT::i8));
4347         if (LastIsNonZero)
4348           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4349       } else
4350         ThisElt = LastElt;
4351
4352       if (ThisElt.getNode())
4353         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4354                         DAG.getIntPtrConstant(i/2));
4355     }
4356   }
4357
4358   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4359 }
4360
4361 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4362 ///
4363 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4364                                      unsigned NumNonZero, unsigned NumZero,
4365                                      SelectionDAG &DAG,
4366                                      const TargetLowering &TLI) {
4367   if (NumNonZero > 4)
4368     return SDValue();
4369
4370   DebugLoc dl = Op.getDebugLoc();
4371   SDValue V(0, 0);
4372   bool First = true;
4373   for (unsigned i = 0; i < 8; ++i) {
4374     bool isNonZero = (NonZeros & (1 << i)) != 0;
4375     if (isNonZero) {
4376       if (First) {
4377         if (NumZero)
4378           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4379         else
4380           V = DAG.getUNDEF(MVT::v8i16);
4381         First = false;
4382       }
4383       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4384                       MVT::v8i16, V, Op.getOperand(i),
4385                       DAG.getIntPtrConstant(i));
4386     }
4387   }
4388
4389   return V;
4390 }
4391
4392 /// getVShift - Return a vector logical shift node.
4393 ///
4394 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4395                          unsigned NumBits, SelectionDAG &DAG,
4396                          const TargetLowering &TLI, DebugLoc dl) {
4397   EVT ShVT = MVT::v2i64;
4398   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4399   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4400   return DAG.getNode(ISD::BITCAST, dl, VT,
4401                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4402                              DAG.getConstant(NumBits,
4403                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4404 }
4405
4406 SDValue
4407 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4408                                           SelectionDAG &DAG) const {
4409
4410   // Check if the scalar load can be widened into a vector load. And if
4411   // the address is "base + cst" see if the cst can be "absorbed" into
4412   // the shuffle mask.
4413   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4414     SDValue Ptr = LD->getBasePtr();
4415     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4416       return SDValue();
4417     EVT PVT = LD->getValueType(0);
4418     if (PVT != MVT::i32 && PVT != MVT::f32)
4419       return SDValue();
4420
4421     int FI = -1;
4422     int64_t Offset = 0;
4423     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4424       FI = FINode->getIndex();
4425       Offset = 0;
4426     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4427                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4428       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4429       Offset = Ptr.getConstantOperandVal(1);
4430       Ptr = Ptr.getOperand(0);
4431     } else {
4432       return SDValue();
4433     }
4434
4435     SDValue Chain = LD->getChain();
4436     // Make sure the stack object alignment is at least 16.
4437     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4438     if (DAG.InferPtrAlignment(Ptr) < 16) {
4439       if (MFI->isFixedObjectIndex(FI)) {
4440         // Can't change the alignment. FIXME: It's possible to compute
4441         // the exact stack offset and reference FI + adjust offset instead.
4442         // If someone *really* cares about this. That's the way to implement it.
4443         return SDValue();
4444       } else {
4445         MFI->setObjectAlignment(FI, 16);
4446       }
4447     }
4448
4449     // (Offset % 16) must be multiple of 4. Then address is then
4450     // Ptr + (Offset & ~15).
4451     if (Offset < 0)
4452       return SDValue();
4453     if ((Offset % 16) & 3)
4454       return SDValue();
4455     int64_t StartOffset = Offset & ~15;
4456     if (StartOffset)
4457       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4458                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4459
4460     int EltNo = (Offset - StartOffset) >> 2;
4461     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4462     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4463     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4464                              LD->getPointerInfo().getWithOffset(StartOffset),
4465                              false, false, 0);
4466     // Canonicalize it to a v4i32 shuffle.
4467     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4468     return DAG.getNode(ISD::BITCAST, dl, VT,
4469                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4470                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4471   }
4472
4473   return SDValue();
4474 }
4475
4476 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4477 /// vector of type 'VT', see if the elements can be replaced by a single large
4478 /// load which has the same value as a build_vector whose operands are 'elts'.
4479 ///
4480 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4481 ///
4482 /// FIXME: we'd also like to handle the case where the last elements are zero
4483 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4484 /// There's even a handy isZeroNode for that purpose.
4485 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4486                                         DebugLoc &DL, SelectionDAG &DAG) {
4487   EVT EltVT = VT.getVectorElementType();
4488   unsigned NumElems = Elts.size();
4489
4490   LoadSDNode *LDBase = NULL;
4491   unsigned LastLoadedElt = -1U;
4492
4493   // For each element in the initializer, see if we've found a load or an undef.
4494   // If we don't find an initial load element, or later load elements are
4495   // non-consecutive, bail out.
4496   for (unsigned i = 0; i < NumElems; ++i) {
4497     SDValue Elt = Elts[i];
4498
4499     if (!Elt.getNode() ||
4500         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4501       return SDValue();
4502     if (!LDBase) {
4503       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4504         return SDValue();
4505       LDBase = cast<LoadSDNode>(Elt.getNode());
4506       LastLoadedElt = i;
4507       continue;
4508     }
4509     if (Elt.getOpcode() == ISD::UNDEF)
4510       continue;
4511
4512     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4513     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4514       return SDValue();
4515     LastLoadedElt = i;
4516   }
4517
4518   // If we have found an entire vector of loads and undefs, then return a large
4519   // load of the entire vector width starting at the base pointer.  If we found
4520   // consecutive loads for the low half, generate a vzext_load node.
4521   if (LastLoadedElt == NumElems - 1) {
4522     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4523       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4524                          LDBase->getPointerInfo(),
4525                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4526     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4527                        LDBase->getPointerInfo(),
4528                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4529                        LDBase->getAlignment());
4530   } else if (NumElems == 4 && LastLoadedElt == 1) {
4531     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4532     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4533     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4534                                               Ops, 2, MVT::i32,
4535                                               LDBase->getMemOperand());
4536     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4537   }
4538   return SDValue();
4539 }
4540
4541 SDValue
4542 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4543   DebugLoc dl = Op.getDebugLoc();
4544
4545   EVT VT = Op.getValueType();
4546   EVT ExtVT = VT.getVectorElementType();
4547
4548   unsigned NumElems = Op.getNumOperands();
4549
4550   // For AVX-length vectors, build the individual 128-bit pieces and
4551   // use shuffles to put them in place.
4552   if (VT.getSizeInBits() > 256 &&
4553       Subtarget->hasAVX() &&
4554       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4555     SmallVector<SDValue, 8> V;
4556     V.resize(NumElems);
4557     for (unsigned i = 0; i < NumElems; ++i) {
4558       V[i] = Op.getOperand(i);
4559     }
4560
4561     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4562
4563     // Build the lower subvector.
4564     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4565     // Build the upper subvector.
4566     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4567                                 NumElems/2);
4568
4569     return ConcatVectors(Lower, Upper, DAG);
4570   }
4571
4572   // All zero's:
4573   //  - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4574   // All one's:
4575   //  - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4576   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4577       ISD::isBuildVectorAllOnes(Op.getNode())) {
4578     // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4579     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4580     // eliminated on x86-32 hosts.
4581     if (Op.getValueType() == MVT::v4i32 ||
4582         Op.getValueType() == MVT::v8i32)
4583       return Op;
4584
4585     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4586       return getOnesVector(Op.getValueType(), DAG, dl);
4587     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4588   }
4589
4590   unsigned EVTBits = ExtVT.getSizeInBits();
4591
4592   unsigned NumZero  = 0;
4593   unsigned NumNonZero = 0;
4594   unsigned NonZeros = 0;
4595   bool IsAllConstants = true;
4596   SmallSet<SDValue, 8> Values;
4597   for (unsigned i = 0; i < NumElems; ++i) {
4598     SDValue Elt = Op.getOperand(i);
4599     if (Elt.getOpcode() == ISD::UNDEF)
4600       continue;
4601     Values.insert(Elt);
4602     if (Elt.getOpcode() != ISD::Constant &&
4603         Elt.getOpcode() != ISD::ConstantFP)
4604       IsAllConstants = false;
4605     if (X86::isZeroNode(Elt))
4606       NumZero++;
4607     else {
4608       NonZeros |= (1 << i);
4609       NumNonZero++;
4610     }
4611   }
4612
4613   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4614   if (NumNonZero == 0)
4615     return DAG.getUNDEF(VT);
4616
4617   // Special case for single non-zero, non-undef, element.
4618   if (NumNonZero == 1) {
4619     unsigned Idx = CountTrailingZeros_32(NonZeros);
4620     SDValue Item = Op.getOperand(Idx);
4621
4622     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4623     // the value are obviously zero, truncate the value to i32 and do the
4624     // insertion that way.  Only do this if the value is non-constant or if the
4625     // value is a constant being inserted into element 0.  It is cheaper to do
4626     // a constant pool load than it is to do a movd + shuffle.
4627     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4628         (!IsAllConstants || Idx == 0)) {
4629       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4630         // Handle SSE only.
4631         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4632         EVT VecVT = MVT::v4i32;
4633         unsigned VecElts = 4;
4634
4635         // Truncate the value (which may itself be a constant) to i32, and
4636         // convert it to a vector with movd (S2V+shuffle to zero extend).
4637         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4638         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4639         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4640                                            Subtarget->hasSSE2(), DAG);
4641
4642         // Now we have our 32-bit value zero extended in the low element of
4643         // a vector.  If Idx != 0, swizzle it into place.
4644         if (Idx != 0) {
4645           SmallVector<int, 4> Mask;
4646           Mask.push_back(Idx);
4647           for (unsigned i = 1; i != VecElts; ++i)
4648             Mask.push_back(i);
4649           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4650                                       DAG.getUNDEF(Item.getValueType()),
4651                                       &Mask[0]);
4652         }
4653         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4654       }
4655     }
4656
4657     // If we have a constant or non-constant insertion into the low element of
4658     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4659     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4660     // depending on what the source datatype is.
4661     if (Idx == 0) {
4662       if (NumZero == 0) {
4663         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4664       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4665           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4666         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4667         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4668         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4669                                            DAG);
4670       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4671         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4672         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4673         EVT MiddleVT = MVT::v4i32;
4674         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4675         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4676                                            Subtarget->hasSSE2(), DAG);
4677         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4678       }
4679     }
4680
4681     // Is it a vector logical left shift?
4682     if (NumElems == 2 && Idx == 1 &&
4683         X86::isZeroNode(Op.getOperand(0)) &&
4684         !X86::isZeroNode(Op.getOperand(1))) {
4685       unsigned NumBits = VT.getSizeInBits();
4686       return getVShift(true, VT,
4687                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4688                                    VT, Op.getOperand(1)),
4689                        NumBits/2, DAG, *this, dl);
4690     }
4691
4692     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4693       return SDValue();
4694
4695     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4696     // is a non-constant being inserted into an element other than the low one,
4697     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4698     // movd/movss) to move this into the low element, then shuffle it into
4699     // place.
4700     if (EVTBits == 32) {
4701       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4702
4703       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4704       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4705                                          Subtarget->hasSSE2(), DAG);
4706       SmallVector<int, 8> MaskVec;
4707       for (unsigned i = 0; i < NumElems; i++)
4708         MaskVec.push_back(i == Idx ? 0 : 1);
4709       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4710     }
4711   }
4712
4713   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4714   if (Values.size() == 1) {
4715     if (EVTBits == 32) {
4716       // Instead of a shuffle like this:
4717       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4718       // Check if it's possible to issue this instead.
4719       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4720       unsigned Idx = CountTrailingZeros_32(NonZeros);
4721       SDValue Item = Op.getOperand(Idx);
4722       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4723         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4724     }
4725     return SDValue();
4726   }
4727
4728   // A vector full of immediates; various special cases are already
4729   // handled, so this is best done with a single constant-pool load.
4730   if (IsAllConstants)
4731     return SDValue();
4732
4733   // Let legalizer expand 2-wide build_vectors.
4734   if (EVTBits == 64) {
4735     if (NumNonZero == 1) {
4736       // One half is zero or undef.
4737       unsigned Idx = CountTrailingZeros_32(NonZeros);
4738       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4739                                  Op.getOperand(Idx));
4740       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4741                                          Subtarget->hasSSE2(), DAG);
4742     }
4743     return SDValue();
4744   }
4745
4746   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4747   if (EVTBits == 8 && NumElems == 16) {
4748     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4749                                         *this);
4750     if (V.getNode()) return V;
4751   }
4752
4753   if (EVTBits == 16 && NumElems == 8) {
4754     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4755                                       *this);
4756     if (V.getNode()) return V;
4757   }
4758
4759   // If element VT is == 32 bits, turn it into a number of shuffles.
4760   SmallVector<SDValue, 8> V;
4761   V.resize(NumElems);
4762   if (NumElems == 4 && NumZero > 0) {
4763     for (unsigned i = 0; i < 4; ++i) {
4764       bool isZero = !(NonZeros & (1 << i));
4765       if (isZero)
4766         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4767       else
4768         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4769     }
4770
4771     for (unsigned i = 0; i < 2; ++i) {
4772       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4773         default: break;
4774         case 0:
4775           V[i] = V[i*2];  // Must be a zero vector.
4776           break;
4777         case 1:
4778           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4779           break;
4780         case 2:
4781           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4782           break;
4783         case 3:
4784           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4785           break;
4786       }
4787     }
4788
4789     SmallVector<int, 8> MaskVec;
4790     bool Reverse = (NonZeros & 0x3) == 2;
4791     for (unsigned i = 0; i < 2; ++i)
4792       MaskVec.push_back(Reverse ? 1-i : i);
4793     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4794     for (unsigned i = 0; i < 2; ++i)
4795       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4796     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4797   }
4798
4799   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4800     // Check for a build vector of consecutive loads.
4801     for (unsigned i = 0; i < NumElems; ++i)
4802       V[i] = Op.getOperand(i);
4803
4804     // Check for elements which are consecutive loads.
4805     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4806     if (LD.getNode())
4807       return LD;
4808
4809     // For SSE 4.1, use insertps to put the high elements into the low element.
4810     if (getSubtarget()->hasSSE41()) {
4811       SDValue Result;
4812       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4813         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4814       else
4815         Result = DAG.getUNDEF(VT);
4816
4817       for (unsigned i = 1; i < NumElems; ++i) {
4818         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4819         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4820                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4821       }
4822       return Result;
4823     }
4824
4825     // Otherwise, expand into a number of unpckl*, start by extending each of
4826     // our (non-undef) elements to the full vector width with the element in the
4827     // bottom slot of the vector (which generates no code for SSE).
4828     for (unsigned i = 0; i < NumElems; ++i) {
4829       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4830         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4831       else
4832         V[i] = DAG.getUNDEF(VT);
4833     }
4834
4835     // Next, we iteratively mix elements, e.g. for v4f32:
4836     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4837     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4838     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4839     unsigned EltStride = NumElems >> 1;
4840     while (EltStride != 0) {
4841       for (unsigned i = 0; i < EltStride; ++i) {
4842         // If V[i+EltStride] is undef and this is the first round of mixing,
4843         // then it is safe to just drop this shuffle: V[i] is already in the
4844         // right place, the one element (since it's the first round) being
4845         // inserted as undef can be dropped.  This isn't safe for successive
4846         // rounds because they will permute elements within both vectors.
4847         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4848             EltStride == NumElems/2)
4849           continue;
4850
4851         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4852       }
4853       EltStride >>= 1;
4854     }
4855     return V[0];
4856   }
4857   return SDValue();
4858 }
4859
4860 SDValue
4861 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4862   // We support concatenate two MMX registers and place them in a MMX
4863   // register.  This is better than doing a stack convert.
4864   DebugLoc dl = Op.getDebugLoc();
4865   EVT ResVT = Op.getValueType();
4866   assert(Op.getNumOperands() == 2);
4867   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4868          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4869   int Mask[2];
4870   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4871   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4872   InVec = Op.getOperand(1);
4873   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4874     unsigned NumElts = ResVT.getVectorNumElements();
4875     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4876     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4877                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4878   } else {
4879     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4880     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4881     Mask[0] = 0; Mask[1] = 2;
4882     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4883   }
4884   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4885 }
4886
4887 // v8i16 shuffles - Prefer shuffles in the following order:
4888 // 1. [all]   pshuflw, pshufhw, optional move
4889 // 2. [ssse3] 1 x pshufb
4890 // 3. [ssse3] 2 x pshufb + 1 x por
4891 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4892 SDValue
4893 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4894                                             SelectionDAG &DAG) const {
4895   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4896   SDValue V1 = SVOp->getOperand(0);
4897   SDValue V2 = SVOp->getOperand(1);
4898   DebugLoc dl = SVOp->getDebugLoc();
4899   SmallVector<int, 8> MaskVals;
4900
4901   // Determine if more than 1 of the words in each of the low and high quadwords
4902   // of the result come from the same quadword of one of the two inputs.  Undef
4903   // mask values count as coming from any quadword, for better codegen.
4904   SmallVector<unsigned, 4> LoQuad(4);
4905   SmallVector<unsigned, 4> HiQuad(4);
4906   BitVector InputQuads(4);
4907   for (unsigned i = 0; i < 8; ++i) {
4908     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4909     int EltIdx = SVOp->getMaskElt(i);
4910     MaskVals.push_back(EltIdx);
4911     if (EltIdx < 0) {
4912       ++Quad[0];
4913       ++Quad[1];
4914       ++Quad[2];
4915       ++Quad[3];
4916       continue;
4917     }
4918     ++Quad[EltIdx / 4];
4919     InputQuads.set(EltIdx / 4);
4920   }
4921
4922   int BestLoQuad = -1;
4923   unsigned MaxQuad = 1;
4924   for (unsigned i = 0; i < 4; ++i) {
4925     if (LoQuad[i] > MaxQuad) {
4926       BestLoQuad = i;
4927       MaxQuad = LoQuad[i];
4928     }
4929   }
4930
4931   int BestHiQuad = -1;
4932   MaxQuad = 1;
4933   for (unsigned i = 0; i < 4; ++i) {
4934     if (HiQuad[i] > MaxQuad) {
4935       BestHiQuad = i;
4936       MaxQuad = HiQuad[i];
4937     }
4938   }
4939
4940   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4941   // of the two input vectors, shuffle them into one input vector so only a
4942   // single pshufb instruction is necessary. If There are more than 2 input
4943   // quads, disable the next transformation since it does not help SSSE3.
4944   bool V1Used = InputQuads[0] || InputQuads[1];
4945   bool V2Used = InputQuads[2] || InputQuads[3];
4946   if (Subtarget->hasSSSE3()) {
4947     if (InputQuads.count() == 2 && V1Used && V2Used) {
4948       BestLoQuad = InputQuads.find_first();
4949       BestHiQuad = InputQuads.find_next(BestLoQuad);
4950     }
4951     if (InputQuads.count() > 2) {
4952       BestLoQuad = -1;
4953       BestHiQuad = -1;
4954     }
4955   }
4956
4957   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4958   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4959   // words from all 4 input quadwords.
4960   SDValue NewV;
4961   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4962     SmallVector<int, 8> MaskV;
4963     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4964     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4965     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4966                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4967                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4968     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4969
4970     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4971     // source words for the shuffle, to aid later transformations.
4972     bool AllWordsInNewV = true;
4973     bool InOrder[2] = { true, true };
4974     for (unsigned i = 0; i != 8; ++i) {
4975       int idx = MaskVals[i];
4976       if (idx != (int)i)
4977         InOrder[i/4] = false;
4978       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4979         continue;
4980       AllWordsInNewV = false;
4981       break;
4982     }
4983
4984     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4985     if (AllWordsInNewV) {
4986       for (int i = 0; i != 8; ++i) {
4987         int idx = MaskVals[i];
4988         if (idx < 0)
4989           continue;
4990         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4991         if ((idx != i) && idx < 4)
4992           pshufhw = false;
4993         if ((idx != i) && idx > 3)
4994           pshuflw = false;
4995       }
4996       V1 = NewV;
4997       V2Used = false;
4998       BestLoQuad = 0;
4999       BestHiQuad = 1;
5000     }
5001
5002     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5003     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5004     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5005       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5006       unsigned TargetMask = 0;
5007       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5008                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5009       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5010                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5011       V1 = NewV.getOperand(0);
5012       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5013     }
5014   }
5015
5016   // If we have SSSE3, and all words of the result are from 1 input vector,
5017   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5018   // is present, fall back to case 4.
5019   if (Subtarget->hasSSSE3()) {
5020     SmallVector<SDValue,16> pshufbMask;
5021
5022     // If we have elements from both input vectors, set the high bit of the
5023     // shuffle mask element to zero out elements that come from V2 in the V1
5024     // mask, and elements that come from V1 in the V2 mask, so that the two
5025     // results can be OR'd together.
5026     bool TwoInputs = V1Used && V2Used;
5027     for (unsigned i = 0; i != 8; ++i) {
5028       int EltIdx = MaskVals[i] * 2;
5029       if (TwoInputs && (EltIdx >= 16)) {
5030         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5031         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5032         continue;
5033       }
5034       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5035       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5036     }
5037     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5038     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5039                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5040                                  MVT::v16i8, &pshufbMask[0], 16));
5041     if (!TwoInputs)
5042       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5043
5044     // Calculate the shuffle mask for the second input, shuffle it, and
5045     // OR it with the first shuffled input.
5046     pshufbMask.clear();
5047     for (unsigned i = 0; i != 8; ++i) {
5048       int EltIdx = MaskVals[i] * 2;
5049       if (EltIdx < 16) {
5050         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5051         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5052         continue;
5053       }
5054       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5055       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5056     }
5057     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5058     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5059                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5060                                  MVT::v16i8, &pshufbMask[0], 16));
5061     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5062     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5063   }
5064
5065   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5066   // and update MaskVals with new element order.
5067   BitVector InOrder(8);
5068   if (BestLoQuad >= 0) {
5069     SmallVector<int, 8> MaskV;
5070     for (int i = 0; i != 4; ++i) {
5071       int idx = MaskVals[i];
5072       if (idx < 0) {
5073         MaskV.push_back(-1);
5074         InOrder.set(i);
5075       } else if ((idx / 4) == BestLoQuad) {
5076         MaskV.push_back(idx & 3);
5077         InOrder.set(i);
5078       } else {
5079         MaskV.push_back(-1);
5080       }
5081     }
5082     for (unsigned i = 4; i != 8; ++i)
5083       MaskV.push_back(i);
5084     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5085                                 &MaskV[0]);
5086
5087     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5088       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5089                                NewV.getOperand(0),
5090                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5091                                DAG);
5092   }
5093
5094   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5095   // and update MaskVals with the new element order.
5096   if (BestHiQuad >= 0) {
5097     SmallVector<int, 8> MaskV;
5098     for (unsigned i = 0; i != 4; ++i)
5099       MaskV.push_back(i);
5100     for (unsigned i = 4; i != 8; ++i) {
5101       int idx = MaskVals[i];
5102       if (idx < 0) {
5103         MaskV.push_back(-1);
5104         InOrder.set(i);
5105       } else if ((idx / 4) == BestHiQuad) {
5106         MaskV.push_back((idx & 3) + 4);
5107         InOrder.set(i);
5108       } else {
5109         MaskV.push_back(-1);
5110       }
5111     }
5112     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5113                                 &MaskV[0]);
5114
5115     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5116       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5117                               NewV.getOperand(0),
5118                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5119                               DAG);
5120   }
5121
5122   // In case BestHi & BestLo were both -1, which means each quadword has a word
5123   // from each of the four input quadwords, calculate the InOrder bitvector now
5124   // before falling through to the insert/extract cleanup.
5125   if (BestLoQuad == -1 && BestHiQuad == -1) {
5126     NewV = V1;
5127     for (int i = 0; i != 8; ++i)
5128       if (MaskVals[i] < 0 || MaskVals[i] == i)
5129         InOrder.set(i);
5130   }
5131
5132   // The other elements are put in the right place using pextrw and pinsrw.
5133   for (unsigned i = 0; i != 8; ++i) {
5134     if (InOrder[i])
5135       continue;
5136     int EltIdx = MaskVals[i];
5137     if (EltIdx < 0)
5138       continue;
5139     SDValue ExtOp = (EltIdx < 8)
5140     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5141                   DAG.getIntPtrConstant(EltIdx))
5142     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5143                   DAG.getIntPtrConstant(EltIdx - 8));
5144     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5145                        DAG.getIntPtrConstant(i));
5146   }
5147   return NewV;
5148 }
5149
5150 // v16i8 shuffles - Prefer shuffles in the following order:
5151 // 1. [ssse3] 1 x pshufb
5152 // 2. [ssse3] 2 x pshufb + 1 x por
5153 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5154 static
5155 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5156                                  SelectionDAG &DAG,
5157                                  const X86TargetLowering &TLI) {
5158   SDValue V1 = SVOp->getOperand(0);
5159   SDValue V2 = SVOp->getOperand(1);
5160   DebugLoc dl = SVOp->getDebugLoc();
5161   SmallVector<int, 16> MaskVals;
5162   SVOp->getMask(MaskVals);
5163
5164   // If we have SSSE3, case 1 is generated when all result bytes come from
5165   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5166   // present, fall back to case 3.
5167   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5168   bool V1Only = true;
5169   bool V2Only = true;
5170   for (unsigned i = 0; i < 16; ++i) {
5171     int EltIdx = MaskVals[i];
5172     if (EltIdx < 0)
5173       continue;
5174     if (EltIdx < 16)
5175       V2Only = false;
5176     else
5177       V1Only = false;
5178   }
5179
5180   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5181   if (TLI.getSubtarget()->hasSSSE3()) {
5182     SmallVector<SDValue,16> pshufbMask;
5183
5184     // If all result elements are from one input vector, then only translate
5185     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5186     //
5187     // Otherwise, we have elements from both input vectors, and must zero out
5188     // elements that come from V2 in the first mask, and V1 in the second mask
5189     // so that we can OR them together.
5190     bool TwoInputs = !(V1Only || V2Only);
5191     for (unsigned i = 0; i != 16; ++i) {
5192       int EltIdx = MaskVals[i];
5193       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5194         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5195         continue;
5196       }
5197       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5198     }
5199     // If all the elements are from V2, assign it to V1 and return after
5200     // building the first pshufb.
5201     if (V2Only)
5202       V1 = V2;
5203     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5204                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5205                                  MVT::v16i8, &pshufbMask[0], 16));
5206     if (!TwoInputs)
5207       return V1;
5208
5209     // Calculate the shuffle mask for the second input, shuffle it, and
5210     // OR it with the first shuffled input.
5211     pshufbMask.clear();
5212     for (unsigned i = 0; i != 16; ++i) {
5213       int EltIdx = MaskVals[i];
5214       if (EltIdx < 16) {
5215         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5216         continue;
5217       }
5218       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5219     }
5220     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5221                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5222                                  MVT::v16i8, &pshufbMask[0], 16));
5223     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5224   }
5225
5226   // No SSSE3 - Calculate in place words and then fix all out of place words
5227   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5228   // the 16 different words that comprise the two doublequadword input vectors.
5229   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5230   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5231   SDValue NewV = V2Only ? V2 : V1;
5232   for (int i = 0; i != 8; ++i) {
5233     int Elt0 = MaskVals[i*2];
5234     int Elt1 = MaskVals[i*2+1];
5235
5236     // This word of the result is all undef, skip it.
5237     if (Elt0 < 0 && Elt1 < 0)
5238       continue;
5239
5240     // This word of the result is already in the correct place, skip it.
5241     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5242       continue;
5243     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5244       continue;
5245
5246     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5247     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5248     SDValue InsElt;
5249
5250     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5251     // using a single extract together, load it and store it.
5252     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5253       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5254                            DAG.getIntPtrConstant(Elt1 / 2));
5255       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5256                         DAG.getIntPtrConstant(i));
5257       continue;
5258     }
5259
5260     // If Elt1 is defined, extract it from the appropriate source.  If the
5261     // source byte is not also odd, shift the extracted word left 8 bits
5262     // otherwise clear the bottom 8 bits if we need to do an or.
5263     if (Elt1 >= 0) {
5264       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5265                            DAG.getIntPtrConstant(Elt1 / 2));
5266       if ((Elt1 & 1) == 0)
5267         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5268                              DAG.getConstant(8,
5269                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5270       else if (Elt0 >= 0)
5271         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5272                              DAG.getConstant(0xFF00, MVT::i16));
5273     }
5274     // If Elt0 is defined, extract it from the appropriate source.  If the
5275     // source byte is not also even, shift the extracted word right 8 bits. If
5276     // Elt1 was also defined, OR the extracted values together before
5277     // inserting them in the result.
5278     if (Elt0 >= 0) {
5279       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5280                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5281       if ((Elt0 & 1) != 0)
5282         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5283                               DAG.getConstant(8,
5284                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5285       else if (Elt1 >= 0)
5286         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5287                              DAG.getConstant(0x00FF, MVT::i16));
5288       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5289                          : InsElt0;
5290     }
5291     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5292                        DAG.getIntPtrConstant(i));
5293   }
5294   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5295 }
5296
5297 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5298 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5299 /// done when every pair / quad of shuffle mask elements point to elements in
5300 /// the right sequence. e.g.
5301 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5302 static
5303 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5304                                  SelectionDAG &DAG, DebugLoc dl) {
5305   EVT VT = SVOp->getValueType(0);
5306   SDValue V1 = SVOp->getOperand(0);
5307   SDValue V2 = SVOp->getOperand(1);
5308   unsigned NumElems = VT.getVectorNumElements();
5309   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5310   EVT NewVT;
5311   switch (VT.getSimpleVT().SimpleTy) {
5312   default: assert(false && "Unexpected!");
5313   case MVT::v4f32: NewVT = MVT::v2f64; break;
5314   case MVT::v4i32: NewVT = MVT::v2i64; break;
5315   case MVT::v8i16: NewVT = MVT::v4i32; break;
5316   case MVT::v16i8: NewVT = MVT::v4i32; break;
5317   }
5318
5319   int Scale = NumElems / NewWidth;
5320   SmallVector<int, 8> MaskVec;
5321   for (unsigned i = 0; i < NumElems; i += Scale) {
5322     int StartIdx = -1;
5323     for (int j = 0; j < Scale; ++j) {
5324       int EltIdx = SVOp->getMaskElt(i+j);
5325       if (EltIdx < 0)
5326         continue;
5327       if (StartIdx == -1)
5328         StartIdx = EltIdx - (EltIdx % Scale);
5329       if (EltIdx != StartIdx + j)
5330         return SDValue();
5331     }
5332     if (StartIdx == -1)
5333       MaskVec.push_back(-1);
5334     else
5335       MaskVec.push_back(StartIdx / Scale);
5336   }
5337
5338   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5339   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5340   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5341 }
5342
5343 /// getVZextMovL - Return a zero-extending vector move low node.
5344 ///
5345 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5346                             SDValue SrcOp, SelectionDAG &DAG,
5347                             const X86Subtarget *Subtarget, DebugLoc dl) {
5348   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5349     LoadSDNode *LD = NULL;
5350     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5351       LD = dyn_cast<LoadSDNode>(SrcOp);
5352     if (!LD) {
5353       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5354       // instead.
5355       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5356       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5357           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5358           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5359           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5360         // PR2108
5361         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5362         return DAG.getNode(ISD::BITCAST, dl, VT,
5363                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5364                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5365                                                    OpVT,
5366                                                    SrcOp.getOperand(0)
5367                                                           .getOperand(0))));
5368       }
5369     }
5370   }
5371
5372   return DAG.getNode(ISD::BITCAST, dl, VT,
5373                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5374                                  DAG.getNode(ISD::BITCAST, dl,
5375                                              OpVT, SrcOp)));
5376 }
5377
5378 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5379 /// shuffles.
5380 static SDValue
5381 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5382   SDValue V1 = SVOp->getOperand(0);
5383   SDValue V2 = SVOp->getOperand(1);
5384   DebugLoc dl = SVOp->getDebugLoc();
5385   EVT VT = SVOp->getValueType(0);
5386
5387   SmallVector<std::pair<int, int>, 8> Locs;
5388   Locs.resize(4);
5389   SmallVector<int, 8> Mask1(4U, -1);
5390   SmallVector<int, 8> PermMask;
5391   SVOp->getMask(PermMask);
5392
5393   unsigned NumHi = 0;
5394   unsigned NumLo = 0;
5395   for (unsigned i = 0; i != 4; ++i) {
5396     int Idx = PermMask[i];
5397     if (Idx < 0) {
5398       Locs[i] = std::make_pair(-1, -1);
5399     } else {
5400       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5401       if (Idx < 4) {
5402         Locs[i] = std::make_pair(0, NumLo);
5403         Mask1[NumLo] = Idx;
5404         NumLo++;
5405       } else {
5406         Locs[i] = std::make_pair(1, NumHi);
5407         if (2+NumHi < 4)
5408           Mask1[2+NumHi] = Idx;
5409         NumHi++;
5410       }
5411     }
5412   }
5413
5414   if (NumLo <= 2 && NumHi <= 2) {
5415     // If no more than two elements come from either vector. This can be
5416     // implemented with two shuffles. First shuffle gather the elements.
5417     // The second shuffle, which takes the first shuffle as both of its
5418     // vector operands, put the elements into the right order.
5419     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5420
5421     SmallVector<int, 8> Mask2(4U, -1);
5422
5423     for (unsigned i = 0; i != 4; ++i) {
5424       if (Locs[i].first == -1)
5425         continue;
5426       else {
5427         unsigned Idx = (i < 2) ? 0 : 4;
5428         Idx += Locs[i].first * 2 + Locs[i].second;
5429         Mask2[i] = Idx;
5430       }
5431     }
5432
5433     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5434   } else if (NumLo == 3 || NumHi == 3) {
5435     // Otherwise, we must have three elements from one vector, call it X, and
5436     // one element from the other, call it Y.  First, use a shufps to build an
5437     // intermediate vector with the one element from Y and the element from X
5438     // that will be in the same half in the final destination (the indexes don't
5439     // matter). Then, use a shufps to build the final vector, taking the half
5440     // containing the element from Y from the intermediate, and the other half
5441     // from X.
5442     if (NumHi == 3) {
5443       // Normalize it so the 3 elements come from V1.
5444       CommuteVectorShuffleMask(PermMask, VT);
5445       std::swap(V1, V2);
5446     }
5447
5448     // Find the element from V2.
5449     unsigned HiIndex;
5450     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5451       int Val = PermMask[HiIndex];
5452       if (Val < 0)
5453         continue;
5454       if (Val >= 4)
5455         break;
5456     }
5457
5458     Mask1[0] = PermMask[HiIndex];
5459     Mask1[1] = -1;
5460     Mask1[2] = PermMask[HiIndex^1];
5461     Mask1[3] = -1;
5462     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5463
5464     if (HiIndex >= 2) {
5465       Mask1[0] = PermMask[0];
5466       Mask1[1] = PermMask[1];
5467       Mask1[2] = HiIndex & 1 ? 6 : 4;
5468       Mask1[3] = HiIndex & 1 ? 4 : 6;
5469       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5470     } else {
5471       Mask1[0] = HiIndex & 1 ? 2 : 0;
5472       Mask1[1] = HiIndex & 1 ? 0 : 2;
5473       Mask1[2] = PermMask[2];
5474       Mask1[3] = PermMask[3];
5475       if (Mask1[2] >= 0)
5476         Mask1[2] += 4;
5477       if (Mask1[3] >= 0)
5478         Mask1[3] += 4;
5479       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5480     }
5481   }
5482
5483   // Break it into (shuffle shuffle_hi, shuffle_lo).
5484   Locs.clear();
5485   Locs.resize(4);
5486   SmallVector<int,8> LoMask(4U, -1);
5487   SmallVector<int,8> HiMask(4U, -1);
5488
5489   SmallVector<int,8> *MaskPtr = &LoMask;
5490   unsigned MaskIdx = 0;
5491   unsigned LoIdx = 0;
5492   unsigned HiIdx = 2;
5493   for (unsigned i = 0; i != 4; ++i) {
5494     if (i == 2) {
5495       MaskPtr = &HiMask;
5496       MaskIdx = 1;
5497       LoIdx = 0;
5498       HiIdx = 2;
5499     }
5500     int Idx = PermMask[i];
5501     if (Idx < 0) {
5502       Locs[i] = std::make_pair(-1, -1);
5503     } else if (Idx < 4) {
5504       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5505       (*MaskPtr)[LoIdx] = Idx;
5506       LoIdx++;
5507     } else {
5508       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5509       (*MaskPtr)[HiIdx] = Idx;
5510       HiIdx++;
5511     }
5512   }
5513
5514   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5515   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5516   SmallVector<int, 8> MaskOps;
5517   for (unsigned i = 0; i != 4; ++i) {
5518     if (Locs[i].first == -1) {
5519       MaskOps.push_back(-1);
5520     } else {
5521       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5522       MaskOps.push_back(Idx);
5523     }
5524   }
5525   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5526 }
5527
5528 static bool MayFoldVectorLoad(SDValue V) {
5529   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5530     V = V.getOperand(0);
5531   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5532     V = V.getOperand(0);
5533   if (MayFoldLoad(V))
5534     return true;
5535   return false;
5536 }
5537
5538 // FIXME: the version above should always be used. Since there's
5539 // a bug where several vector shuffles can't be folded because the
5540 // DAG is not updated during lowering and a node claims to have two
5541 // uses while it only has one, use this version, and let isel match
5542 // another instruction if the load really happens to have more than
5543 // one use. Remove this version after this bug get fixed.
5544 // rdar://8434668, PR8156
5545 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5546   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5547     V = V.getOperand(0);
5548   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5549     V = V.getOperand(0);
5550   if (ISD::isNormalLoad(V.getNode()))
5551     return true;
5552   return false;
5553 }
5554
5555 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5556 /// a vector extract, and if both can be later optimized into a single load.
5557 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5558 /// here because otherwise a target specific shuffle node is going to be
5559 /// emitted for this shuffle, and the optimization not done.
5560 /// FIXME: This is probably not the best approach, but fix the problem
5561 /// until the right path is decided.
5562 static
5563 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5564                                          const TargetLowering &TLI) {
5565   EVT VT = V.getValueType();
5566   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5567
5568   // Be sure that the vector shuffle is present in a pattern like this:
5569   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5570   if (!V.hasOneUse())
5571     return false;
5572
5573   SDNode *N = *V.getNode()->use_begin();
5574   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5575     return false;
5576
5577   SDValue EltNo = N->getOperand(1);
5578   if (!isa<ConstantSDNode>(EltNo))
5579     return false;
5580
5581   // If the bit convert changed the number of elements, it is unsafe
5582   // to examine the mask.
5583   bool HasShuffleIntoBitcast = false;
5584   if (V.getOpcode() == ISD::BITCAST) {
5585     EVT SrcVT = V.getOperand(0).getValueType();
5586     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5587       return false;
5588     V = V.getOperand(0);
5589     HasShuffleIntoBitcast = true;
5590   }
5591
5592   // Select the input vector, guarding against out of range extract vector.
5593   unsigned NumElems = VT.getVectorNumElements();
5594   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5595   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5596   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5597
5598   // Skip one more bit_convert if necessary
5599   if (V.getOpcode() == ISD::BITCAST)
5600     V = V.getOperand(0);
5601
5602   if (ISD::isNormalLoad(V.getNode())) {
5603     // Is the original load suitable?
5604     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5605
5606     // FIXME: avoid the multi-use bug that is preventing lots of
5607     // of foldings to be detected, this is still wrong of course, but
5608     // give the temporary desired behavior, and if it happens that
5609     // the load has real more uses, during isel it will not fold, and
5610     // will generate poor code.
5611     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5612       return false;
5613
5614     if (!HasShuffleIntoBitcast)
5615       return true;
5616
5617     // If there's a bitcast before the shuffle, check if the load type and
5618     // alignment is valid.
5619     unsigned Align = LN0->getAlignment();
5620     unsigned NewAlign =
5621       TLI.getTargetData()->getABITypeAlignment(
5622                                     VT.getTypeForEVT(*DAG.getContext()));
5623
5624     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5625       return false;
5626   }
5627
5628   return true;
5629 }
5630
5631 static
5632 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5633   EVT VT = Op.getValueType();
5634
5635   // Canonizalize to v2f64.
5636   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5637   return DAG.getNode(ISD::BITCAST, dl, VT,
5638                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5639                                           V1, DAG));
5640 }
5641
5642 static
5643 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5644                         bool HasSSE2) {
5645   SDValue V1 = Op.getOperand(0);
5646   SDValue V2 = Op.getOperand(1);
5647   EVT VT = Op.getValueType();
5648
5649   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5650
5651   if (HasSSE2 && VT == MVT::v2f64)
5652     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5653
5654   // v4f32 or v4i32
5655   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5656 }
5657
5658 static
5659 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5660   SDValue V1 = Op.getOperand(0);
5661   SDValue V2 = Op.getOperand(1);
5662   EVT VT = Op.getValueType();
5663
5664   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5665          "unsupported shuffle type");
5666
5667   if (V2.getOpcode() == ISD::UNDEF)
5668     V2 = V1;
5669
5670   // v4i32 or v4f32
5671   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5672 }
5673
5674 static
5675 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5676   SDValue V1 = Op.getOperand(0);
5677   SDValue V2 = Op.getOperand(1);
5678   EVT VT = Op.getValueType();
5679   unsigned NumElems = VT.getVectorNumElements();
5680
5681   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5682   // operand of these instructions is only memory, so check if there's a
5683   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5684   // same masks.
5685   bool CanFoldLoad = false;
5686
5687   // Trivial case, when V2 comes from a load.
5688   if (MayFoldVectorLoad(V2))
5689     CanFoldLoad = true;
5690
5691   // When V1 is a load, it can be folded later into a store in isel, example:
5692   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5693   //    turns into:
5694   //  (MOVLPSmr addr:$src1, VR128:$src2)
5695   // So, recognize this potential and also use MOVLPS or MOVLPD
5696   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5697     CanFoldLoad = true;
5698
5699   // Both of them can't be memory operations though.
5700   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5701     CanFoldLoad = false;
5702
5703   if (CanFoldLoad) {
5704     if (HasSSE2 && NumElems == 2)
5705       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5706
5707     if (NumElems == 4)
5708       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5709   }
5710
5711   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5712   // movl and movlp will both match v2i64, but v2i64 is never matched by
5713   // movl earlier because we make it strict to avoid messing with the movlp load
5714   // folding logic (see the code above getMOVLP call). Match it here then,
5715   // this is horrible, but will stay like this until we move all shuffle
5716   // matching to x86 specific nodes. Note that for the 1st condition all
5717   // types are matched with movsd.
5718   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5719     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5720   else if (HasSSE2)
5721     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5722
5723
5724   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5725
5726   // Invert the operand order and use SHUFPS to match it.
5727   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5728                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5729 }
5730
5731 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5732   switch(VT.getSimpleVT().SimpleTy) {
5733   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5734   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5735   case MVT::v4f32:
5736     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5737   case MVT::v2f64:
5738     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5739   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5740   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5741   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5742   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5743   default:
5744     llvm_unreachable("Unknown type for unpckl");
5745   }
5746   return 0;
5747 }
5748
5749 static inline unsigned getUNPCKHOpcode(EVT VT) {
5750   switch(VT.getSimpleVT().SimpleTy) {
5751   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5752   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5753   case MVT::v4f32: return X86ISD::UNPCKHPS;
5754   case MVT::v2f64: return X86ISD::UNPCKHPD;
5755   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5756   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5757   default:
5758     llvm_unreachable("Unknown type for unpckh");
5759   }
5760   return 0;
5761 }
5762
5763 static
5764 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5765                                const TargetLowering &TLI,
5766                                const X86Subtarget *Subtarget) {
5767   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5768   EVT VT = Op.getValueType();
5769   DebugLoc dl = Op.getDebugLoc();
5770   SDValue V1 = Op.getOperand(0);
5771   SDValue V2 = Op.getOperand(1);
5772
5773   if (isZeroShuffle(SVOp))
5774     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5775
5776   // Handle splat operations
5777   if (SVOp->isSplat()) {
5778     unsigned NumElem = VT.getVectorNumElements();
5779     // Special case, this is the only place now where it's allowed to return
5780     // a vector_shuffle operation without using a target specific node, because
5781     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
5782     // this be moved to DAGCombine instead?
5783     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5784       return Op;
5785
5786     // Handle splats by matching through known masks
5787     if ((VT.is128BitVector() && NumElem <= 4) ||
5788         (VT.is256BitVector() && NumElem <= 8))
5789       return SDValue();
5790
5791     // All i16 and i8 vector types can't be used directly by a generic shuffle
5792     // instruction because the target has no such instruction. Generate shuffles
5793     // which repeat i16 and i8 several times until they fit in i32, and then can
5794     // be manipulated by target suported shuffles. After the insertion of the
5795     // necessary shuffles, the result is bitcasted back to v4f32 or v8f32.
5796     return PromoteSplat(SVOp, DAG);
5797   }
5798
5799   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5800   // do it!
5801   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5802     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5803     if (NewOp.getNode())
5804       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5805   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5806     // FIXME: Figure out a cleaner way to do this.
5807     // Try to make use of movq to zero out the top part.
5808     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5809       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5810       if (NewOp.getNode()) {
5811         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5812           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5813                               DAG, Subtarget, dl);
5814       }
5815     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5816       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5817       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5818         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5819                             DAG, Subtarget, dl);
5820     }
5821   }
5822   return SDValue();
5823 }
5824
5825 SDValue
5826 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5827   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5828   SDValue V1 = Op.getOperand(0);
5829   SDValue V2 = Op.getOperand(1);
5830   EVT VT = Op.getValueType();
5831   DebugLoc dl = Op.getDebugLoc();
5832   unsigned NumElems = VT.getVectorNumElements();
5833   bool isMMX = VT.getSizeInBits() == 64;
5834   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5835   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5836   bool V1IsSplat = false;
5837   bool V2IsSplat = false;
5838   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5839   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5840   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5841   MachineFunction &MF = DAG.getMachineFunction();
5842   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5843
5844   // Shuffle operations on MMX not supported.
5845   if (isMMX)
5846     return Op;
5847
5848   // Vector shuffle lowering takes 3 steps:
5849   //
5850   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5851   //    narrowing and commutation of operands should be handled.
5852   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5853   //    shuffle nodes.
5854   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5855   //    so the shuffle can be broken into other shuffles and the legalizer can
5856   //    try the lowering again.
5857   //
5858   // The general ideia is that no vector_shuffle operation should be left to
5859   // be matched during isel, all of them must be converted to a target specific
5860   // node here.
5861
5862   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5863   // narrowing and commutation of operands should be handled. The actual code
5864   // doesn't include all of those, work in progress...
5865   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5866   if (NewOp.getNode())
5867     return NewOp;
5868
5869   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5870   // unpckh_undef). Only use pshufd if speed is more important than size.
5871   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5872     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5873       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5874   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5875     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5876       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5877
5878   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5879       RelaxedMayFoldVectorLoad(V1))
5880     return getMOVDDup(Op, dl, V1, DAG);
5881
5882   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5883     return getMOVHighToLow(Op, dl, DAG);
5884
5885   // Use to match splats
5886   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5887       (VT == MVT::v2f64 || VT == MVT::v2i64))
5888     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5889
5890   if (X86::isPSHUFDMask(SVOp)) {
5891     // The actual implementation will match the mask in the if above and then
5892     // during isel it can match several different instructions, not only pshufd
5893     // as its name says, sad but true, emulate the behavior for now...
5894     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5895         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5896
5897     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5898
5899     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5900       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5901
5902     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5903       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5904                                   TargetMask, DAG);
5905
5906     if (VT == MVT::v4f32)
5907       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5908                                   TargetMask, DAG);
5909   }
5910
5911   // Check if this can be converted into a logical shift.
5912   bool isLeft = false;
5913   unsigned ShAmt = 0;
5914   SDValue ShVal;
5915   bool isShift = getSubtarget()->hasSSE2() &&
5916     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5917   if (isShift && ShVal.hasOneUse()) {
5918     // If the shifted value has multiple uses, it may be cheaper to use
5919     // v_set0 + movlhps or movhlps, etc.
5920     EVT EltVT = VT.getVectorElementType();
5921     ShAmt *= EltVT.getSizeInBits();
5922     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5923   }
5924
5925   if (X86::isMOVLMask(SVOp)) {
5926     if (V1IsUndef)
5927       return V2;
5928     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5929       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5930     if (!X86::isMOVLPMask(SVOp)) {
5931       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5932         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5933
5934       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5935         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5936     }
5937   }
5938
5939   // FIXME: fold these into legal mask.
5940   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5941     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5942
5943   if (X86::isMOVHLPSMask(SVOp))
5944     return getMOVHighToLow(Op, dl, DAG);
5945
5946   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5947     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5948
5949   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5950     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5951
5952   if (X86::isMOVLPMask(SVOp))
5953     return getMOVLP(Op, dl, DAG, HasSSE2);
5954
5955   if (ShouldXformToMOVHLPS(SVOp) ||
5956       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5957     return CommuteVectorShuffle(SVOp, DAG);
5958
5959   if (isShift) {
5960     // No better options. Use a vshl / vsrl.
5961     EVT EltVT = VT.getVectorElementType();
5962     ShAmt *= EltVT.getSizeInBits();
5963     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5964   }
5965
5966   bool Commuted = false;
5967   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5968   // 1,1,1,1 -> v8i16 though.
5969   V1IsSplat = isSplatVector(V1.getNode());
5970   V2IsSplat = isSplatVector(V2.getNode());
5971
5972   // Canonicalize the splat or undef, if present, to be on the RHS.
5973   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5974     Op = CommuteVectorShuffle(SVOp, DAG);
5975     SVOp = cast<ShuffleVectorSDNode>(Op);
5976     V1 = SVOp->getOperand(0);
5977     V2 = SVOp->getOperand(1);
5978     std::swap(V1IsSplat, V2IsSplat);
5979     std::swap(V1IsUndef, V2IsUndef);
5980     Commuted = true;
5981   }
5982
5983   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5984     // Shuffling low element of v1 into undef, just return v1.
5985     if (V2IsUndef)
5986       return V1;
5987     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5988     // the instruction selector will not match, so get a canonical MOVL with
5989     // swapped operands to undo the commute.
5990     return getMOVL(DAG, dl, VT, V2, V1);
5991   }
5992
5993   if (X86::isUNPCKLMask(SVOp))
5994     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5995                                 dl, VT, V1, V2, DAG);
5996
5997   if (X86::isUNPCKHMask(SVOp))
5998     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5999
6000   if (V2IsSplat) {
6001     // Normalize mask so all entries that point to V2 points to its first
6002     // element then try to match unpck{h|l} again. If match, return a
6003     // new vector_shuffle with the corrected mask.
6004     SDValue NewMask = NormalizeMask(SVOp, DAG);
6005     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6006     if (NSVOp != SVOp) {
6007       if (X86::isUNPCKLMask(NSVOp, true)) {
6008         return NewMask;
6009       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6010         return NewMask;
6011       }
6012     }
6013   }
6014
6015   if (Commuted) {
6016     // Commute is back and try unpck* again.
6017     // FIXME: this seems wrong.
6018     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6019     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6020
6021     if (X86::isUNPCKLMask(NewSVOp))
6022       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6023                                   dl, VT, V2, V1, DAG);
6024
6025     if (X86::isUNPCKHMask(NewSVOp))
6026       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6027   }
6028
6029   // Normalize the node to match x86 shuffle ops if needed
6030   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6031     return CommuteVectorShuffle(SVOp, DAG);
6032
6033   // The checks below are all present in isShuffleMaskLegal, but they are
6034   // inlined here right now to enable us to directly emit target specific
6035   // nodes, and remove one by one until they don't return Op anymore.
6036   SmallVector<int, 16> M;
6037   SVOp->getMask(M);
6038
6039   if (isPALIGNRMask(M, VT, HasSSSE3))
6040     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6041                                 X86::getShufflePALIGNRImmediate(SVOp),
6042                                 DAG);
6043
6044   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6045       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6046     if (VT == MVT::v2f64) {
6047       X86ISD::NodeType Opcode =
6048         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
6049       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
6050     }
6051     if (VT == MVT::v2i64)
6052       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6053   }
6054
6055   if (isPSHUFHWMask(M, VT))
6056     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6057                                 X86::getShufflePSHUFHWImmediate(SVOp),
6058                                 DAG);
6059
6060   if (isPSHUFLWMask(M, VT))
6061     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6062                                 X86::getShufflePSHUFLWImmediate(SVOp),
6063                                 DAG);
6064
6065   if (isSHUFPMask(M, VT)) {
6066     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6067     if (VT == MVT::v4f32 || VT == MVT::v4i32)
6068       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6069                                   TargetMask, DAG);
6070     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6071       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6072                                   TargetMask, DAG);
6073   }
6074
6075   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6076     if (VT != MVT::v2i64 && VT != MVT::v2f64)
6077       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6078                                   dl, VT, V1, V1, DAG);
6079   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6080     if (VT != MVT::v2i64 && VT != MVT::v2f64)
6081       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6082
6083   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6084   if (VT == MVT::v8i16) {
6085     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6086     if (NewOp.getNode())
6087       return NewOp;
6088   }
6089
6090   if (VT == MVT::v16i8) {
6091     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6092     if (NewOp.getNode())
6093       return NewOp;
6094   }
6095
6096   // Handle all 4 wide cases with a number of shuffles.
6097   if (NumElems == 4)
6098     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
6099
6100   // Handle VPERMIL permutations
6101   if (isVPERMILMask(M, VT)) {
6102     unsigned TargetMask = getShuffleVPERMILImmediate(SVOp);
6103     if (VT == MVT::v8f32)
6104       return getTargetShuffleNode(X86ISD::VPERMIL, dl, VT, V1, TargetMask, DAG);
6105   }
6106
6107   return SDValue();
6108 }
6109
6110 SDValue
6111 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6112                                                 SelectionDAG &DAG) const {
6113   EVT VT = Op.getValueType();
6114   DebugLoc dl = Op.getDebugLoc();
6115   if (VT.getSizeInBits() == 8) {
6116     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6117                                     Op.getOperand(0), Op.getOperand(1));
6118     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6119                                     DAG.getValueType(VT));
6120     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6121   } else if (VT.getSizeInBits() == 16) {
6122     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6123     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6124     if (Idx == 0)
6125       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6126                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6127                                      DAG.getNode(ISD::BITCAST, dl,
6128                                                  MVT::v4i32,
6129                                                  Op.getOperand(0)),
6130                                      Op.getOperand(1)));
6131     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6132                                     Op.getOperand(0), Op.getOperand(1));
6133     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6134                                     DAG.getValueType(VT));
6135     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6136   } else if (VT == MVT::f32) {
6137     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6138     // the result back to FR32 register. It's only worth matching if the
6139     // result has a single use which is a store or a bitcast to i32.  And in
6140     // the case of a store, it's not worth it if the index is a constant 0,
6141     // because a MOVSSmr can be used instead, which is smaller and faster.
6142     if (!Op.hasOneUse())
6143       return SDValue();
6144     SDNode *User = *Op.getNode()->use_begin();
6145     if ((User->getOpcode() != ISD::STORE ||
6146          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6147           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6148         (User->getOpcode() != ISD::BITCAST ||
6149          User->getValueType(0) != MVT::i32))
6150       return SDValue();
6151     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6152                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6153                                               Op.getOperand(0)),
6154                                               Op.getOperand(1));
6155     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6156   } else if (VT == MVT::i32) {
6157     // ExtractPS works with constant index.
6158     if (isa<ConstantSDNode>(Op.getOperand(1)))
6159       return Op;
6160   }
6161   return SDValue();
6162 }
6163
6164
6165 SDValue
6166 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6167                                            SelectionDAG &DAG) const {
6168   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6169     return SDValue();
6170
6171   SDValue Vec = Op.getOperand(0);
6172   EVT VecVT = Vec.getValueType();
6173
6174   // If this is a 256-bit vector result, first extract the 128-bit
6175   // vector and then extract from the 128-bit vector.
6176   if (VecVT.getSizeInBits() > 128) {
6177     DebugLoc dl = Op.getNode()->getDebugLoc();
6178     unsigned NumElems = VecVT.getVectorNumElements();
6179     SDValue Idx = Op.getOperand(1);
6180
6181     if (!isa<ConstantSDNode>(Idx))
6182       return SDValue();
6183
6184     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6185     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6186
6187     // Get the 128-bit vector.
6188     bool Upper = IdxVal >= ExtractNumElems;
6189     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6190
6191     // Extract from it.
6192     SDValue ScaledIdx = Idx;
6193     if (Upper)
6194       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6195                               DAG.getConstant(ExtractNumElems,
6196                                               Idx.getValueType()));
6197     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6198                        ScaledIdx);
6199   }
6200
6201   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6202
6203   if (Subtarget->hasSSE41()) {
6204     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6205     if (Res.getNode())
6206       return Res;
6207   }
6208
6209   EVT VT = Op.getValueType();
6210   DebugLoc dl = Op.getDebugLoc();
6211   // TODO: handle v16i8.
6212   if (VT.getSizeInBits() == 16) {
6213     SDValue Vec = Op.getOperand(0);
6214     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6215     if (Idx == 0)
6216       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6217                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6218                                      DAG.getNode(ISD::BITCAST, dl,
6219                                                  MVT::v4i32, Vec),
6220                                      Op.getOperand(1)));
6221     // Transform it so it match pextrw which produces a 32-bit result.
6222     EVT EltVT = MVT::i32;
6223     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6224                                     Op.getOperand(0), Op.getOperand(1));
6225     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6226                                     DAG.getValueType(VT));
6227     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6228   } else if (VT.getSizeInBits() == 32) {
6229     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6230     if (Idx == 0)
6231       return Op;
6232
6233     // SHUFPS the element to the lowest double word, then movss.
6234     int Mask[4] = { Idx, -1, -1, -1 };
6235     EVT VVT = Op.getOperand(0).getValueType();
6236     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6237                                        DAG.getUNDEF(VVT), Mask);
6238     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6239                        DAG.getIntPtrConstant(0));
6240   } else if (VT.getSizeInBits() == 64) {
6241     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6242     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6243     //        to match extract_elt for f64.
6244     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6245     if (Idx == 0)
6246       return Op;
6247
6248     // UNPCKHPD the element to the lowest double word, then movsd.
6249     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6250     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6251     int Mask[2] = { 1, -1 };
6252     EVT VVT = Op.getOperand(0).getValueType();
6253     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6254                                        DAG.getUNDEF(VVT), Mask);
6255     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6256                        DAG.getIntPtrConstant(0));
6257   }
6258
6259   return SDValue();
6260 }
6261
6262 SDValue
6263 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6264                                                SelectionDAG &DAG) const {
6265   EVT VT = Op.getValueType();
6266   EVT EltVT = VT.getVectorElementType();
6267   DebugLoc dl = Op.getDebugLoc();
6268
6269   SDValue N0 = Op.getOperand(0);
6270   SDValue N1 = Op.getOperand(1);
6271   SDValue N2 = Op.getOperand(2);
6272
6273   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6274       isa<ConstantSDNode>(N2)) {
6275     unsigned Opc;
6276     if (VT == MVT::v8i16)
6277       Opc = X86ISD::PINSRW;
6278     else if (VT == MVT::v16i8)
6279       Opc = X86ISD::PINSRB;
6280     else
6281       Opc = X86ISD::PINSRB;
6282
6283     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6284     // argument.
6285     if (N1.getValueType() != MVT::i32)
6286       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6287     if (N2.getValueType() != MVT::i32)
6288       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6289     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6290   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6291     // Bits [7:6] of the constant are the source select.  This will always be
6292     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6293     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6294     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6295     // Bits [5:4] of the constant are the destination select.  This is the
6296     //  value of the incoming immediate.
6297     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6298     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6299     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6300     // Create this as a scalar to vector..
6301     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6302     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6303   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6304     // PINSR* works with constant index.
6305     return Op;
6306   }
6307   return SDValue();
6308 }
6309
6310 SDValue
6311 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6312   EVT VT = Op.getValueType();
6313   EVT EltVT = VT.getVectorElementType();
6314
6315   DebugLoc dl = Op.getDebugLoc();
6316   SDValue N0 = Op.getOperand(0);
6317   SDValue N1 = Op.getOperand(1);
6318   SDValue N2 = Op.getOperand(2);
6319
6320   // If this is a 256-bit vector result, first insert into a 128-bit
6321   // vector and then insert into the 256-bit vector.
6322   if (VT.getSizeInBits() > 128) {
6323     if (!isa<ConstantSDNode>(N2))
6324       return SDValue();
6325
6326     // Get the 128-bit vector.
6327     unsigned NumElems = VT.getVectorNumElements();
6328     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6329     bool Upper = IdxVal >= NumElems / 2;
6330
6331     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6332
6333     // Insert into it.
6334     SDValue ScaledN2 = N2;
6335     if (Upper)
6336       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6337                              DAG.getConstant(NumElems /
6338                                              (VT.getSizeInBits() / 128),
6339                                              N2.getValueType()));
6340     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6341                      N1, ScaledN2);
6342
6343     // Insert the 128-bit vector
6344     // FIXME: Why UNDEF?
6345     return Insert128BitVector(N0, Op, N2, DAG, dl);
6346   }
6347
6348   if (Subtarget->hasSSE41())
6349     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6350
6351   if (EltVT == MVT::i8)
6352     return SDValue();
6353
6354   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6355     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6356     // as its second argument.
6357     if (N1.getValueType() != MVT::i32)
6358       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6359     if (N2.getValueType() != MVT::i32)
6360       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6361     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6362   }
6363   return SDValue();
6364 }
6365
6366 SDValue
6367 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6368   LLVMContext *Context = DAG.getContext();
6369   DebugLoc dl = Op.getDebugLoc();
6370   EVT OpVT = Op.getValueType();
6371
6372   // If this is a 256-bit vector result, first insert into a 128-bit
6373   // vector and then insert into the 256-bit vector.
6374   if (OpVT.getSizeInBits() > 128) {
6375     // Insert into a 128-bit vector.
6376     EVT VT128 = EVT::getVectorVT(*Context,
6377                                  OpVT.getVectorElementType(),
6378                                  OpVT.getVectorNumElements() / 2);
6379
6380     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6381
6382     // Insert the 128-bit vector.
6383     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6384                               DAG.getConstant(0, MVT::i32),
6385                               DAG, dl);
6386   }
6387
6388   if (Op.getValueType() == MVT::v1i64 &&
6389       Op.getOperand(0).getValueType() == MVT::i64)
6390     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6391
6392   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6393   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6394          "Expected an SSE type!");
6395   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6396                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6397 }
6398
6399 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6400 // a simple subregister reference or explicit instructions to grab
6401 // upper bits of a vector.
6402 SDValue
6403 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6404   if (Subtarget->hasAVX()) {
6405     DebugLoc dl = Op.getNode()->getDebugLoc();
6406     SDValue Vec = Op.getNode()->getOperand(0);
6407     SDValue Idx = Op.getNode()->getOperand(1);
6408
6409     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6410         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6411         return Extract128BitVector(Vec, Idx, DAG, dl);
6412     }
6413   }
6414   return SDValue();
6415 }
6416
6417 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6418 // simple superregister reference or explicit instructions to insert
6419 // the upper bits of a vector.
6420 SDValue
6421 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6422   if (Subtarget->hasAVX()) {
6423     DebugLoc dl = Op.getNode()->getDebugLoc();
6424     SDValue Vec = Op.getNode()->getOperand(0);
6425     SDValue SubVec = Op.getNode()->getOperand(1);
6426     SDValue Idx = Op.getNode()->getOperand(2);
6427
6428     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6429         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6430       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6431     }
6432   }
6433   return SDValue();
6434 }
6435
6436 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6437 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6438 // one of the above mentioned nodes. It has to be wrapped because otherwise
6439 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6440 // be used to form addressing mode. These wrapped nodes will be selected
6441 // into MOV32ri.
6442 SDValue
6443 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6444   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6445
6446   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6447   // global base reg.
6448   unsigned char OpFlag = 0;
6449   unsigned WrapperKind = X86ISD::Wrapper;
6450   CodeModel::Model M = getTargetMachine().getCodeModel();
6451
6452   if (Subtarget->isPICStyleRIPRel() &&
6453       (M == CodeModel::Small || M == CodeModel::Kernel))
6454     WrapperKind = X86ISD::WrapperRIP;
6455   else if (Subtarget->isPICStyleGOT())
6456     OpFlag = X86II::MO_GOTOFF;
6457   else if (Subtarget->isPICStyleStubPIC())
6458     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6459
6460   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6461                                              CP->getAlignment(),
6462                                              CP->getOffset(), OpFlag);
6463   DebugLoc DL = CP->getDebugLoc();
6464   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6465   // With PIC, the address is actually $g + Offset.
6466   if (OpFlag) {
6467     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6468                          DAG.getNode(X86ISD::GlobalBaseReg,
6469                                      DebugLoc(), getPointerTy()),
6470                          Result);
6471   }
6472
6473   return Result;
6474 }
6475
6476 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6477   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6478
6479   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6480   // global base reg.
6481   unsigned char OpFlag = 0;
6482   unsigned WrapperKind = X86ISD::Wrapper;
6483   CodeModel::Model M = getTargetMachine().getCodeModel();
6484
6485   if (Subtarget->isPICStyleRIPRel() &&
6486       (M == CodeModel::Small || M == CodeModel::Kernel))
6487     WrapperKind = X86ISD::WrapperRIP;
6488   else if (Subtarget->isPICStyleGOT())
6489     OpFlag = X86II::MO_GOTOFF;
6490   else if (Subtarget->isPICStyleStubPIC())
6491     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6492
6493   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6494                                           OpFlag);
6495   DebugLoc DL = JT->getDebugLoc();
6496   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6497
6498   // With PIC, the address is actually $g + Offset.
6499   if (OpFlag)
6500     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6501                          DAG.getNode(X86ISD::GlobalBaseReg,
6502                                      DebugLoc(), getPointerTy()),
6503                          Result);
6504
6505   return Result;
6506 }
6507
6508 SDValue
6509 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6510   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6511
6512   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6513   // global base reg.
6514   unsigned char OpFlag = 0;
6515   unsigned WrapperKind = X86ISD::Wrapper;
6516   CodeModel::Model M = getTargetMachine().getCodeModel();
6517
6518   if (Subtarget->isPICStyleRIPRel() &&
6519       (M == CodeModel::Small || M == CodeModel::Kernel))
6520     WrapperKind = X86ISD::WrapperRIP;
6521   else if (Subtarget->isPICStyleGOT())
6522     OpFlag = X86II::MO_GOTOFF;
6523   else if (Subtarget->isPICStyleStubPIC())
6524     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6525
6526   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6527
6528   DebugLoc DL = Op.getDebugLoc();
6529   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6530
6531
6532   // With PIC, the address is actually $g + Offset.
6533   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6534       !Subtarget->is64Bit()) {
6535     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6536                          DAG.getNode(X86ISD::GlobalBaseReg,
6537                                      DebugLoc(), getPointerTy()),
6538                          Result);
6539   }
6540
6541   return Result;
6542 }
6543
6544 SDValue
6545 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6546   // Create the TargetBlockAddressAddress node.
6547   unsigned char OpFlags =
6548     Subtarget->ClassifyBlockAddressReference();
6549   CodeModel::Model M = getTargetMachine().getCodeModel();
6550   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6551   DebugLoc dl = Op.getDebugLoc();
6552   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6553                                        /*isTarget=*/true, OpFlags);
6554
6555   if (Subtarget->isPICStyleRIPRel() &&
6556       (M == CodeModel::Small || M == CodeModel::Kernel))
6557     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6558   else
6559     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6560
6561   // With PIC, the address is actually $g + Offset.
6562   if (isGlobalRelativeToPICBase(OpFlags)) {
6563     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6564                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6565                          Result);
6566   }
6567
6568   return Result;
6569 }
6570
6571 SDValue
6572 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6573                                       int64_t Offset,
6574                                       SelectionDAG &DAG) const {
6575   // Create the TargetGlobalAddress node, folding in the constant
6576   // offset if it is legal.
6577   unsigned char OpFlags =
6578     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6579   CodeModel::Model M = getTargetMachine().getCodeModel();
6580   SDValue Result;
6581   if (OpFlags == X86II::MO_NO_FLAG &&
6582       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6583     // A direct static reference to a global.
6584     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6585     Offset = 0;
6586   } else {
6587     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6588   }
6589
6590   if (Subtarget->isPICStyleRIPRel() &&
6591       (M == CodeModel::Small || M == CodeModel::Kernel))
6592     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6593   else
6594     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6595
6596   // With PIC, the address is actually $g + Offset.
6597   if (isGlobalRelativeToPICBase(OpFlags)) {
6598     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6599                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6600                          Result);
6601   }
6602
6603   // For globals that require a load from a stub to get the address, emit the
6604   // load.
6605   if (isGlobalStubReference(OpFlags))
6606     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6607                          MachinePointerInfo::getGOT(), false, false, 0);
6608
6609   // If there was a non-zero offset that we didn't fold, create an explicit
6610   // addition for it.
6611   if (Offset != 0)
6612     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6613                          DAG.getConstant(Offset, getPointerTy()));
6614
6615   return Result;
6616 }
6617
6618 SDValue
6619 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6620   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6621   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6622   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6623 }
6624
6625 static SDValue
6626 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6627            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6628            unsigned char OperandFlags) {
6629   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6630   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6631   DebugLoc dl = GA->getDebugLoc();
6632   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6633                                            GA->getValueType(0),
6634                                            GA->getOffset(),
6635                                            OperandFlags);
6636   if (InFlag) {
6637     SDValue Ops[] = { Chain,  TGA, *InFlag };
6638     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6639   } else {
6640     SDValue Ops[]  = { Chain, TGA };
6641     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6642   }
6643
6644   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6645   MFI->setAdjustsStack(true);
6646
6647   SDValue Flag = Chain.getValue(1);
6648   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6649 }
6650
6651 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6652 static SDValue
6653 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6654                                 const EVT PtrVT) {
6655   SDValue InFlag;
6656   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6657   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6658                                      DAG.getNode(X86ISD::GlobalBaseReg,
6659                                                  DebugLoc(), PtrVT), InFlag);
6660   InFlag = Chain.getValue(1);
6661
6662   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6663 }
6664
6665 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6666 static SDValue
6667 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6668                                 const EVT PtrVT) {
6669   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6670                     X86::RAX, X86II::MO_TLSGD);
6671 }
6672
6673 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6674 // "local exec" model.
6675 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6676                                    const EVT PtrVT, TLSModel::Model model,
6677                                    bool is64Bit) {
6678   DebugLoc dl = GA->getDebugLoc();
6679
6680   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6681   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6682                                                          is64Bit ? 257 : 256));
6683
6684   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6685                                       DAG.getIntPtrConstant(0),
6686                                       MachinePointerInfo(Ptr), false, false, 0);
6687
6688   unsigned char OperandFlags = 0;
6689   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6690   // initialexec.
6691   unsigned WrapperKind = X86ISD::Wrapper;
6692   if (model == TLSModel::LocalExec) {
6693     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6694   } else if (is64Bit) {
6695     assert(model == TLSModel::InitialExec);
6696     OperandFlags = X86II::MO_GOTTPOFF;
6697     WrapperKind = X86ISD::WrapperRIP;
6698   } else {
6699     assert(model == TLSModel::InitialExec);
6700     OperandFlags = X86II::MO_INDNTPOFF;
6701   }
6702
6703   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6704   // exec)
6705   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6706                                            GA->getValueType(0),
6707                                            GA->getOffset(), OperandFlags);
6708   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6709
6710   if (model == TLSModel::InitialExec)
6711     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6712                          MachinePointerInfo::getGOT(), false, false, 0);
6713
6714   // The address of the thread local variable is the add of the thread
6715   // pointer with the offset of the variable.
6716   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6717 }
6718
6719 SDValue
6720 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6721
6722   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6723   const GlobalValue *GV = GA->getGlobal();
6724
6725   if (Subtarget->isTargetELF()) {
6726     // TODO: implement the "local dynamic" model
6727     // TODO: implement the "initial exec"model for pic executables
6728
6729     // If GV is an alias then use the aliasee for determining
6730     // thread-localness.
6731     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6732       GV = GA->resolveAliasedGlobal(false);
6733
6734     TLSModel::Model model
6735       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6736
6737     switch (model) {
6738       case TLSModel::GeneralDynamic:
6739       case TLSModel::LocalDynamic: // not implemented
6740         if (Subtarget->is64Bit())
6741           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6742         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6743
6744       case TLSModel::InitialExec:
6745       case TLSModel::LocalExec:
6746         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6747                                    Subtarget->is64Bit());
6748     }
6749   } else if (Subtarget->isTargetDarwin()) {
6750     // Darwin only has one model of TLS.  Lower to that.
6751     unsigned char OpFlag = 0;
6752     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6753                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6754
6755     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6756     // global base reg.
6757     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6758                   !Subtarget->is64Bit();
6759     if (PIC32)
6760       OpFlag = X86II::MO_TLVP_PIC_BASE;
6761     else
6762       OpFlag = X86II::MO_TLVP;
6763     DebugLoc DL = Op.getDebugLoc();
6764     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6765                                                 GA->getValueType(0),
6766                                                 GA->getOffset(), OpFlag);
6767     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6768
6769     // With PIC32, the address is actually $g + Offset.
6770     if (PIC32)
6771       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6772                            DAG.getNode(X86ISD::GlobalBaseReg,
6773                                        DebugLoc(), getPointerTy()),
6774                            Offset);
6775
6776     // Lowering the machine isd will make sure everything is in the right
6777     // location.
6778     SDValue Chain = DAG.getEntryNode();
6779     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6780     SDValue Args[] = { Chain, Offset };
6781     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6782
6783     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6784     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6785     MFI->setAdjustsStack(true);
6786
6787     // And our return value (tls address) is in the standard call return value
6788     // location.
6789     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6790     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6791   }
6792
6793   assert(false &&
6794          "TLS not implemented for this target.");
6795
6796   llvm_unreachable("Unreachable");
6797   return SDValue();
6798 }
6799
6800
6801 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6802 /// take a 2 x i32 value to shift plus a shift amount.
6803 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6804   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6805   EVT VT = Op.getValueType();
6806   unsigned VTBits = VT.getSizeInBits();
6807   DebugLoc dl = Op.getDebugLoc();
6808   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6809   SDValue ShOpLo = Op.getOperand(0);
6810   SDValue ShOpHi = Op.getOperand(1);
6811   SDValue ShAmt  = Op.getOperand(2);
6812   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6813                                      DAG.getConstant(VTBits - 1, MVT::i8))
6814                        : DAG.getConstant(0, VT);
6815
6816   SDValue Tmp2, Tmp3;
6817   if (Op.getOpcode() == ISD::SHL_PARTS) {
6818     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6819     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6820   } else {
6821     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6822     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6823   }
6824
6825   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6826                                 DAG.getConstant(VTBits, MVT::i8));
6827   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6828                              AndNode, DAG.getConstant(0, MVT::i8));
6829
6830   SDValue Hi, Lo;
6831   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6832   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6833   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6834
6835   if (Op.getOpcode() == ISD::SHL_PARTS) {
6836     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6837     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6838   } else {
6839     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6840     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6841   }
6842
6843   SDValue Ops[2] = { Lo, Hi };
6844   return DAG.getMergeValues(Ops, 2, dl);
6845 }
6846
6847 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6848                                            SelectionDAG &DAG) const {
6849   EVT SrcVT = Op.getOperand(0).getValueType();
6850
6851   if (SrcVT.isVector())
6852     return SDValue();
6853
6854   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6855          "Unknown SINT_TO_FP to lower!");
6856
6857   // These are really Legal; return the operand so the caller accepts it as
6858   // Legal.
6859   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6860     return Op;
6861   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6862       Subtarget->is64Bit()) {
6863     return Op;
6864   }
6865
6866   DebugLoc dl = Op.getDebugLoc();
6867   unsigned Size = SrcVT.getSizeInBits()/8;
6868   MachineFunction &MF = DAG.getMachineFunction();
6869   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6870   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6871   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6872                                StackSlot,
6873                                MachinePointerInfo::getFixedStack(SSFI),
6874                                false, false, 0);
6875   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6876 }
6877
6878 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6879                                      SDValue StackSlot,
6880                                      SelectionDAG &DAG) const {
6881   // Build the FILD
6882   DebugLoc DL = Op.getDebugLoc();
6883   SDVTList Tys;
6884   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6885   if (useSSE)
6886     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6887   else
6888     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6889
6890   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6891
6892   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6893   MachineMemOperand *MMO;
6894   if (FI) {
6895     int SSFI = FI->getIndex();
6896     MMO =
6897       DAG.getMachineFunction()
6898       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6899                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6900   } else {
6901     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6902     StackSlot = StackSlot.getOperand(1);
6903   }
6904   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6905   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6906                                            X86ISD::FILD, DL,
6907                                            Tys, Ops, array_lengthof(Ops),
6908                                            SrcVT, MMO);
6909
6910   if (useSSE) {
6911     Chain = Result.getValue(1);
6912     SDValue InFlag = Result.getValue(2);
6913
6914     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6915     // shouldn't be necessary except that RFP cannot be live across
6916     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6917     MachineFunction &MF = DAG.getMachineFunction();
6918     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6919     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6920     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6921     Tys = DAG.getVTList(MVT::Other);
6922     SDValue Ops[] = {
6923       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6924     };
6925     MachineMemOperand *MMO =
6926       DAG.getMachineFunction()
6927       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6928                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6929
6930     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6931                                     Ops, array_lengthof(Ops),
6932                                     Op.getValueType(), MMO);
6933     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6934                          MachinePointerInfo::getFixedStack(SSFI),
6935                          false, false, 0);
6936   }
6937
6938   return Result;
6939 }
6940
6941 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6942 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6943                                                SelectionDAG &DAG) const {
6944   // This algorithm is not obvious. Here it is in C code, more or less:
6945   /*
6946     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6947       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6948       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6949
6950       // Copy ints to xmm registers.
6951       __m128i xh = _mm_cvtsi32_si128( hi );
6952       __m128i xl = _mm_cvtsi32_si128( lo );
6953
6954       // Combine into low half of a single xmm register.
6955       __m128i x = _mm_unpacklo_epi32( xh, xl );
6956       __m128d d;
6957       double sd;
6958
6959       // Merge in appropriate exponents to give the integer bits the right
6960       // magnitude.
6961       x = _mm_unpacklo_epi32( x, exp );
6962
6963       // Subtract away the biases to deal with the IEEE-754 double precision
6964       // implicit 1.
6965       d = _mm_sub_pd( (__m128d) x, bias );
6966
6967       // All conversions up to here are exact. The correctly rounded result is
6968       // calculated using the current rounding mode using the following
6969       // horizontal add.
6970       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6971       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6972                                 // store doesn't really need to be here (except
6973                                 // maybe to zero the other double)
6974       return sd;
6975     }
6976   */
6977
6978   DebugLoc dl = Op.getDebugLoc();
6979   LLVMContext *Context = DAG.getContext();
6980
6981   // Build some magic constants.
6982   std::vector<Constant*> CV0;
6983   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6984   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6985   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6986   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6987   Constant *C0 = ConstantVector::get(CV0);
6988   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6989
6990   std::vector<Constant*> CV1;
6991   CV1.push_back(
6992     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6993   CV1.push_back(
6994     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6995   Constant *C1 = ConstantVector::get(CV1);
6996   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6997
6998   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6999                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7000                                         Op.getOperand(0),
7001                                         DAG.getIntPtrConstant(1)));
7002   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7003                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7004                                         Op.getOperand(0),
7005                                         DAG.getIntPtrConstant(0)));
7006   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7007   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7008                               MachinePointerInfo::getConstantPool(),
7009                               false, false, 16);
7010   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7011   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7012   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7013                               MachinePointerInfo::getConstantPool(),
7014                               false, false, 16);
7015   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7016
7017   // Add the halves; easiest way is to swap them into another reg first.
7018   int ShufMask[2] = { 1, -1 };
7019   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7020                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7021   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7022   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7023                      DAG.getIntPtrConstant(0));
7024 }
7025
7026 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7027 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7028                                                SelectionDAG &DAG) const {
7029   DebugLoc dl = Op.getDebugLoc();
7030   // FP constant to bias correct the final result.
7031   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7032                                    MVT::f64);
7033
7034   // Load the 32-bit value into an XMM register.
7035   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7036                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7037                                          Op.getOperand(0),
7038                                          DAG.getIntPtrConstant(0)));
7039
7040   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7041                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7042                      DAG.getIntPtrConstant(0));
7043
7044   // Or the load with the bias.
7045   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7046                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7047                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7048                                                    MVT::v2f64, Load)),
7049                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7050                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7051                                                    MVT::v2f64, Bias)));
7052   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7053                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7054                    DAG.getIntPtrConstant(0));
7055
7056   // Subtract the bias.
7057   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7058
7059   // Handle final rounding.
7060   EVT DestVT = Op.getValueType();
7061
7062   if (DestVT.bitsLT(MVT::f64)) {
7063     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7064                        DAG.getIntPtrConstant(0));
7065   } else if (DestVT.bitsGT(MVT::f64)) {
7066     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7067   }
7068
7069   // Handle final rounding.
7070   return Sub;
7071 }
7072
7073 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7074                                            SelectionDAG &DAG) const {
7075   SDValue N0 = Op.getOperand(0);
7076   DebugLoc dl = Op.getDebugLoc();
7077
7078   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7079   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7080   // the optimization here.
7081   if (DAG.SignBitIsZero(N0))
7082     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7083
7084   EVT SrcVT = N0.getValueType();
7085   EVT DstVT = Op.getValueType();
7086   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7087     return LowerUINT_TO_FP_i64(Op, DAG);
7088   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7089     return LowerUINT_TO_FP_i32(Op, DAG);
7090
7091   // Make a 64-bit buffer, and use it to build an FILD.
7092   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7093   if (SrcVT == MVT::i32) {
7094     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7095     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7096                                      getPointerTy(), StackSlot, WordOff);
7097     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7098                                   StackSlot, MachinePointerInfo(),
7099                                   false, false, 0);
7100     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7101                                   OffsetSlot, MachinePointerInfo(),
7102                                   false, false, 0);
7103     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7104     return Fild;
7105   }
7106
7107   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7108   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7109                                 StackSlot, MachinePointerInfo(),
7110                                false, false, 0);
7111   // For i64 source, we need to add the appropriate power of 2 if the input
7112   // was negative.  This is the same as the optimization in
7113   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7114   // we must be careful to do the computation in x87 extended precision, not
7115   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7116   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7117   MachineMemOperand *MMO =
7118     DAG.getMachineFunction()
7119     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7120                           MachineMemOperand::MOLoad, 8, 8);
7121
7122   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7123   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7124   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7125                                          MVT::i64, MMO);
7126
7127   APInt FF(32, 0x5F800000ULL);
7128
7129   // Check whether the sign bit is set.
7130   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7131                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7132                                  ISD::SETLT);
7133
7134   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7135   SDValue FudgePtr = DAG.getConstantPool(
7136                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7137                                          getPointerTy());
7138
7139   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7140   SDValue Zero = DAG.getIntPtrConstant(0);
7141   SDValue Four = DAG.getIntPtrConstant(4);
7142   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7143                                Zero, Four);
7144   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7145
7146   // Load the value out, extending it from f32 to f80.
7147   // FIXME: Avoid the extend by constructing the right constant pool?
7148   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7149                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7150                                  MVT::f32, false, false, 4);
7151   // Extend everything to 80 bits to force it to be done on x87.
7152   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7153   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7154 }
7155
7156 std::pair<SDValue,SDValue> X86TargetLowering::
7157 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7158   DebugLoc DL = Op.getDebugLoc();
7159
7160   EVT DstTy = Op.getValueType();
7161
7162   if (!IsSigned) {
7163     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7164     DstTy = MVT::i64;
7165   }
7166
7167   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7168          DstTy.getSimpleVT() >= MVT::i16 &&
7169          "Unknown FP_TO_SINT to lower!");
7170
7171   // These are really Legal.
7172   if (DstTy == MVT::i32 &&
7173       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7174     return std::make_pair(SDValue(), SDValue());
7175   if (Subtarget->is64Bit() &&
7176       DstTy == MVT::i64 &&
7177       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7178     return std::make_pair(SDValue(), SDValue());
7179
7180   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7181   // stack slot.
7182   MachineFunction &MF = DAG.getMachineFunction();
7183   unsigned MemSize = DstTy.getSizeInBits()/8;
7184   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7185   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7186
7187
7188
7189   unsigned Opc;
7190   switch (DstTy.getSimpleVT().SimpleTy) {
7191   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7192   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7193   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7194   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7195   }
7196
7197   SDValue Chain = DAG.getEntryNode();
7198   SDValue Value = Op.getOperand(0);
7199   EVT TheVT = Op.getOperand(0).getValueType();
7200   if (isScalarFPTypeInSSEReg(TheVT)) {
7201     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7202     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7203                          MachinePointerInfo::getFixedStack(SSFI),
7204                          false, false, 0);
7205     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7206     SDValue Ops[] = {
7207       Chain, StackSlot, DAG.getValueType(TheVT)
7208     };
7209
7210     MachineMemOperand *MMO =
7211       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7212                               MachineMemOperand::MOLoad, MemSize, MemSize);
7213     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7214                                     DstTy, MMO);
7215     Chain = Value.getValue(1);
7216     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7217     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7218   }
7219
7220   MachineMemOperand *MMO =
7221     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7222                             MachineMemOperand::MOStore, MemSize, MemSize);
7223
7224   // Build the FP_TO_INT*_IN_MEM
7225   SDValue Ops[] = { Chain, Value, StackSlot };
7226   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7227                                          Ops, 3, DstTy, MMO);
7228
7229   return std::make_pair(FIST, StackSlot);
7230 }
7231
7232 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7233                                            SelectionDAG &DAG) const {
7234   if (Op.getValueType().isVector())
7235     return SDValue();
7236
7237   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7238   SDValue FIST = Vals.first, StackSlot = Vals.second;
7239   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7240   if (FIST.getNode() == 0) return Op;
7241
7242   // Load the result.
7243   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7244                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7245 }
7246
7247 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7248                                            SelectionDAG &DAG) const {
7249   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7250   SDValue FIST = Vals.first, StackSlot = Vals.second;
7251   assert(FIST.getNode() && "Unexpected failure");
7252
7253   // Load the result.
7254   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7255                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7256 }
7257
7258 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7259                                      SelectionDAG &DAG) const {
7260   LLVMContext *Context = DAG.getContext();
7261   DebugLoc dl = Op.getDebugLoc();
7262   EVT VT = Op.getValueType();
7263   EVT EltVT = VT;
7264   if (VT.isVector())
7265     EltVT = VT.getVectorElementType();
7266   std::vector<Constant*> CV;
7267   if (EltVT == MVT::f64) {
7268     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7269     CV.push_back(C);
7270     CV.push_back(C);
7271   } else {
7272     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7273     CV.push_back(C);
7274     CV.push_back(C);
7275     CV.push_back(C);
7276     CV.push_back(C);
7277   }
7278   Constant *C = ConstantVector::get(CV);
7279   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7280   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7281                              MachinePointerInfo::getConstantPool(),
7282                              false, false, 16);
7283   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7284 }
7285
7286 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7287   LLVMContext *Context = DAG.getContext();
7288   DebugLoc dl = Op.getDebugLoc();
7289   EVT VT = Op.getValueType();
7290   EVT EltVT = VT;
7291   if (VT.isVector())
7292     EltVT = VT.getVectorElementType();
7293   std::vector<Constant*> CV;
7294   if (EltVT == MVT::f64) {
7295     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7296     CV.push_back(C);
7297     CV.push_back(C);
7298   } else {
7299     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7300     CV.push_back(C);
7301     CV.push_back(C);
7302     CV.push_back(C);
7303     CV.push_back(C);
7304   }
7305   Constant *C = ConstantVector::get(CV);
7306   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7307   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7308                              MachinePointerInfo::getConstantPool(),
7309                              false, false, 16);
7310   if (VT.isVector()) {
7311     return DAG.getNode(ISD::BITCAST, dl, VT,
7312                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7313                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7314                                 Op.getOperand(0)),
7315                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7316   } else {
7317     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7318   }
7319 }
7320
7321 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7322   LLVMContext *Context = DAG.getContext();
7323   SDValue Op0 = Op.getOperand(0);
7324   SDValue Op1 = Op.getOperand(1);
7325   DebugLoc dl = Op.getDebugLoc();
7326   EVT VT = Op.getValueType();
7327   EVT SrcVT = Op1.getValueType();
7328
7329   // If second operand is smaller, extend it first.
7330   if (SrcVT.bitsLT(VT)) {
7331     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7332     SrcVT = VT;
7333   }
7334   // And if it is bigger, shrink it first.
7335   if (SrcVT.bitsGT(VT)) {
7336     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7337     SrcVT = VT;
7338   }
7339
7340   // At this point the operands and the result should have the same
7341   // type, and that won't be f80 since that is not custom lowered.
7342
7343   // First get the sign bit of second operand.
7344   std::vector<Constant*> CV;
7345   if (SrcVT == MVT::f64) {
7346     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7347     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7348   } else {
7349     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7350     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7351     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7352     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7353   }
7354   Constant *C = ConstantVector::get(CV);
7355   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7356   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7357                               MachinePointerInfo::getConstantPool(),
7358                               false, false, 16);
7359   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7360
7361   // Shift sign bit right or left if the two operands have different types.
7362   if (SrcVT.bitsGT(VT)) {
7363     // Op0 is MVT::f32, Op1 is MVT::f64.
7364     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7365     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7366                           DAG.getConstant(32, MVT::i32));
7367     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7368     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7369                           DAG.getIntPtrConstant(0));
7370   }
7371
7372   // Clear first operand sign bit.
7373   CV.clear();
7374   if (VT == MVT::f64) {
7375     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7376     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7377   } else {
7378     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7379     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7380     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7381     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7382   }
7383   C = ConstantVector::get(CV);
7384   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7385   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7386                               MachinePointerInfo::getConstantPool(),
7387                               false, false, 16);
7388   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7389
7390   // Or the value with the sign bit.
7391   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7392 }
7393
7394 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7395   SDValue N0 = Op.getOperand(0);
7396   DebugLoc dl = Op.getDebugLoc();
7397   EVT VT = Op.getValueType();
7398
7399   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7400   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7401                                   DAG.getConstant(1, VT));
7402   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7403 }
7404
7405 /// Emit nodes that will be selected as "test Op0,Op0", or something
7406 /// equivalent.
7407 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7408                                     SelectionDAG &DAG) const {
7409   DebugLoc dl = Op.getDebugLoc();
7410
7411   // CF and OF aren't always set the way we want. Determine which
7412   // of these we need.
7413   bool NeedCF = false;
7414   bool NeedOF = false;
7415   switch (X86CC) {
7416   default: break;
7417   case X86::COND_A: case X86::COND_AE:
7418   case X86::COND_B: case X86::COND_BE:
7419     NeedCF = true;
7420     break;
7421   case X86::COND_G: case X86::COND_GE:
7422   case X86::COND_L: case X86::COND_LE:
7423   case X86::COND_O: case X86::COND_NO:
7424     NeedOF = true;
7425     break;
7426   }
7427
7428   // See if we can use the EFLAGS value from the operand instead of
7429   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7430   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7431   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7432     // Emit a CMP with 0, which is the TEST pattern.
7433     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7434                        DAG.getConstant(0, Op.getValueType()));
7435
7436   unsigned Opcode = 0;
7437   unsigned NumOperands = 0;
7438   switch (Op.getNode()->getOpcode()) {
7439   case ISD::ADD:
7440     // Due to an isel shortcoming, be conservative if this add is likely to be
7441     // selected as part of a load-modify-store instruction. When the root node
7442     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7443     // uses of other nodes in the match, such as the ADD in this case. This
7444     // leads to the ADD being left around and reselected, with the result being
7445     // two adds in the output.  Alas, even if none our users are stores, that
7446     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7447     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7448     // climbing the DAG back to the root, and it doesn't seem to be worth the
7449     // effort.
7450     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7451            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7452       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7453         goto default_case;
7454
7455     if (ConstantSDNode *C =
7456         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7457       // An add of one will be selected as an INC.
7458       if (C->getAPIntValue() == 1) {
7459         Opcode = X86ISD::INC;
7460         NumOperands = 1;
7461         break;
7462       }
7463
7464       // An add of negative one (subtract of one) will be selected as a DEC.
7465       if (C->getAPIntValue().isAllOnesValue()) {
7466         Opcode = X86ISD::DEC;
7467         NumOperands = 1;
7468         break;
7469       }
7470     }
7471
7472     // Otherwise use a regular EFLAGS-setting add.
7473     Opcode = X86ISD::ADD;
7474     NumOperands = 2;
7475     break;
7476   case ISD::AND: {
7477     // If the primary and result isn't used, don't bother using X86ISD::AND,
7478     // because a TEST instruction will be better.
7479     bool NonFlagUse = false;
7480     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7481            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7482       SDNode *User = *UI;
7483       unsigned UOpNo = UI.getOperandNo();
7484       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7485         // Look pass truncate.
7486         UOpNo = User->use_begin().getOperandNo();
7487         User = *User->use_begin();
7488       }
7489
7490       if (User->getOpcode() != ISD::BRCOND &&
7491           User->getOpcode() != ISD::SETCC &&
7492           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7493         NonFlagUse = true;
7494         break;
7495       }
7496     }
7497
7498     if (!NonFlagUse)
7499       break;
7500   }
7501     // FALL THROUGH
7502   case ISD::SUB:
7503   case ISD::OR:
7504   case ISD::XOR:
7505     // Due to the ISEL shortcoming noted above, be conservative if this op is
7506     // likely to be selected as part of a load-modify-store instruction.
7507     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7508            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7509       if (UI->getOpcode() == ISD::STORE)
7510         goto default_case;
7511
7512     // Otherwise use a regular EFLAGS-setting instruction.
7513     switch (Op.getNode()->getOpcode()) {
7514     default: llvm_unreachable("unexpected operator!");
7515     case ISD::SUB: Opcode = X86ISD::SUB; break;
7516     case ISD::OR:  Opcode = X86ISD::OR;  break;
7517     case ISD::XOR: Opcode = X86ISD::XOR; break;
7518     case ISD::AND: Opcode = X86ISD::AND; break;
7519     }
7520
7521     NumOperands = 2;
7522     break;
7523   case X86ISD::ADD:
7524   case X86ISD::SUB:
7525   case X86ISD::INC:
7526   case X86ISD::DEC:
7527   case X86ISD::OR:
7528   case X86ISD::XOR:
7529   case X86ISD::AND:
7530     return SDValue(Op.getNode(), 1);
7531   default:
7532   default_case:
7533     break;
7534   }
7535
7536   if (Opcode == 0)
7537     // Emit a CMP with 0, which is the TEST pattern.
7538     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7539                        DAG.getConstant(0, Op.getValueType()));
7540
7541   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7542   SmallVector<SDValue, 4> Ops;
7543   for (unsigned i = 0; i != NumOperands; ++i)
7544     Ops.push_back(Op.getOperand(i));
7545
7546   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7547   DAG.ReplaceAllUsesWith(Op, New);
7548   return SDValue(New.getNode(), 1);
7549 }
7550
7551 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7552 /// equivalent.
7553 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7554                                    SelectionDAG &DAG) const {
7555   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7556     if (C->getAPIntValue() == 0)
7557       return EmitTest(Op0, X86CC, DAG);
7558
7559   DebugLoc dl = Op0.getDebugLoc();
7560   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7561 }
7562
7563 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7564 /// if it's possible.
7565 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7566                                      DebugLoc dl, SelectionDAG &DAG) const {
7567   SDValue Op0 = And.getOperand(0);
7568   SDValue Op1 = And.getOperand(1);
7569   if (Op0.getOpcode() == ISD::TRUNCATE)
7570     Op0 = Op0.getOperand(0);
7571   if (Op1.getOpcode() == ISD::TRUNCATE)
7572     Op1 = Op1.getOperand(0);
7573
7574   SDValue LHS, RHS;
7575   if (Op1.getOpcode() == ISD::SHL)
7576     std::swap(Op0, Op1);
7577   if (Op0.getOpcode() == ISD::SHL) {
7578     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7579       if (And00C->getZExtValue() == 1) {
7580         // If we looked past a truncate, check that it's only truncating away
7581         // known zeros.
7582         unsigned BitWidth = Op0.getValueSizeInBits();
7583         unsigned AndBitWidth = And.getValueSizeInBits();
7584         if (BitWidth > AndBitWidth) {
7585           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7586           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7587           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7588             return SDValue();
7589         }
7590         LHS = Op1;
7591         RHS = Op0.getOperand(1);
7592       }
7593   } else if (Op1.getOpcode() == ISD::Constant) {
7594     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7595     SDValue AndLHS = Op0;
7596     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7597       LHS = AndLHS.getOperand(0);
7598       RHS = AndLHS.getOperand(1);
7599     }
7600   }
7601
7602   if (LHS.getNode()) {
7603     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7604     // instruction.  Since the shift amount is in-range-or-undefined, we know
7605     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7606     // the encoding for the i16 version is larger than the i32 version.
7607     // Also promote i16 to i32 for performance / code size reason.
7608     if (LHS.getValueType() == MVT::i8 ||
7609         LHS.getValueType() == MVT::i16)
7610       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7611
7612     // If the operand types disagree, extend the shift amount to match.  Since
7613     // BT ignores high bits (like shifts) we can use anyextend.
7614     if (LHS.getValueType() != RHS.getValueType())
7615       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7616
7617     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7618     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7619     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7620                        DAG.getConstant(Cond, MVT::i8), BT);
7621   }
7622
7623   return SDValue();
7624 }
7625
7626 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7627   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7628   SDValue Op0 = Op.getOperand(0);
7629   SDValue Op1 = Op.getOperand(1);
7630   DebugLoc dl = Op.getDebugLoc();
7631   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7632
7633   // Optimize to BT if possible.
7634   // Lower (X & (1 << N)) == 0 to BT(X, N).
7635   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7636   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7637   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7638       Op1.getOpcode() == ISD::Constant &&
7639       cast<ConstantSDNode>(Op1)->isNullValue() &&
7640       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7641     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7642     if (NewSetCC.getNode())
7643       return NewSetCC;
7644   }
7645
7646   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7647   // these.
7648   if (Op1.getOpcode() == ISD::Constant &&
7649       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7650        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7651       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7652
7653     // If the input is a setcc, then reuse the input setcc or use a new one with
7654     // the inverted condition.
7655     if (Op0.getOpcode() == X86ISD::SETCC) {
7656       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7657       bool Invert = (CC == ISD::SETNE) ^
7658         cast<ConstantSDNode>(Op1)->isNullValue();
7659       if (!Invert) return Op0;
7660
7661       CCode = X86::GetOppositeBranchCondition(CCode);
7662       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7663                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7664     }
7665   }
7666
7667   bool isFP = Op1.getValueType().isFloatingPoint();
7668   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7669   if (X86CC == X86::COND_INVALID)
7670     return SDValue();
7671
7672   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7673   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7674                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7675 }
7676
7677 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7678   SDValue Cond;
7679   SDValue Op0 = Op.getOperand(0);
7680   SDValue Op1 = Op.getOperand(1);
7681   SDValue CC = Op.getOperand(2);
7682   EVT VT = Op.getValueType();
7683   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7684   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7685   DebugLoc dl = Op.getDebugLoc();
7686
7687   if (isFP) {
7688     unsigned SSECC = 8;
7689     EVT VT0 = Op0.getValueType();
7690     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7691     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7692     bool Swap = false;
7693
7694     switch (SetCCOpcode) {
7695     default: break;
7696     case ISD::SETOEQ:
7697     case ISD::SETEQ:  SSECC = 0; break;
7698     case ISD::SETOGT:
7699     case ISD::SETGT: Swap = true; // Fallthrough
7700     case ISD::SETLT:
7701     case ISD::SETOLT: SSECC = 1; break;
7702     case ISD::SETOGE:
7703     case ISD::SETGE: Swap = true; // Fallthrough
7704     case ISD::SETLE:
7705     case ISD::SETOLE: SSECC = 2; break;
7706     case ISD::SETUO:  SSECC = 3; break;
7707     case ISD::SETUNE:
7708     case ISD::SETNE:  SSECC = 4; break;
7709     case ISD::SETULE: Swap = true;
7710     case ISD::SETUGE: SSECC = 5; break;
7711     case ISD::SETULT: Swap = true;
7712     case ISD::SETUGT: SSECC = 6; break;
7713     case ISD::SETO:   SSECC = 7; break;
7714     }
7715     if (Swap)
7716       std::swap(Op0, Op1);
7717
7718     // In the two special cases we can't handle, emit two comparisons.
7719     if (SSECC == 8) {
7720       if (SetCCOpcode == ISD::SETUEQ) {
7721         SDValue UNORD, EQ;
7722         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7723         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7724         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7725       }
7726       else if (SetCCOpcode == ISD::SETONE) {
7727         SDValue ORD, NEQ;
7728         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7729         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7730         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7731       }
7732       llvm_unreachable("Illegal FP comparison");
7733     }
7734     // Handle all other FP comparisons here.
7735     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7736   }
7737
7738   // We are handling one of the integer comparisons here.  Since SSE only has
7739   // GT and EQ comparisons for integer, swapping operands and multiple
7740   // operations may be required for some comparisons.
7741   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7742   bool Swap = false, Invert = false, FlipSigns = false;
7743
7744   switch (VT.getSimpleVT().SimpleTy) {
7745   default: break;
7746   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7747   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7748   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7749   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7750   }
7751
7752   switch (SetCCOpcode) {
7753   default: break;
7754   case ISD::SETNE:  Invert = true;
7755   case ISD::SETEQ:  Opc = EQOpc; break;
7756   case ISD::SETLT:  Swap = true;
7757   case ISD::SETGT:  Opc = GTOpc; break;
7758   case ISD::SETGE:  Swap = true;
7759   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7760   case ISD::SETULT: Swap = true;
7761   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7762   case ISD::SETUGE: Swap = true;
7763   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7764   }
7765   if (Swap)
7766     std::swap(Op0, Op1);
7767
7768   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7769   // bits of the inputs before performing those operations.
7770   if (FlipSigns) {
7771     EVT EltVT = VT.getVectorElementType();
7772     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7773                                       EltVT);
7774     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7775     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7776                                     SignBits.size());
7777     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7778     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7779   }
7780
7781   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7782
7783   // If the logical-not of the result is required, perform that now.
7784   if (Invert)
7785     Result = DAG.getNOT(dl, Result, VT);
7786
7787   return Result;
7788 }
7789
7790 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7791 static bool isX86LogicalCmp(SDValue Op) {
7792   unsigned Opc = Op.getNode()->getOpcode();
7793   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7794     return true;
7795   if (Op.getResNo() == 1 &&
7796       (Opc == X86ISD::ADD ||
7797        Opc == X86ISD::SUB ||
7798        Opc == X86ISD::ADC ||
7799        Opc == X86ISD::SBB ||
7800        Opc == X86ISD::SMUL ||
7801        Opc == X86ISD::UMUL ||
7802        Opc == X86ISD::INC ||
7803        Opc == X86ISD::DEC ||
7804        Opc == X86ISD::OR ||
7805        Opc == X86ISD::XOR ||
7806        Opc == X86ISD::AND))
7807     return true;
7808
7809   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7810     return true;
7811
7812   return false;
7813 }
7814
7815 static bool isZero(SDValue V) {
7816   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7817   return C && C->isNullValue();
7818 }
7819
7820 static bool isAllOnes(SDValue V) {
7821   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7822   return C && C->isAllOnesValue();
7823 }
7824
7825 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7826   bool addTest = true;
7827   SDValue Cond  = Op.getOperand(0);
7828   SDValue Op1 = Op.getOperand(1);
7829   SDValue Op2 = Op.getOperand(2);
7830   DebugLoc DL = Op.getDebugLoc();
7831   SDValue CC;
7832
7833   if (Cond.getOpcode() == ISD::SETCC) {
7834     SDValue NewCond = LowerSETCC(Cond, DAG);
7835     if (NewCond.getNode())
7836       Cond = NewCond;
7837   }
7838
7839   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7840   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7841   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7842   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7843   if (Cond.getOpcode() == X86ISD::SETCC &&
7844       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7845       isZero(Cond.getOperand(1).getOperand(1))) {
7846     SDValue Cmp = Cond.getOperand(1);
7847
7848     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7849
7850     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7851         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7852       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7853
7854       SDValue CmpOp0 = Cmp.getOperand(0);
7855       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7856                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7857
7858       SDValue Res =   // Res = 0 or -1.
7859         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7860                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7861
7862       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7863         Res = DAG.getNOT(DL, Res, Res.getValueType());
7864
7865       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7866       if (N2C == 0 || !N2C->isNullValue())
7867         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7868       return Res;
7869     }
7870   }
7871
7872   // Look past (and (setcc_carry (cmp ...)), 1).
7873   if (Cond.getOpcode() == ISD::AND &&
7874       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7875     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7876     if (C && C->getAPIntValue() == 1)
7877       Cond = Cond.getOperand(0);
7878   }
7879
7880   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7881   // setting operand in place of the X86ISD::SETCC.
7882   if (Cond.getOpcode() == X86ISD::SETCC ||
7883       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7884     CC = Cond.getOperand(0);
7885
7886     SDValue Cmp = Cond.getOperand(1);
7887     unsigned Opc = Cmp.getOpcode();
7888     EVT VT = Op.getValueType();
7889
7890     bool IllegalFPCMov = false;
7891     if (VT.isFloatingPoint() && !VT.isVector() &&
7892         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7893       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7894
7895     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7896         Opc == X86ISD::BT) { // FIXME
7897       Cond = Cmp;
7898       addTest = false;
7899     }
7900   }
7901
7902   if (addTest) {
7903     // Look pass the truncate.
7904     if (Cond.getOpcode() == ISD::TRUNCATE)
7905       Cond = Cond.getOperand(0);
7906
7907     // We know the result of AND is compared against zero. Try to match
7908     // it to BT.
7909     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7910       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7911       if (NewSetCC.getNode()) {
7912         CC = NewSetCC.getOperand(0);
7913         Cond = NewSetCC.getOperand(1);
7914         addTest = false;
7915       }
7916     }
7917   }
7918
7919   if (addTest) {
7920     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7921     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7922   }
7923
7924   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7925   // a <  b ?  0 : -1 -> RES = setcc_carry
7926   // a >= b ? -1 :  0 -> RES = setcc_carry
7927   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7928   if (Cond.getOpcode() == X86ISD::CMP) {
7929     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7930
7931     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7932         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7933       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7934                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7935       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7936         return DAG.getNOT(DL, Res, Res.getValueType());
7937       return Res;
7938     }
7939   }
7940
7941   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7942   // condition is true.
7943   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7944   SDValue Ops[] = { Op2, Op1, CC, Cond };
7945   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7946 }
7947
7948 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7949 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7950 // from the AND / OR.
7951 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7952   Opc = Op.getOpcode();
7953   if (Opc != ISD::OR && Opc != ISD::AND)
7954     return false;
7955   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7956           Op.getOperand(0).hasOneUse() &&
7957           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7958           Op.getOperand(1).hasOneUse());
7959 }
7960
7961 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7962 // 1 and that the SETCC node has a single use.
7963 static bool isXor1OfSetCC(SDValue Op) {
7964   if (Op.getOpcode() != ISD::XOR)
7965     return false;
7966   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7967   if (N1C && N1C->getAPIntValue() == 1) {
7968     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7969       Op.getOperand(0).hasOneUse();
7970   }
7971   return false;
7972 }
7973
7974 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7975   bool addTest = true;
7976   SDValue Chain = Op.getOperand(0);
7977   SDValue Cond  = Op.getOperand(1);
7978   SDValue Dest  = Op.getOperand(2);
7979   DebugLoc dl = Op.getDebugLoc();
7980   SDValue CC;
7981
7982   if (Cond.getOpcode() == ISD::SETCC) {
7983     SDValue NewCond = LowerSETCC(Cond, DAG);
7984     if (NewCond.getNode())
7985       Cond = NewCond;
7986   }
7987 #if 0
7988   // FIXME: LowerXALUO doesn't handle these!!
7989   else if (Cond.getOpcode() == X86ISD::ADD  ||
7990            Cond.getOpcode() == X86ISD::SUB  ||
7991            Cond.getOpcode() == X86ISD::SMUL ||
7992            Cond.getOpcode() == X86ISD::UMUL)
7993     Cond = LowerXALUO(Cond, DAG);
7994 #endif
7995
7996   // Look pass (and (setcc_carry (cmp ...)), 1).
7997   if (Cond.getOpcode() == ISD::AND &&
7998       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7999     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8000     if (C && C->getAPIntValue() == 1)
8001       Cond = Cond.getOperand(0);
8002   }
8003
8004   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8005   // setting operand in place of the X86ISD::SETCC.
8006   if (Cond.getOpcode() == X86ISD::SETCC ||
8007       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8008     CC = Cond.getOperand(0);
8009
8010     SDValue Cmp = Cond.getOperand(1);
8011     unsigned Opc = Cmp.getOpcode();
8012     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8013     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8014       Cond = Cmp;
8015       addTest = false;
8016     } else {
8017       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8018       default: break;
8019       case X86::COND_O:
8020       case X86::COND_B:
8021         // These can only come from an arithmetic instruction with overflow,
8022         // e.g. SADDO, UADDO.
8023         Cond = Cond.getNode()->getOperand(1);
8024         addTest = false;
8025         break;
8026       }
8027     }
8028   } else {
8029     unsigned CondOpc;
8030     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8031       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8032       if (CondOpc == ISD::OR) {
8033         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8034         // two branches instead of an explicit OR instruction with a
8035         // separate test.
8036         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8037             isX86LogicalCmp(Cmp)) {
8038           CC = Cond.getOperand(0).getOperand(0);
8039           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8040                               Chain, Dest, CC, Cmp);
8041           CC = Cond.getOperand(1).getOperand(0);
8042           Cond = Cmp;
8043           addTest = false;
8044         }
8045       } else { // ISD::AND
8046         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8047         // two branches instead of an explicit AND instruction with a
8048         // separate test. However, we only do this if this block doesn't
8049         // have a fall-through edge, because this requires an explicit
8050         // jmp when the condition is false.
8051         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8052             isX86LogicalCmp(Cmp) &&
8053             Op.getNode()->hasOneUse()) {
8054           X86::CondCode CCode =
8055             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8056           CCode = X86::GetOppositeBranchCondition(CCode);
8057           CC = DAG.getConstant(CCode, MVT::i8);
8058           SDNode *User = *Op.getNode()->use_begin();
8059           // Look for an unconditional branch following this conditional branch.
8060           // We need this because we need to reverse the successors in order
8061           // to implement FCMP_OEQ.
8062           if (User->getOpcode() == ISD::BR) {
8063             SDValue FalseBB = User->getOperand(1);
8064             SDNode *NewBR =
8065               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8066             assert(NewBR == User);
8067             (void)NewBR;
8068             Dest = FalseBB;
8069
8070             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8071                                 Chain, Dest, CC, Cmp);
8072             X86::CondCode CCode =
8073               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8074             CCode = X86::GetOppositeBranchCondition(CCode);
8075             CC = DAG.getConstant(CCode, MVT::i8);
8076             Cond = Cmp;
8077             addTest = false;
8078           }
8079         }
8080       }
8081     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8082       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8083       // It should be transformed during dag combiner except when the condition
8084       // is set by a arithmetics with overflow node.
8085       X86::CondCode CCode =
8086         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8087       CCode = X86::GetOppositeBranchCondition(CCode);
8088       CC = DAG.getConstant(CCode, MVT::i8);
8089       Cond = Cond.getOperand(0).getOperand(1);
8090       addTest = false;
8091     }
8092   }
8093
8094   if (addTest) {
8095     // Look pass the truncate.
8096     if (Cond.getOpcode() == ISD::TRUNCATE)
8097       Cond = Cond.getOperand(0);
8098
8099     // We know the result of AND is compared against zero. Try to match
8100     // it to BT.
8101     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8102       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8103       if (NewSetCC.getNode()) {
8104         CC = NewSetCC.getOperand(0);
8105         Cond = NewSetCC.getOperand(1);
8106         addTest = false;
8107       }
8108     }
8109   }
8110
8111   if (addTest) {
8112     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8113     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8114   }
8115   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8116                      Chain, Dest, CC, Cond);
8117 }
8118
8119
8120 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8121 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8122 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8123 // that the guard pages used by the OS virtual memory manager are allocated in
8124 // correct sequence.
8125 SDValue
8126 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8127                                            SelectionDAG &DAG) const {
8128   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8129          "This should be used only on Windows targets");
8130   assert(!Subtarget->isTargetEnvMacho());
8131   DebugLoc dl = Op.getDebugLoc();
8132
8133   // Get the inputs.
8134   SDValue Chain = Op.getOperand(0);
8135   SDValue Size  = Op.getOperand(1);
8136   // FIXME: Ensure alignment here
8137
8138   SDValue Flag;
8139
8140   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8141   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8142
8143   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8144   Flag = Chain.getValue(1);
8145
8146   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8147
8148   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8149   Flag = Chain.getValue(1);
8150
8151   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8152
8153   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8154   return DAG.getMergeValues(Ops1, 2, dl);
8155 }
8156
8157 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8158   MachineFunction &MF = DAG.getMachineFunction();
8159   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8160
8161   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8162   DebugLoc DL = Op.getDebugLoc();
8163
8164   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8165     // vastart just stores the address of the VarArgsFrameIndex slot into the
8166     // memory location argument.
8167     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8168                                    getPointerTy());
8169     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8170                         MachinePointerInfo(SV), false, false, 0);
8171   }
8172
8173   // __va_list_tag:
8174   //   gp_offset         (0 - 6 * 8)
8175   //   fp_offset         (48 - 48 + 8 * 16)
8176   //   overflow_arg_area (point to parameters coming in memory).
8177   //   reg_save_area
8178   SmallVector<SDValue, 8> MemOps;
8179   SDValue FIN = Op.getOperand(1);
8180   // Store gp_offset
8181   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8182                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8183                                                MVT::i32),
8184                                FIN, MachinePointerInfo(SV), false, false, 0);
8185   MemOps.push_back(Store);
8186
8187   // Store fp_offset
8188   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8189                     FIN, DAG.getIntPtrConstant(4));
8190   Store = DAG.getStore(Op.getOperand(0), DL,
8191                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8192                                        MVT::i32),
8193                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8194   MemOps.push_back(Store);
8195
8196   // Store ptr to overflow_arg_area
8197   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8198                     FIN, DAG.getIntPtrConstant(4));
8199   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8200                                     getPointerTy());
8201   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8202                        MachinePointerInfo(SV, 8),
8203                        false, false, 0);
8204   MemOps.push_back(Store);
8205
8206   // Store ptr to reg_save_area.
8207   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8208                     FIN, DAG.getIntPtrConstant(8));
8209   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8210                                     getPointerTy());
8211   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8212                        MachinePointerInfo(SV, 16), false, false, 0);
8213   MemOps.push_back(Store);
8214   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8215                      &MemOps[0], MemOps.size());
8216 }
8217
8218 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8219   assert(Subtarget->is64Bit() &&
8220          "LowerVAARG only handles 64-bit va_arg!");
8221   assert((Subtarget->isTargetLinux() ||
8222           Subtarget->isTargetDarwin()) &&
8223           "Unhandled target in LowerVAARG");
8224   assert(Op.getNode()->getNumOperands() == 4);
8225   SDValue Chain = Op.getOperand(0);
8226   SDValue SrcPtr = Op.getOperand(1);
8227   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8228   unsigned Align = Op.getConstantOperandVal(3);
8229   DebugLoc dl = Op.getDebugLoc();
8230
8231   EVT ArgVT = Op.getNode()->getValueType(0);
8232   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8233   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8234   uint8_t ArgMode;
8235
8236   // Decide which area this value should be read from.
8237   // TODO: Implement the AMD64 ABI in its entirety. This simple
8238   // selection mechanism works only for the basic types.
8239   if (ArgVT == MVT::f80) {
8240     llvm_unreachable("va_arg for f80 not yet implemented");
8241   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8242     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8243   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8244     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8245   } else {
8246     llvm_unreachable("Unhandled argument type in LowerVAARG");
8247   }
8248
8249   if (ArgMode == 2) {
8250     // Sanity Check: Make sure using fp_offset makes sense.
8251     assert(!UseSoftFloat &&
8252            !(DAG.getMachineFunction()
8253                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8254            Subtarget->hasXMM());
8255   }
8256
8257   // Insert VAARG_64 node into the DAG
8258   // VAARG_64 returns two values: Variable Argument Address, Chain
8259   SmallVector<SDValue, 11> InstOps;
8260   InstOps.push_back(Chain);
8261   InstOps.push_back(SrcPtr);
8262   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8263   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8264   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8265   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8266   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8267                                           VTs, &InstOps[0], InstOps.size(),
8268                                           MVT::i64,
8269                                           MachinePointerInfo(SV),
8270                                           /*Align=*/0,
8271                                           /*Volatile=*/false,
8272                                           /*ReadMem=*/true,
8273                                           /*WriteMem=*/true);
8274   Chain = VAARG.getValue(1);
8275
8276   // Load the next argument and return it
8277   return DAG.getLoad(ArgVT, dl,
8278                      Chain,
8279                      VAARG,
8280                      MachinePointerInfo(),
8281                      false, false, 0);
8282 }
8283
8284 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8285   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8286   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8287   SDValue Chain = Op.getOperand(0);
8288   SDValue DstPtr = Op.getOperand(1);
8289   SDValue SrcPtr = Op.getOperand(2);
8290   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8291   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8292   DebugLoc DL = Op.getDebugLoc();
8293
8294   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8295                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8296                        false,
8297                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8298 }
8299
8300 SDValue
8301 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8302   DebugLoc dl = Op.getDebugLoc();
8303   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8304   switch (IntNo) {
8305   default: return SDValue();    // Don't custom lower most intrinsics.
8306   // Comparison intrinsics.
8307   case Intrinsic::x86_sse_comieq_ss:
8308   case Intrinsic::x86_sse_comilt_ss:
8309   case Intrinsic::x86_sse_comile_ss:
8310   case Intrinsic::x86_sse_comigt_ss:
8311   case Intrinsic::x86_sse_comige_ss:
8312   case Intrinsic::x86_sse_comineq_ss:
8313   case Intrinsic::x86_sse_ucomieq_ss:
8314   case Intrinsic::x86_sse_ucomilt_ss:
8315   case Intrinsic::x86_sse_ucomile_ss:
8316   case Intrinsic::x86_sse_ucomigt_ss:
8317   case Intrinsic::x86_sse_ucomige_ss:
8318   case Intrinsic::x86_sse_ucomineq_ss:
8319   case Intrinsic::x86_sse2_comieq_sd:
8320   case Intrinsic::x86_sse2_comilt_sd:
8321   case Intrinsic::x86_sse2_comile_sd:
8322   case Intrinsic::x86_sse2_comigt_sd:
8323   case Intrinsic::x86_sse2_comige_sd:
8324   case Intrinsic::x86_sse2_comineq_sd:
8325   case Intrinsic::x86_sse2_ucomieq_sd:
8326   case Intrinsic::x86_sse2_ucomilt_sd:
8327   case Intrinsic::x86_sse2_ucomile_sd:
8328   case Intrinsic::x86_sse2_ucomigt_sd:
8329   case Intrinsic::x86_sse2_ucomige_sd:
8330   case Intrinsic::x86_sse2_ucomineq_sd: {
8331     unsigned Opc = 0;
8332     ISD::CondCode CC = ISD::SETCC_INVALID;
8333     switch (IntNo) {
8334     default: break;
8335     case Intrinsic::x86_sse_comieq_ss:
8336     case Intrinsic::x86_sse2_comieq_sd:
8337       Opc = X86ISD::COMI;
8338       CC = ISD::SETEQ;
8339       break;
8340     case Intrinsic::x86_sse_comilt_ss:
8341     case Intrinsic::x86_sse2_comilt_sd:
8342       Opc = X86ISD::COMI;
8343       CC = ISD::SETLT;
8344       break;
8345     case Intrinsic::x86_sse_comile_ss:
8346     case Intrinsic::x86_sse2_comile_sd:
8347       Opc = X86ISD::COMI;
8348       CC = ISD::SETLE;
8349       break;
8350     case Intrinsic::x86_sse_comigt_ss:
8351     case Intrinsic::x86_sse2_comigt_sd:
8352       Opc = X86ISD::COMI;
8353       CC = ISD::SETGT;
8354       break;
8355     case Intrinsic::x86_sse_comige_ss:
8356     case Intrinsic::x86_sse2_comige_sd:
8357       Opc = X86ISD::COMI;
8358       CC = ISD::SETGE;
8359       break;
8360     case Intrinsic::x86_sse_comineq_ss:
8361     case Intrinsic::x86_sse2_comineq_sd:
8362       Opc = X86ISD::COMI;
8363       CC = ISD::SETNE;
8364       break;
8365     case Intrinsic::x86_sse_ucomieq_ss:
8366     case Intrinsic::x86_sse2_ucomieq_sd:
8367       Opc = X86ISD::UCOMI;
8368       CC = ISD::SETEQ;
8369       break;
8370     case Intrinsic::x86_sse_ucomilt_ss:
8371     case Intrinsic::x86_sse2_ucomilt_sd:
8372       Opc = X86ISD::UCOMI;
8373       CC = ISD::SETLT;
8374       break;
8375     case Intrinsic::x86_sse_ucomile_ss:
8376     case Intrinsic::x86_sse2_ucomile_sd:
8377       Opc = X86ISD::UCOMI;
8378       CC = ISD::SETLE;
8379       break;
8380     case Intrinsic::x86_sse_ucomigt_ss:
8381     case Intrinsic::x86_sse2_ucomigt_sd:
8382       Opc = X86ISD::UCOMI;
8383       CC = ISD::SETGT;
8384       break;
8385     case Intrinsic::x86_sse_ucomige_ss:
8386     case Intrinsic::x86_sse2_ucomige_sd:
8387       Opc = X86ISD::UCOMI;
8388       CC = ISD::SETGE;
8389       break;
8390     case Intrinsic::x86_sse_ucomineq_ss:
8391     case Intrinsic::x86_sse2_ucomineq_sd:
8392       Opc = X86ISD::UCOMI;
8393       CC = ISD::SETNE;
8394       break;
8395     }
8396
8397     SDValue LHS = Op.getOperand(1);
8398     SDValue RHS = Op.getOperand(2);
8399     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8400     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8401     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8402     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8403                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8404     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8405   }
8406   // ptest and testp intrinsics. The intrinsic these come from are designed to
8407   // return an integer value, not just an instruction so lower it to the ptest
8408   // or testp pattern and a setcc for the result.
8409   case Intrinsic::x86_sse41_ptestz:
8410   case Intrinsic::x86_sse41_ptestc:
8411   case Intrinsic::x86_sse41_ptestnzc:
8412   case Intrinsic::x86_avx_ptestz_256:
8413   case Intrinsic::x86_avx_ptestc_256:
8414   case Intrinsic::x86_avx_ptestnzc_256:
8415   case Intrinsic::x86_avx_vtestz_ps:
8416   case Intrinsic::x86_avx_vtestc_ps:
8417   case Intrinsic::x86_avx_vtestnzc_ps:
8418   case Intrinsic::x86_avx_vtestz_pd:
8419   case Intrinsic::x86_avx_vtestc_pd:
8420   case Intrinsic::x86_avx_vtestnzc_pd:
8421   case Intrinsic::x86_avx_vtestz_ps_256:
8422   case Intrinsic::x86_avx_vtestc_ps_256:
8423   case Intrinsic::x86_avx_vtestnzc_ps_256:
8424   case Intrinsic::x86_avx_vtestz_pd_256:
8425   case Intrinsic::x86_avx_vtestc_pd_256:
8426   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8427     bool IsTestPacked = false;
8428     unsigned X86CC = 0;
8429     switch (IntNo) {
8430     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8431     case Intrinsic::x86_avx_vtestz_ps:
8432     case Intrinsic::x86_avx_vtestz_pd:
8433     case Intrinsic::x86_avx_vtestz_ps_256:
8434     case Intrinsic::x86_avx_vtestz_pd_256:
8435       IsTestPacked = true; // Fallthrough
8436     case Intrinsic::x86_sse41_ptestz:
8437     case Intrinsic::x86_avx_ptestz_256:
8438       // ZF = 1
8439       X86CC = X86::COND_E;
8440       break;
8441     case Intrinsic::x86_avx_vtestc_ps:
8442     case Intrinsic::x86_avx_vtestc_pd:
8443     case Intrinsic::x86_avx_vtestc_ps_256:
8444     case Intrinsic::x86_avx_vtestc_pd_256:
8445       IsTestPacked = true; // Fallthrough
8446     case Intrinsic::x86_sse41_ptestc:
8447     case Intrinsic::x86_avx_ptestc_256:
8448       // CF = 1
8449       X86CC = X86::COND_B;
8450       break;
8451     case Intrinsic::x86_avx_vtestnzc_ps:
8452     case Intrinsic::x86_avx_vtestnzc_pd:
8453     case Intrinsic::x86_avx_vtestnzc_ps_256:
8454     case Intrinsic::x86_avx_vtestnzc_pd_256:
8455       IsTestPacked = true; // Fallthrough
8456     case Intrinsic::x86_sse41_ptestnzc:
8457     case Intrinsic::x86_avx_ptestnzc_256:
8458       // ZF and CF = 0
8459       X86CC = X86::COND_A;
8460       break;
8461     }
8462
8463     SDValue LHS = Op.getOperand(1);
8464     SDValue RHS = Op.getOperand(2);
8465     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8466     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8467     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8468     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8469     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8470   }
8471
8472   // Fix vector shift instructions where the last operand is a non-immediate
8473   // i32 value.
8474   case Intrinsic::x86_sse2_pslli_w:
8475   case Intrinsic::x86_sse2_pslli_d:
8476   case Intrinsic::x86_sse2_pslli_q:
8477   case Intrinsic::x86_sse2_psrli_w:
8478   case Intrinsic::x86_sse2_psrli_d:
8479   case Intrinsic::x86_sse2_psrli_q:
8480   case Intrinsic::x86_sse2_psrai_w:
8481   case Intrinsic::x86_sse2_psrai_d:
8482   case Intrinsic::x86_mmx_pslli_w:
8483   case Intrinsic::x86_mmx_pslli_d:
8484   case Intrinsic::x86_mmx_pslli_q:
8485   case Intrinsic::x86_mmx_psrli_w:
8486   case Intrinsic::x86_mmx_psrli_d:
8487   case Intrinsic::x86_mmx_psrli_q:
8488   case Intrinsic::x86_mmx_psrai_w:
8489   case Intrinsic::x86_mmx_psrai_d: {
8490     SDValue ShAmt = Op.getOperand(2);
8491     if (isa<ConstantSDNode>(ShAmt))
8492       return SDValue();
8493
8494     unsigned NewIntNo = 0;
8495     EVT ShAmtVT = MVT::v4i32;
8496     switch (IntNo) {
8497     case Intrinsic::x86_sse2_pslli_w:
8498       NewIntNo = Intrinsic::x86_sse2_psll_w;
8499       break;
8500     case Intrinsic::x86_sse2_pslli_d:
8501       NewIntNo = Intrinsic::x86_sse2_psll_d;
8502       break;
8503     case Intrinsic::x86_sse2_pslli_q:
8504       NewIntNo = Intrinsic::x86_sse2_psll_q;
8505       break;
8506     case Intrinsic::x86_sse2_psrli_w:
8507       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8508       break;
8509     case Intrinsic::x86_sse2_psrli_d:
8510       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8511       break;
8512     case Intrinsic::x86_sse2_psrli_q:
8513       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8514       break;
8515     case Intrinsic::x86_sse2_psrai_w:
8516       NewIntNo = Intrinsic::x86_sse2_psra_w;
8517       break;
8518     case Intrinsic::x86_sse2_psrai_d:
8519       NewIntNo = Intrinsic::x86_sse2_psra_d;
8520       break;
8521     default: {
8522       ShAmtVT = MVT::v2i32;
8523       switch (IntNo) {
8524       case Intrinsic::x86_mmx_pslli_w:
8525         NewIntNo = Intrinsic::x86_mmx_psll_w;
8526         break;
8527       case Intrinsic::x86_mmx_pslli_d:
8528         NewIntNo = Intrinsic::x86_mmx_psll_d;
8529         break;
8530       case Intrinsic::x86_mmx_pslli_q:
8531         NewIntNo = Intrinsic::x86_mmx_psll_q;
8532         break;
8533       case Intrinsic::x86_mmx_psrli_w:
8534         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8535         break;
8536       case Intrinsic::x86_mmx_psrli_d:
8537         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8538         break;
8539       case Intrinsic::x86_mmx_psrli_q:
8540         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8541         break;
8542       case Intrinsic::x86_mmx_psrai_w:
8543         NewIntNo = Intrinsic::x86_mmx_psra_w;
8544         break;
8545       case Intrinsic::x86_mmx_psrai_d:
8546         NewIntNo = Intrinsic::x86_mmx_psra_d;
8547         break;
8548       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8549       }
8550       break;
8551     }
8552     }
8553
8554     // The vector shift intrinsics with scalars uses 32b shift amounts but
8555     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8556     // to be zero.
8557     SDValue ShOps[4];
8558     ShOps[0] = ShAmt;
8559     ShOps[1] = DAG.getConstant(0, MVT::i32);
8560     if (ShAmtVT == MVT::v4i32) {
8561       ShOps[2] = DAG.getUNDEF(MVT::i32);
8562       ShOps[3] = DAG.getUNDEF(MVT::i32);
8563       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8564     } else {
8565       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8566 // FIXME this must be lowered to get rid of the invalid type.
8567     }
8568
8569     EVT VT = Op.getValueType();
8570     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8571     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8572                        DAG.getConstant(NewIntNo, MVT::i32),
8573                        Op.getOperand(1), ShAmt);
8574   }
8575   }
8576 }
8577
8578 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8579                                            SelectionDAG &DAG) const {
8580   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8581   MFI->setReturnAddressIsTaken(true);
8582
8583   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8584   DebugLoc dl = Op.getDebugLoc();
8585
8586   if (Depth > 0) {
8587     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8588     SDValue Offset =
8589       DAG.getConstant(TD->getPointerSize(),
8590                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8591     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8592                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8593                                    FrameAddr, Offset),
8594                        MachinePointerInfo(), false, false, 0);
8595   }
8596
8597   // Just load the return address.
8598   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8599   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8600                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8601 }
8602
8603 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8604   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8605   MFI->setFrameAddressIsTaken(true);
8606
8607   EVT VT = Op.getValueType();
8608   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8609   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8610   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8611   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8612   while (Depth--)
8613     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8614                             MachinePointerInfo(),
8615                             false, false, 0);
8616   return FrameAddr;
8617 }
8618
8619 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8620                                                      SelectionDAG &DAG) const {
8621   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8622 }
8623
8624 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8625   MachineFunction &MF = DAG.getMachineFunction();
8626   SDValue Chain     = Op.getOperand(0);
8627   SDValue Offset    = Op.getOperand(1);
8628   SDValue Handler   = Op.getOperand(2);
8629   DebugLoc dl       = Op.getDebugLoc();
8630
8631   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8632                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8633                                      getPointerTy());
8634   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8635
8636   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8637                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8638   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8639   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8640                        false, false, 0);
8641   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8642   MF.getRegInfo().addLiveOut(StoreAddrReg);
8643
8644   return DAG.getNode(X86ISD::EH_RETURN, dl,
8645                      MVT::Other,
8646                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8647 }
8648
8649 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8650                                              SelectionDAG &DAG) const {
8651   SDValue Root = Op.getOperand(0);
8652   SDValue Trmp = Op.getOperand(1); // trampoline
8653   SDValue FPtr = Op.getOperand(2); // nested function
8654   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8655   DebugLoc dl  = Op.getDebugLoc();
8656
8657   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8658
8659   if (Subtarget->is64Bit()) {
8660     SDValue OutChains[6];
8661
8662     // Large code-model.
8663     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8664     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8665
8666     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8667     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8668
8669     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8670
8671     // Load the pointer to the nested function into R11.
8672     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8673     SDValue Addr = Trmp;
8674     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8675                                 Addr, MachinePointerInfo(TrmpAddr),
8676                                 false, false, 0);
8677
8678     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8679                        DAG.getConstant(2, MVT::i64));
8680     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8681                                 MachinePointerInfo(TrmpAddr, 2),
8682                                 false, false, 2);
8683
8684     // Load the 'nest' parameter value into R10.
8685     // R10 is specified in X86CallingConv.td
8686     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8687     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8688                        DAG.getConstant(10, MVT::i64));
8689     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8690                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8691                                 false, false, 0);
8692
8693     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8694                        DAG.getConstant(12, MVT::i64));
8695     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8696                                 MachinePointerInfo(TrmpAddr, 12),
8697                                 false, false, 2);
8698
8699     // Jump to the nested function.
8700     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8701     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8702                        DAG.getConstant(20, MVT::i64));
8703     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8704                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8705                                 false, false, 0);
8706
8707     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8708     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8709                        DAG.getConstant(22, MVT::i64));
8710     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8711                                 MachinePointerInfo(TrmpAddr, 22),
8712                                 false, false, 0);
8713
8714     SDValue Ops[] =
8715       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8716     return DAG.getMergeValues(Ops, 2, dl);
8717   } else {
8718     const Function *Func =
8719       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8720     CallingConv::ID CC = Func->getCallingConv();
8721     unsigned NestReg;
8722
8723     switch (CC) {
8724     default:
8725       llvm_unreachable("Unsupported calling convention");
8726     case CallingConv::C:
8727     case CallingConv::X86_StdCall: {
8728       // Pass 'nest' parameter in ECX.
8729       // Must be kept in sync with X86CallingConv.td
8730       NestReg = X86::ECX;
8731
8732       // Check that ECX wasn't needed by an 'inreg' parameter.
8733       FunctionType *FTy = Func->getFunctionType();
8734       const AttrListPtr &Attrs = Func->getAttributes();
8735
8736       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8737         unsigned InRegCount = 0;
8738         unsigned Idx = 1;
8739
8740         for (FunctionType::param_iterator I = FTy->param_begin(),
8741              E = FTy->param_end(); I != E; ++I, ++Idx)
8742           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8743             // FIXME: should only count parameters that are lowered to integers.
8744             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8745
8746         if (InRegCount > 2) {
8747           report_fatal_error("Nest register in use - reduce number of inreg"
8748                              " parameters!");
8749         }
8750       }
8751       break;
8752     }
8753     case CallingConv::X86_FastCall:
8754     case CallingConv::X86_ThisCall:
8755     case CallingConv::Fast:
8756       // Pass 'nest' parameter in EAX.
8757       // Must be kept in sync with X86CallingConv.td
8758       NestReg = X86::EAX;
8759       break;
8760     }
8761
8762     SDValue OutChains[4];
8763     SDValue Addr, Disp;
8764
8765     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8766                        DAG.getConstant(10, MVT::i32));
8767     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8768
8769     // This is storing the opcode for MOV32ri.
8770     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8771     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
8772     OutChains[0] = DAG.getStore(Root, dl,
8773                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8774                                 Trmp, MachinePointerInfo(TrmpAddr),
8775                                 false, false, 0);
8776
8777     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8778                        DAG.getConstant(1, MVT::i32));
8779     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8780                                 MachinePointerInfo(TrmpAddr, 1),
8781                                 false, false, 1);
8782
8783     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8784     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8785                        DAG.getConstant(5, MVT::i32));
8786     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8787                                 MachinePointerInfo(TrmpAddr, 5),
8788                                 false, false, 1);
8789
8790     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8791                        DAG.getConstant(6, MVT::i32));
8792     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8793                                 MachinePointerInfo(TrmpAddr, 6),
8794                                 false, false, 1);
8795
8796     SDValue Ops[] =
8797       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8798     return DAG.getMergeValues(Ops, 2, dl);
8799   }
8800 }
8801
8802 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8803                                             SelectionDAG &DAG) const {
8804   /*
8805    The rounding mode is in bits 11:10 of FPSR, and has the following
8806    settings:
8807      00 Round to nearest
8808      01 Round to -inf
8809      10 Round to +inf
8810      11 Round to 0
8811
8812   FLT_ROUNDS, on the other hand, expects the following:
8813     -1 Undefined
8814      0 Round to 0
8815      1 Round to nearest
8816      2 Round to +inf
8817      3 Round to -inf
8818
8819   To perform the conversion, we do:
8820     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8821   */
8822
8823   MachineFunction &MF = DAG.getMachineFunction();
8824   const TargetMachine &TM = MF.getTarget();
8825   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8826   unsigned StackAlignment = TFI.getStackAlignment();
8827   EVT VT = Op.getValueType();
8828   DebugLoc DL = Op.getDebugLoc();
8829
8830   // Save FP Control Word to stack slot
8831   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8832   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8833
8834
8835   MachineMemOperand *MMO =
8836    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8837                            MachineMemOperand::MOStore, 2, 2);
8838
8839   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8840   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8841                                           DAG.getVTList(MVT::Other),
8842                                           Ops, 2, MVT::i16, MMO);
8843
8844   // Load FP Control Word from stack slot
8845   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8846                             MachinePointerInfo(), false, false, 0);
8847
8848   // Transform as necessary
8849   SDValue CWD1 =
8850     DAG.getNode(ISD::SRL, DL, MVT::i16,
8851                 DAG.getNode(ISD::AND, DL, MVT::i16,
8852                             CWD, DAG.getConstant(0x800, MVT::i16)),
8853                 DAG.getConstant(11, MVT::i8));
8854   SDValue CWD2 =
8855     DAG.getNode(ISD::SRL, DL, MVT::i16,
8856                 DAG.getNode(ISD::AND, DL, MVT::i16,
8857                             CWD, DAG.getConstant(0x400, MVT::i16)),
8858                 DAG.getConstant(9, MVT::i8));
8859
8860   SDValue RetVal =
8861     DAG.getNode(ISD::AND, DL, MVT::i16,
8862                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8863                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8864                             DAG.getConstant(1, MVT::i16)),
8865                 DAG.getConstant(3, MVT::i16));
8866
8867
8868   return DAG.getNode((VT.getSizeInBits() < 16 ?
8869                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8870 }
8871
8872 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8873   EVT VT = Op.getValueType();
8874   EVT OpVT = VT;
8875   unsigned NumBits = VT.getSizeInBits();
8876   DebugLoc dl = Op.getDebugLoc();
8877
8878   Op = Op.getOperand(0);
8879   if (VT == MVT::i8) {
8880     // Zero extend to i32 since there is not an i8 bsr.
8881     OpVT = MVT::i32;
8882     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8883   }
8884
8885   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8886   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8887   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8888
8889   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8890   SDValue Ops[] = {
8891     Op,
8892     DAG.getConstant(NumBits+NumBits-1, OpVT),
8893     DAG.getConstant(X86::COND_E, MVT::i8),
8894     Op.getValue(1)
8895   };
8896   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8897
8898   // Finally xor with NumBits-1.
8899   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8900
8901   if (VT == MVT::i8)
8902     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8903   return Op;
8904 }
8905
8906 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8907   EVT VT = Op.getValueType();
8908   EVT OpVT = VT;
8909   unsigned NumBits = VT.getSizeInBits();
8910   DebugLoc dl = Op.getDebugLoc();
8911
8912   Op = Op.getOperand(0);
8913   if (VT == MVT::i8) {
8914     OpVT = MVT::i32;
8915     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8916   }
8917
8918   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8919   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8920   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8921
8922   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8923   SDValue Ops[] = {
8924     Op,
8925     DAG.getConstant(NumBits, OpVT),
8926     DAG.getConstant(X86::COND_E, MVT::i8),
8927     Op.getValue(1)
8928   };
8929   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8930
8931   if (VT == MVT::i8)
8932     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8933   return Op;
8934 }
8935
8936 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8937   EVT VT = Op.getValueType();
8938   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8939   DebugLoc dl = Op.getDebugLoc();
8940
8941   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8942   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8943   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8944   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8945   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8946   //
8947   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8948   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8949   //  return AloBlo + AloBhi + AhiBlo;
8950
8951   SDValue A = Op.getOperand(0);
8952   SDValue B = Op.getOperand(1);
8953
8954   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8955                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8956                        A, DAG.getConstant(32, MVT::i32));
8957   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8958                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8959                        B, DAG.getConstant(32, MVT::i32));
8960   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8961                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8962                        A, B);
8963   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8964                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8965                        A, Bhi);
8966   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8967                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8968                        Ahi, B);
8969   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8970                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8971                        AloBhi, DAG.getConstant(32, MVT::i32));
8972   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8973                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8974                        AhiBlo, DAG.getConstant(32, MVT::i32));
8975   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8976   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8977   return Res;
8978 }
8979
8980 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8981
8982   EVT VT = Op.getValueType();
8983   DebugLoc dl = Op.getDebugLoc();
8984   SDValue R = Op.getOperand(0);
8985   SDValue Amt = Op.getOperand(1);
8986
8987   LLVMContext *Context = DAG.getContext();
8988
8989   // Must have SSE2.
8990   if (!Subtarget->hasSSE2()) return SDValue();
8991
8992   // Optimize shl/srl/sra with constant shift amount.
8993   if (isSplatVector(Amt.getNode())) {
8994     SDValue SclrAmt = Amt->getOperand(0);
8995     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8996       uint64_t ShiftAmt = C->getZExtValue();
8997
8998       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8999        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9000                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9001                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9002
9003       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9004        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9005                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9006                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9007
9008       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9009        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9010                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9011                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9012
9013       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9014        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9015                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9016                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9017
9018       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9019        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9020                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9021                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9022
9023       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9024        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9025                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9026                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9027
9028       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9029        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9030                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9031                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9032
9033       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9034        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9035                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9036                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9037     }
9038   }
9039
9040   // Lower SHL with variable shift amount.
9041   // Cannot lower SHL without SSE2 or later.
9042   if (!Subtarget->hasSSE2()) return SDValue();
9043
9044   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9045     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9046                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9047                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9048
9049     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9050
9051     std::vector<Constant*> CV(4, CI);
9052     Constant *C = ConstantVector::get(CV);
9053     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9054     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9055                                  MachinePointerInfo::getConstantPool(),
9056                                  false, false, 16);
9057
9058     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9059     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9060     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9061     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9062   }
9063   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9064     // a = a << 5;
9065     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9066                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9067                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9068
9069     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9070     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9071
9072     std::vector<Constant*> CVM1(16, CM1);
9073     std::vector<Constant*> CVM2(16, CM2);
9074     Constant *C = ConstantVector::get(CVM1);
9075     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9076     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9077                             MachinePointerInfo::getConstantPool(),
9078                             false, false, 16);
9079
9080     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9081     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9082     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9083                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9084                     DAG.getConstant(4, MVT::i32));
9085     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9086     // a += a
9087     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9088
9089     C = ConstantVector::get(CVM2);
9090     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9091     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9092                     MachinePointerInfo::getConstantPool(),
9093                     false, false, 16);
9094
9095     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9096     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9097     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9098                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9099                     DAG.getConstant(2, MVT::i32));
9100     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9101     // a += a
9102     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9103
9104     // return pblendv(r, r+r, a);
9105     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9106                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9107     return R;
9108   }
9109   return SDValue();
9110 }
9111
9112 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9113   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9114   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9115   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9116   // has only one use.
9117   SDNode *N = Op.getNode();
9118   SDValue LHS = N->getOperand(0);
9119   SDValue RHS = N->getOperand(1);
9120   unsigned BaseOp = 0;
9121   unsigned Cond = 0;
9122   DebugLoc DL = Op.getDebugLoc();
9123   switch (Op.getOpcode()) {
9124   default: llvm_unreachable("Unknown ovf instruction!");
9125   case ISD::SADDO:
9126     // A subtract of one will be selected as a INC. Note that INC doesn't
9127     // set CF, so we can't do this for UADDO.
9128     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9129       if (C->isOne()) {
9130         BaseOp = X86ISD::INC;
9131         Cond = X86::COND_O;
9132         break;
9133       }
9134     BaseOp = X86ISD::ADD;
9135     Cond = X86::COND_O;
9136     break;
9137   case ISD::UADDO:
9138     BaseOp = X86ISD::ADD;
9139     Cond = X86::COND_B;
9140     break;
9141   case ISD::SSUBO:
9142     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9143     // set CF, so we can't do this for USUBO.
9144     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9145       if (C->isOne()) {
9146         BaseOp = X86ISD::DEC;
9147         Cond = X86::COND_O;
9148         break;
9149       }
9150     BaseOp = X86ISD::SUB;
9151     Cond = X86::COND_O;
9152     break;
9153   case ISD::USUBO:
9154     BaseOp = X86ISD::SUB;
9155     Cond = X86::COND_B;
9156     break;
9157   case ISD::SMULO:
9158     BaseOp = X86ISD::SMUL;
9159     Cond = X86::COND_O;
9160     break;
9161   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9162     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9163                                  MVT::i32);
9164     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9165
9166     SDValue SetCC =
9167       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9168                   DAG.getConstant(X86::COND_O, MVT::i32),
9169                   SDValue(Sum.getNode(), 2));
9170
9171     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9172     return Sum;
9173   }
9174   }
9175
9176   // Also sets EFLAGS.
9177   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9178   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9179
9180   SDValue SetCC =
9181     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9182                 DAG.getConstant(Cond, MVT::i32),
9183                 SDValue(Sum.getNode(), 1));
9184
9185   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9186   return Sum;
9187 }
9188
9189 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9190   DebugLoc dl = Op.getDebugLoc();
9191   SDNode* Node = Op.getNode();
9192   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9193   EVT VT = Node->getValueType(0);
9194
9195   if (Subtarget->hasSSE2() && VT.isVector()) {
9196     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9197                         ExtraVT.getScalarType().getSizeInBits();
9198     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9199
9200     unsigned SHLIntrinsicsID = 0;
9201     unsigned SRAIntrinsicsID = 0;
9202     switch (VT.getSimpleVT().SimpleTy) {
9203       default:
9204         return SDValue();
9205       case MVT::v2i64: {
9206         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9207         SRAIntrinsicsID = 0;
9208         break;
9209       }
9210       case MVT::v4i32: {
9211         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9212         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9213         break;
9214       }
9215       case MVT::v8i16: {
9216         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9217         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9218         break;
9219       }
9220     }
9221
9222     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9223                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9224                          Node->getOperand(0), ShAmt);
9225
9226     // In case of 1 bit sext, no need to shr
9227     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9228
9229     if (SRAIntrinsicsID) {
9230       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9231                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9232                          Tmp1, ShAmt);
9233     }
9234     return Tmp1;
9235   }
9236
9237   return SDValue();
9238 }
9239
9240
9241 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9242   DebugLoc dl = Op.getDebugLoc();
9243
9244   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9245   // There isn't any reason to disable it if the target processor supports it.
9246   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9247     SDValue Chain = Op.getOperand(0);
9248     SDValue Zero = DAG.getConstant(0, MVT::i32);
9249     SDValue Ops[] = {
9250       DAG.getRegister(X86::ESP, MVT::i32), // Base
9251       DAG.getTargetConstant(1, MVT::i8),   // Scale
9252       DAG.getRegister(0, MVT::i32),        // Index
9253       DAG.getTargetConstant(0, MVT::i32),  // Disp
9254       DAG.getRegister(0, MVT::i32),        // Segment.
9255       Zero,
9256       Chain
9257     };
9258     SDNode *Res =
9259       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9260                           array_lengthof(Ops));
9261     return SDValue(Res, 0);
9262   }
9263
9264   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9265   if (!isDev)
9266     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9267
9268   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9269   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9270   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9271   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9272
9273   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9274   if (!Op1 && !Op2 && !Op3 && Op4)
9275     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9276
9277   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9278   if (Op1 && !Op2 && !Op3 && !Op4)
9279     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9280
9281   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9282   //           (MFENCE)>;
9283   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9284 }
9285
9286 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9287   EVT T = Op.getValueType();
9288   DebugLoc DL = Op.getDebugLoc();
9289   unsigned Reg = 0;
9290   unsigned size = 0;
9291   switch(T.getSimpleVT().SimpleTy) {
9292   default:
9293     assert(false && "Invalid value type!");
9294   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9295   case MVT::i16: Reg = X86::AX;  size = 2; break;
9296   case MVT::i32: Reg = X86::EAX; size = 4; break;
9297   case MVT::i64:
9298     assert(Subtarget->is64Bit() && "Node not type legal!");
9299     Reg = X86::RAX; size = 8;
9300     break;
9301   }
9302   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9303                                     Op.getOperand(2), SDValue());
9304   SDValue Ops[] = { cpIn.getValue(0),
9305                     Op.getOperand(1),
9306                     Op.getOperand(3),
9307                     DAG.getTargetConstant(size, MVT::i8),
9308                     cpIn.getValue(1) };
9309   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9310   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9311   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9312                                            Ops, 5, T, MMO);
9313   SDValue cpOut =
9314     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9315   return cpOut;
9316 }
9317
9318 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9319                                                  SelectionDAG &DAG) const {
9320   assert(Subtarget->is64Bit() && "Result not type legalized?");
9321   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9322   SDValue TheChain = Op.getOperand(0);
9323   DebugLoc dl = Op.getDebugLoc();
9324   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9325   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9326   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9327                                    rax.getValue(2));
9328   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9329                             DAG.getConstant(32, MVT::i8));
9330   SDValue Ops[] = {
9331     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9332     rdx.getValue(1)
9333   };
9334   return DAG.getMergeValues(Ops, 2, dl);
9335 }
9336
9337 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9338                                             SelectionDAG &DAG) const {
9339   EVT SrcVT = Op.getOperand(0).getValueType();
9340   EVT DstVT = Op.getValueType();
9341   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9342          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9343   assert((DstVT == MVT::i64 ||
9344           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9345          "Unexpected custom BITCAST");
9346   // i64 <=> MMX conversions are Legal.
9347   if (SrcVT==MVT::i64 && DstVT.isVector())
9348     return Op;
9349   if (DstVT==MVT::i64 && SrcVT.isVector())
9350     return Op;
9351   // MMX <=> MMX conversions are Legal.
9352   if (SrcVT.isVector() && DstVT.isVector())
9353     return Op;
9354   // All other conversions need to be expanded.
9355   return SDValue();
9356 }
9357
9358 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9359   SDNode *Node = Op.getNode();
9360   DebugLoc dl = Node->getDebugLoc();
9361   EVT T = Node->getValueType(0);
9362   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9363                               DAG.getConstant(0, T), Node->getOperand(2));
9364   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9365                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9366                        Node->getOperand(0),
9367                        Node->getOperand(1), negOp,
9368                        cast<AtomicSDNode>(Node)->getSrcValue(),
9369                        cast<AtomicSDNode>(Node)->getAlignment());
9370 }
9371
9372 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9373   EVT VT = Op.getNode()->getValueType(0);
9374
9375   // Let legalize expand this if it isn't a legal type yet.
9376   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9377     return SDValue();
9378
9379   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9380
9381   unsigned Opc;
9382   bool ExtraOp = false;
9383   switch (Op.getOpcode()) {
9384   default: assert(0 && "Invalid code");
9385   case ISD::ADDC: Opc = X86ISD::ADD; break;
9386   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9387   case ISD::SUBC: Opc = X86ISD::SUB; break;
9388   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9389   }
9390
9391   if (!ExtraOp)
9392     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9393                        Op.getOperand(1));
9394   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9395                      Op.getOperand(1), Op.getOperand(2));
9396 }
9397
9398 /// LowerOperation - Provide custom lowering hooks for some operations.
9399 ///
9400 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9401   switch (Op.getOpcode()) {
9402   default: llvm_unreachable("Should not custom lower this!");
9403   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
9404   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9405   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9406   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9407   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9408   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9409   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9410   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9411   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9412   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9413   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9414   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9415   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9416   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9417   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9418   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9419   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9420   case ISD::SHL_PARTS:
9421   case ISD::SRA_PARTS:
9422   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9423   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9424   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9425   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9426   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9427   case ISD::FABS:               return LowerFABS(Op, DAG);
9428   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9429   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9430   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9431   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9432   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9433   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9434   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9435   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9436   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9437   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9438   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9439   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9440   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9441   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9442   case ISD::FRAME_TO_ARGS_OFFSET:
9443                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9444   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9445   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9446   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9447   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9448   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9449   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9450   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9451   case ISD::SRA:
9452   case ISD::SRL:
9453   case ISD::SHL:                return LowerShift(Op, DAG);
9454   case ISD::SADDO:
9455   case ISD::UADDO:
9456   case ISD::SSUBO:
9457   case ISD::USUBO:
9458   case ISD::SMULO:
9459   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9460   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9461   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9462   case ISD::ADDC:
9463   case ISD::ADDE:
9464   case ISD::SUBC:
9465   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9466   }
9467 }
9468
9469 void X86TargetLowering::
9470 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9471                         SelectionDAG &DAG, unsigned NewOp) const {
9472   EVT T = Node->getValueType(0);
9473   DebugLoc dl = Node->getDebugLoc();
9474   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9475
9476   SDValue Chain = Node->getOperand(0);
9477   SDValue In1 = Node->getOperand(1);
9478   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9479                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9480   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9481                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9482   SDValue Ops[] = { Chain, In1, In2L, In2H };
9483   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9484   SDValue Result =
9485     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9486                             cast<MemSDNode>(Node)->getMemOperand());
9487   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9488   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9489   Results.push_back(Result.getValue(2));
9490 }
9491
9492 /// ReplaceNodeResults - Replace a node with an illegal result type
9493 /// with a new node built out of custom code.
9494 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9495                                            SmallVectorImpl<SDValue>&Results,
9496                                            SelectionDAG &DAG) const {
9497   DebugLoc dl = N->getDebugLoc();
9498   switch (N->getOpcode()) {
9499   default:
9500     assert(false && "Do not know how to custom type legalize this operation!");
9501     return;
9502   case ISD::SIGN_EXTEND_INREG:
9503   case ISD::ADDC:
9504   case ISD::ADDE:
9505   case ISD::SUBC:
9506   case ISD::SUBE:
9507     // We don't want to expand or promote these.
9508     return;
9509   case ISD::FP_TO_SINT: {
9510     std::pair<SDValue,SDValue> Vals =
9511         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9512     SDValue FIST = Vals.first, StackSlot = Vals.second;
9513     if (FIST.getNode() != 0) {
9514       EVT VT = N->getValueType(0);
9515       // Return a load from the stack slot.
9516       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9517                                     MachinePointerInfo(), false, false, 0));
9518     }
9519     return;
9520   }
9521   case ISD::READCYCLECOUNTER: {
9522     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9523     SDValue TheChain = N->getOperand(0);
9524     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9525     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9526                                      rd.getValue(1));
9527     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9528                                      eax.getValue(2));
9529     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9530     SDValue Ops[] = { eax, edx };
9531     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9532     Results.push_back(edx.getValue(1));
9533     return;
9534   }
9535   case ISD::ATOMIC_CMP_SWAP: {
9536     EVT T = N->getValueType(0);
9537     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9538     SDValue cpInL, cpInH;
9539     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9540                         DAG.getConstant(0, MVT::i32));
9541     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9542                         DAG.getConstant(1, MVT::i32));
9543     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9544     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9545                              cpInL.getValue(1));
9546     SDValue swapInL, swapInH;
9547     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9548                           DAG.getConstant(0, MVT::i32));
9549     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9550                           DAG.getConstant(1, MVT::i32));
9551     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9552                                cpInH.getValue(1));
9553     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9554                                swapInL.getValue(1));
9555     SDValue Ops[] = { swapInH.getValue(0),
9556                       N->getOperand(1),
9557                       swapInH.getValue(1) };
9558     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9559     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9560     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9561                                              Ops, 3, T, MMO);
9562     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9563                                         MVT::i32, Result.getValue(1));
9564     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9565                                         MVT::i32, cpOutL.getValue(2));
9566     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9567     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9568     Results.push_back(cpOutH.getValue(1));
9569     return;
9570   }
9571   case ISD::ATOMIC_LOAD_ADD:
9572     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9573     return;
9574   case ISD::ATOMIC_LOAD_AND:
9575     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9576     return;
9577   case ISD::ATOMIC_LOAD_NAND:
9578     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9579     return;
9580   case ISD::ATOMIC_LOAD_OR:
9581     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9582     return;
9583   case ISD::ATOMIC_LOAD_SUB:
9584     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9585     return;
9586   case ISD::ATOMIC_LOAD_XOR:
9587     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9588     return;
9589   case ISD::ATOMIC_SWAP:
9590     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9591     return;
9592   }
9593 }
9594
9595 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9596   switch (Opcode) {
9597   default: return NULL;
9598   case X86ISD::BSF:                return "X86ISD::BSF";
9599   case X86ISD::BSR:                return "X86ISD::BSR";
9600   case X86ISD::SHLD:               return "X86ISD::SHLD";
9601   case X86ISD::SHRD:               return "X86ISD::SHRD";
9602   case X86ISD::FAND:               return "X86ISD::FAND";
9603   case X86ISD::FOR:                return "X86ISD::FOR";
9604   case X86ISD::FXOR:               return "X86ISD::FXOR";
9605   case X86ISD::FSRL:               return "X86ISD::FSRL";
9606   case X86ISD::FILD:               return "X86ISD::FILD";
9607   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9608   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9609   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9610   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9611   case X86ISD::FLD:                return "X86ISD::FLD";
9612   case X86ISD::FST:                return "X86ISD::FST";
9613   case X86ISD::CALL:               return "X86ISD::CALL";
9614   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9615   case X86ISD::BT:                 return "X86ISD::BT";
9616   case X86ISD::CMP:                return "X86ISD::CMP";
9617   case X86ISD::COMI:               return "X86ISD::COMI";
9618   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9619   case X86ISD::SETCC:              return "X86ISD::SETCC";
9620   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9621   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9622   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9623   case X86ISD::CMOV:               return "X86ISD::CMOV";
9624   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9625   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9626   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9627   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9628   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9629   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9630   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9631   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9632   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9633   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9634   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9635   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9636   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9637   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9638   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9639   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9640   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9641   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9642   case X86ISD::FMAX:               return "X86ISD::FMAX";
9643   case X86ISD::FMIN:               return "X86ISD::FMIN";
9644   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9645   case X86ISD::FRCP:               return "X86ISD::FRCP";
9646   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9647   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9648   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9649   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9650   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9651   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9652   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9653   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9654   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9655   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9656   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9657   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9658   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9659   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9660   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9661   case X86ISD::VSHL:               return "X86ISD::VSHL";
9662   case X86ISD::VSRL:               return "X86ISD::VSRL";
9663   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9664   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9665   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9666   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9667   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9668   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9669   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9670   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9671   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9672   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9673   case X86ISD::ADD:                return "X86ISD::ADD";
9674   case X86ISD::SUB:                return "X86ISD::SUB";
9675   case X86ISD::ADC:                return "X86ISD::ADC";
9676   case X86ISD::SBB:                return "X86ISD::SBB";
9677   case X86ISD::SMUL:               return "X86ISD::SMUL";
9678   case X86ISD::UMUL:               return "X86ISD::UMUL";
9679   case X86ISD::INC:                return "X86ISD::INC";
9680   case X86ISD::DEC:                return "X86ISD::DEC";
9681   case X86ISD::OR:                 return "X86ISD::OR";
9682   case X86ISD::XOR:                return "X86ISD::XOR";
9683   case X86ISD::AND:                return "X86ISD::AND";
9684   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9685   case X86ISD::PTEST:              return "X86ISD::PTEST";
9686   case X86ISD::TESTP:              return "X86ISD::TESTP";
9687   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9688   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9689   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9690   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9691   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9692   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9693   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9694   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9695   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9696   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9697   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9698   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9699   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9700   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9701   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9702   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9703   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9704   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9705   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9706   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9707   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9708   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9709   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9710   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9711   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9712   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9713   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9714   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9715   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9716   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9717   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9718   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9719   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9720   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9721   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9722   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9723   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9724   case X86ISD::VPERMIL:            return "X86ISD::VPERMIL";
9725   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9726   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9727   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9728   }
9729 }
9730
9731 // isLegalAddressingMode - Return true if the addressing mode represented
9732 // by AM is legal for this target, for a load/store of the specified type.
9733 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9734                                               Type *Ty) const {
9735   // X86 supports extremely general addressing modes.
9736   CodeModel::Model M = getTargetMachine().getCodeModel();
9737   Reloc::Model R = getTargetMachine().getRelocationModel();
9738
9739   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9740   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9741     return false;
9742
9743   if (AM.BaseGV) {
9744     unsigned GVFlags =
9745       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9746
9747     // If a reference to this global requires an extra load, we can't fold it.
9748     if (isGlobalStubReference(GVFlags))
9749       return false;
9750
9751     // If BaseGV requires a register for the PIC base, we cannot also have a
9752     // BaseReg specified.
9753     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9754       return false;
9755
9756     // If lower 4G is not available, then we must use rip-relative addressing.
9757     if ((M != CodeModel::Small || R != Reloc::Static) &&
9758         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9759       return false;
9760   }
9761
9762   switch (AM.Scale) {
9763   case 0:
9764   case 1:
9765   case 2:
9766   case 4:
9767   case 8:
9768     // These scales always work.
9769     break;
9770   case 3:
9771   case 5:
9772   case 9:
9773     // These scales are formed with basereg+scalereg.  Only accept if there is
9774     // no basereg yet.
9775     if (AM.HasBaseReg)
9776       return false;
9777     break;
9778   default:  // Other stuff never works.
9779     return false;
9780   }
9781
9782   return true;
9783 }
9784
9785
9786 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9787   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9788     return false;
9789   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9790   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9791   if (NumBits1 <= NumBits2)
9792     return false;
9793   return true;
9794 }
9795
9796 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9797   if (!VT1.isInteger() || !VT2.isInteger())
9798     return false;
9799   unsigned NumBits1 = VT1.getSizeInBits();
9800   unsigned NumBits2 = VT2.getSizeInBits();
9801   if (NumBits1 <= NumBits2)
9802     return false;
9803   return true;
9804 }
9805
9806 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9807   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9808   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9809 }
9810
9811 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9812   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9813   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9814 }
9815
9816 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9817   // i16 instructions are longer (0x66 prefix) and potentially slower.
9818   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9819 }
9820
9821 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9822 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9823 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9824 /// are assumed to be legal.
9825 bool
9826 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9827                                       EVT VT) const {
9828   // Very little shuffling can be done for 64-bit vectors right now.
9829   if (VT.getSizeInBits() == 64)
9830     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9831
9832   // FIXME: pshufb, blends, shifts.
9833   return (VT.getVectorNumElements() == 2 ||
9834           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9835           isMOVLMask(M, VT) ||
9836           isSHUFPMask(M, VT) ||
9837           isPSHUFDMask(M, VT) ||
9838           isPSHUFHWMask(M, VT) ||
9839           isPSHUFLWMask(M, VT) ||
9840           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9841           isUNPCKLMask(M, VT) ||
9842           isUNPCKHMask(M, VT) ||
9843           isUNPCKL_v_undef_Mask(M, VT) ||
9844           isUNPCKH_v_undef_Mask(M, VT));
9845 }
9846
9847 bool
9848 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9849                                           EVT VT) const {
9850   unsigned NumElts = VT.getVectorNumElements();
9851   // FIXME: This collection of masks seems suspect.
9852   if (NumElts == 2)
9853     return true;
9854   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9855     return (isMOVLMask(Mask, VT)  ||
9856             isCommutedMOVLMask(Mask, VT, true) ||
9857             isSHUFPMask(Mask, VT) ||
9858             isCommutedSHUFPMask(Mask, VT));
9859   }
9860   return false;
9861 }
9862
9863 //===----------------------------------------------------------------------===//
9864 //                           X86 Scheduler Hooks
9865 //===----------------------------------------------------------------------===//
9866
9867 // private utility function
9868 MachineBasicBlock *
9869 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9870                                                        MachineBasicBlock *MBB,
9871                                                        unsigned regOpc,
9872                                                        unsigned immOpc,
9873                                                        unsigned LoadOpc,
9874                                                        unsigned CXchgOpc,
9875                                                        unsigned notOpc,
9876                                                        unsigned EAXreg,
9877                                                        TargetRegisterClass *RC,
9878                                                        bool invSrc) const {
9879   // For the atomic bitwise operator, we generate
9880   //   thisMBB:
9881   //   newMBB:
9882   //     ld  t1 = [bitinstr.addr]
9883   //     op  t2 = t1, [bitinstr.val]
9884   //     mov EAX = t1
9885   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9886   //     bz  newMBB
9887   //     fallthrough -->nextMBB
9888   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9889   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9890   MachineFunction::iterator MBBIter = MBB;
9891   ++MBBIter;
9892
9893   /// First build the CFG
9894   MachineFunction *F = MBB->getParent();
9895   MachineBasicBlock *thisMBB = MBB;
9896   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9897   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9898   F->insert(MBBIter, newMBB);
9899   F->insert(MBBIter, nextMBB);
9900
9901   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9902   nextMBB->splice(nextMBB->begin(), thisMBB,
9903                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9904                   thisMBB->end());
9905   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9906
9907   // Update thisMBB to fall through to newMBB
9908   thisMBB->addSuccessor(newMBB);
9909
9910   // newMBB jumps to itself and fall through to nextMBB
9911   newMBB->addSuccessor(nextMBB);
9912   newMBB->addSuccessor(newMBB);
9913
9914   // Insert instructions into newMBB based on incoming instruction
9915   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9916          "unexpected number of operands");
9917   DebugLoc dl = bInstr->getDebugLoc();
9918   MachineOperand& destOper = bInstr->getOperand(0);
9919   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9920   int numArgs = bInstr->getNumOperands() - 1;
9921   for (int i=0; i < numArgs; ++i)
9922     argOpers[i] = &bInstr->getOperand(i+1);
9923
9924   // x86 address has 4 operands: base, index, scale, and displacement
9925   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9926   int valArgIndx = lastAddrIndx + 1;
9927
9928   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9929   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9930   for (int i=0; i <= lastAddrIndx; ++i)
9931     (*MIB).addOperand(*argOpers[i]);
9932
9933   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9934   if (invSrc) {
9935     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9936   }
9937   else
9938     tt = t1;
9939
9940   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9941   assert((argOpers[valArgIndx]->isReg() ||
9942           argOpers[valArgIndx]->isImm()) &&
9943          "invalid operand");
9944   if (argOpers[valArgIndx]->isReg())
9945     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9946   else
9947     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9948   MIB.addReg(tt);
9949   (*MIB).addOperand(*argOpers[valArgIndx]);
9950
9951   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9952   MIB.addReg(t1);
9953
9954   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9955   for (int i=0; i <= lastAddrIndx; ++i)
9956     (*MIB).addOperand(*argOpers[i]);
9957   MIB.addReg(t2);
9958   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9959   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9960                     bInstr->memoperands_end());
9961
9962   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9963   MIB.addReg(EAXreg);
9964
9965   // insert branch
9966   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9967
9968   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9969   return nextMBB;
9970 }
9971
9972 // private utility function:  64 bit atomics on 32 bit host.
9973 MachineBasicBlock *
9974 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9975                                                        MachineBasicBlock *MBB,
9976                                                        unsigned regOpcL,
9977                                                        unsigned regOpcH,
9978                                                        unsigned immOpcL,
9979                                                        unsigned immOpcH,
9980                                                        bool invSrc) const {
9981   // For the atomic bitwise operator, we generate
9982   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9983   //     ld t1,t2 = [bitinstr.addr]
9984   //   newMBB:
9985   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9986   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9987   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9988   //     mov ECX, EBX <- t5, t6
9989   //     mov EAX, EDX <- t1, t2
9990   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9991   //     mov t3, t4 <- EAX, EDX
9992   //     bz  newMBB
9993   //     result in out1, out2
9994   //     fallthrough -->nextMBB
9995
9996   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9997   const unsigned LoadOpc = X86::MOV32rm;
9998   const unsigned NotOpc = X86::NOT32r;
9999   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10000   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10001   MachineFunction::iterator MBBIter = MBB;
10002   ++MBBIter;
10003
10004   /// First build the CFG
10005   MachineFunction *F = MBB->getParent();
10006   MachineBasicBlock *thisMBB = MBB;
10007   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10008   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10009   F->insert(MBBIter, newMBB);
10010   F->insert(MBBIter, nextMBB);
10011
10012   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10013   nextMBB->splice(nextMBB->begin(), thisMBB,
10014                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10015                   thisMBB->end());
10016   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10017
10018   // Update thisMBB to fall through to newMBB
10019   thisMBB->addSuccessor(newMBB);
10020
10021   // newMBB jumps to itself and fall through to nextMBB
10022   newMBB->addSuccessor(nextMBB);
10023   newMBB->addSuccessor(newMBB);
10024
10025   DebugLoc dl = bInstr->getDebugLoc();
10026   // Insert instructions into newMBB based on incoming instruction
10027   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10028   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10029          "unexpected number of operands");
10030   MachineOperand& dest1Oper = bInstr->getOperand(0);
10031   MachineOperand& dest2Oper = bInstr->getOperand(1);
10032   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10033   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10034     argOpers[i] = &bInstr->getOperand(i+2);
10035
10036     // We use some of the operands multiple times, so conservatively just
10037     // clear any kill flags that might be present.
10038     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10039       argOpers[i]->setIsKill(false);
10040   }
10041
10042   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10043   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10044
10045   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10046   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10047   for (int i=0; i <= lastAddrIndx; ++i)
10048     (*MIB).addOperand(*argOpers[i]);
10049   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10050   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10051   // add 4 to displacement.
10052   for (int i=0; i <= lastAddrIndx-2; ++i)
10053     (*MIB).addOperand(*argOpers[i]);
10054   MachineOperand newOp3 = *(argOpers[3]);
10055   if (newOp3.isImm())
10056     newOp3.setImm(newOp3.getImm()+4);
10057   else
10058     newOp3.setOffset(newOp3.getOffset()+4);
10059   (*MIB).addOperand(newOp3);
10060   (*MIB).addOperand(*argOpers[lastAddrIndx]);
10061
10062   // t3/4 are defined later, at the bottom of the loop
10063   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10064   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10065   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10066     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10067   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10068     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10069
10070   // The subsequent operations should be using the destination registers of
10071   //the PHI instructions.
10072   if (invSrc) {
10073     t1 = F->getRegInfo().createVirtualRegister(RC);
10074     t2 = F->getRegInfo().createVirtualRegister(RC);
10075     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10076     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10077   } else {
10078     t1 = dest1Oper.getReg();
10079     t2 = dest2Oper.getReg();
10080   }
10081
10082   int valArgIndx = lastAddrIndx + 1;
10083   assert((argOpers[valArgIndx]->isReg() ||
10084           argOpers[valArgIndx]->isImm()) &&
10085          "invalid operand");
10086   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10087   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10088   if (argOpers[valArgIndx]->isReg())
10089     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10090   else
10091     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10092   if (regOpcL != X86::MOV32rr)
10093     MIB.addReg(t1);
10094   (*MIB).addOperand(*argOpers[valArgIndx]);
10095   assert(argOpers[valArgIndx + 1]->isReg() ==
10096          argOpers[valArgIndx]->isReg());
10097   assert(argOpers[valArgIndx + 1]->isImm() ==
10098          argOpers[valArgIndx]->isImm());
10099   if (argOpers[valArgIndx + 1]->isReg())
10100     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10101   else
10102     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10103   if (regOpcH != X86::MOV32rr)
10104     MIB.addReg(t2);
10105   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10106
10107   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10108   MIB.addReg(t1);
10109   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10110   MIB.addReg(t2);
10111
10112   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10113   MIB.addReg(t5);
10114   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10115   MIB.addReg(t6);
10116
10117   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10118   for (int i=0; i <= lastAddrIndx; ++i)
10119     (*MIB).addOperand(*argOpers[i]);
10120
10121   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10122   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10123                     bInstr->memoperands_end());
10124
10125   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10126   MIB.addReg(X86::EAX);
10127   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10128   MIB.addReg(X86::EDX);
10129
10130   // insert branch
10131   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10132
10133   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10134   return nextMBB;
10135 }
10136
10137 // private utility function
10138 MachineBasicBlock *
10139 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10140                                                       MachineBasicBlock *MBB,
10141                                                       unsigned cmovOpc) const {
10142   // For the atomic min/max operator, we generate
10143   //   thisMBB:
10144   //   newMBB:
10145   //     ld t1 = [min/max.addr]
10146   //     mov t2 = [min/max.val]
10147   //     cmp  t1, t2
10148   //     cmov[cond] t2 = t1
10149   //     mov EAX = t1
10150   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10151   //     bz   newMBB
10152   //     fallthrough -->nextMBB
10153   //
10154   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10155   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10156   MachineFunction::iterator MBBIter = MBB;
10157   ++MBBIter;
10158
10159   /// First build the CFG
10160   MachineFunction *F = MBB->getParent();
10161   MachineBasicBlock *thisMBB = MBB;
10162   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10163   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10164   F->insert(MBBIter, newMBB);
10165   F->insert(MBBIter, nextMBB);
10166
10167   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10168   nextMBB->splice(nextMBB->begin(), thisMBB,
10169                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10170                   thisMBB->end());
10171   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10172
10173   // Update thisMBB to fall through to newMBB
10174   thisMBB->addSuccessor(newMBB);
10175
10176   // newMBB jumps to newMBB and fall through to nextMBB
10177   newMBB->addSuccessor(nextMBB);
10178   newMBB->addSuccessor(newMBB);
10179
10180   DebugLoc dl = mInstr->getDebugLoc();
10181   // Insert instructions into newMBB based on incoming instruction
10182   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10183          "unexpected number of operands");
10184   MachineOperand& destOper = mInstr->getOperand(0);
10185   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10186   int numArgs = mInstr->getNumOperands() - 1;
10187   for (int i=0; i < numArgs; ++i)
10188     argOpers[i] = &mInstr->getOperand(i+1);
10189
10190   // x86 address has 4 operands: base, index, scale, and displacement
10191   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10192   int valArgIndx = lastAddrIndx + 1;
10193
10194   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10195   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10196   for (int i=0; i <= lastAddrIndx; ++i)
10197     (*MIB).addOperand(*argOpers[i]);
10198
10199   // We only support register and immediate values
10200   assert((argOpers[valArgIndx]->isReg() ||
10201           argOpers[valArgIndx]->isImm()) &&
10202          "invalid operand");
10203
10204   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10205   if (argOpers[valArgIndx]->isReg())
10206     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10207   else
10208     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10209   (*MIB).addOperand(*argOpers[valArgIndx]);
10210
10211   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10212   MIB.addReg(t1);
10213
10214   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10215   MIB.addReg(t1);
10216   MIB.addReg(t2);
10217
10218   // Generate movc
10219   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10220   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10221   MIB.addReg(t2);
10222   MIB.addReg(t1);
10223
10224   // Cmp and exchange if none has modified the memory location
10225   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10226   for (int i=0; i <= lastAddrIndx; ++i)
10227     (*MIB).addOperand(*argOpers[i]);
10228   MIB.addReg(t3);
10229   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10230   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10231                     mInstr->memoperands_end());
10232
10233   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10234   MIB.addReg(X86::EAX);
10235
10236   // insert branch
10237   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10238
10239   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10240   return nextMBB;
10241 }
10242
10243 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10244 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10245 // in the .td file.
10246 MachineBasicBlock *
10247 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10248                             unsigned numArgs, bool memArg) const {
10249   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10250          "Target must have SSE4.2 or AVX features enabled");
10251
10252   DebugLoc dl = MI->getDebugLoc();
10253   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10254   unsigned Opc;
10255   if (!Subtarget->hasAVX()) {
10256     if (memArg)
10257       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10258     else
10259       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10260   } else {
10261     if (memArg)
10262       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10263     else
10264       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10265   }
10266
10267   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10268   for (unsigned i = 0; i < numArgs; ++i) {
10269     MachineOperand &Op = MI->getOperand(i+1);
10270     if (!(Op.isReg() && Op.isImplicit()))
10271       MIB.addOperand(Op);
10272   }
10273   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10274     .addReg(X86::XMM0);
10275
10276   MI->eraseFromParent();
10277   return BB;
10278 }
10279
10280 MachineBasicBlock *
10281 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10282   DebugLoc dl = MI->getDebugLoc();
10283   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10284
10285   // Address into RAX/EAX, other two args into ECX, EDX.
10286   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10287   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10288   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10289   for (int i = 0; i < X86::AddrNumOperands; ++i)
10290     MIB.addOperand(MI->getOperand(i));
10291
10292   unsigned ValOps = X86::AddrNumOperands;
10293   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10294     .addReg(MI->getOperand(ValOps).getReg());
10295   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10296     .addReg(MI->getOperand(ValOps+1).getReg());
10297
10298   // The instruction doesn't actually take any operands though.
10299   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10300
10301   MI->eraseFromParent(); // The pseudo is gone now.
10302   return BB;
10303 }
10304
10305 MachineBasicBlock *
10306 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10307   DebugLoc dl = MI->getDebugLoc();
10308   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10309
10310   // First arg in ECX, the second in EAX.
10311   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10312     .addReg(MI->getOperand(0).getReg());
10313   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10314     .addReg(MI->getOperand(1).getReg());
10315
10316   // The instruction doesn't actually take any operands though.
10317   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10318
10319   MI->eraseFromParent(); // The pseudo is gone now.
10320   return BB;
10321 }
10322
10323 MachineBasicBlock *
10324 X86TargetLowering::EmitVAARG64WithCustomInserter(
10325                    MachineInstr *MI,
10326                    MachineBasicBlock *MBB) const {
10327   // Emit va_arg instruction on X86-64.
10328
10329   // Operands to this pseudo-instruction:
10330   // 0  ) Output        : destination address (reg)
10331   // 1-5) Input         : va_list address (addr, i64mem)
10332   // 6  ) ArgSize       : Size (in bytes) of vararg type
10333   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10334   // 8  ) Align         : Alignment of type
10335   // 9  ) EFLAGS (implicit-def)
10336
10337   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10338   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10339
10340   unsigned DestReg = MI->getOperand(0).getReg();
10341   MachineOperand &Base = MI->getOperand(1);
10342   MachineOperand &Scale = MI->getOperand(2);
10343   MachineOperand &Index = MI->getOperand(3);
10344   MachineOperand &Disp = MI->getOperand(4);
10345   MachineOperand &Segment = MI->getOperand(5);
10346   unsigned ArgSize = MI->getOperand(6).getImm();
10347   unsigned ArgMode = MI->getOperand(7).getImm();
10348   unsigned Align = MI->getOperand(8).getImm();
10349
10350   // Memory Reference
10351   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10352   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10353   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10354
10355   // Machine Information
10356   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10357   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10358   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10359   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10360   DebugLoc DL = MI->getDebugLoc();
10361
10362   // struct va_list {
10363   //   i32   gp_offset
10364   //   i32   fp_offset
10365   //   i64   overflow_area (address)
10366   //   i64   reg_save_area (address)
10367   // }
10368   // sizeof(va_list) = 24
10369   // alignment(va_list) = 8
10370
10371   unsigned TotalNumIntRegs = 6;
10372   unsigned TotalNumXMMRegs = 8;
10373   bool UseGPOffset = (ArgMode == 1);
10374   bool UseFPOffset = (ArgMode == 2);
10375   unsigned MaxOffset = TotalNumIntRegs * 8 +
10376                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10377
10378   /* Align ArgSize to a multiple of 8 */
10379   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10380   bool NeedsAlign = (Align > 8);
10381
10382   MachineBasicBlock *thisMBB = MBB;
10383   MachineBasicBlock *overflowMBB;
10384   MachineBasicBlock *offsetMBB;
10385   MachineBasicBlock *endMBB;
10386
10387   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10388   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10389   unsigned OffsetReg = 0;
10390
10391   if (!UseGPOffset && !UseFPOffset) {
10392     // If we only pull from the overflow region, we don't create a branch.
10393     // We don't need to alter control flow.
10394     OffsetDestReg = 0; // unused
10395     OverflowDestReg = DestReg;
10396
10397     offsetMBB = NULL;
10398     overflowMBB = thisMBB;
10399     endMBB = thisMBB;
10400   } else {
10401     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10402     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10403     // If not, pull from overflow_area. (branch to overflowMBB)
10404     //
10405     //       thisMBB
10406     //         |     .
10407     //         |        .
10408     //     offsetMBB   overflowMBB
10409     //         |        .
10410     //         |     .
10411     //        endMBB
10412
10413     // Registers for the PHI in endMBB
10414     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10415     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10416
10417     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10418     MachineFunction *MF = MBB->getParent();
10419     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10420     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10421     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10422
10423     MachineFunction::iterator MBBIter = MBB;
10424     ++MBBIter;
10425
10426     // Insert the new basic blocks
10427     MF->insert(MBBIter, offsetMBB);
10428     MF->insert(MBBIter, overflowMBB);
10429     MF->insert(MBBIter, endMBB);
10430
10431     // Transfer the remainder of MBB and its successor edges to endMBB.
10432     endMBB->splice(endMBB->begin(), thisMBB,
10433                     llvm::next(MachineBasicBlock::iterator(MI)),
10434                     thisMBB->end());
10435     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10436
10437     // Make offsetMBB and overflowMBB successors of thisMBB
10438     thisMBB->addSuccessor(offsetMBB);
10439     thisMBB->addSuccessor(overflowMBB);
10440
10441     // endMBB is a successor of both offsetMBB and overflowMBB
10442     offsetMBB->addSuccessor(endMBB);
10443     overflowMBB->addSuccessor(endMBB);
10444
10445     // Load the offset value into a register
10446     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10447     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10448       .addOperand(Base)
10449       .addOperand(Scale)
10450       .addOperand(Index)
10451       .addDisp(Disp, UseFPOffset ? 4 : 0)
10452       .addOperand(Segment)
10453       .setMemRefs(MMOBegin, MMOEnd);
10454
10455     // Check if there is enough room left to pull this argument.
10456     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10457       .addReg(OffsetReg)
10458       .addImm(MaxOffset + 8 - ArgSizeA8);
10459
10460     // Branch to "overflowMBB" if offset >= max
10461     // Fall through to "offsetMBB" otherwise
10462     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10463       .addMBB(overflowMBB);
10464   }
10465
10466   // In offsetMBB, emit code to use the reg_save_area.
10467   if (offsetMBB) {
10468     assert(OffsetReg != 0);
10469
10470     // Read the reg_save_area address.
10471     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10472     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10473       .addOperand(Base)
10474       .addOperand(Scale)
10475       .addOperand(Index)
10476       .addDisp(Disp, 16)
10477       .addOperand(Segment)
10478       .setMemRefs(MMOBegin, MMOEnd);
10479
10480     // Zero-extend the offset
10481     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10482       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10483         .addImm(0)
10484         .addReg(OffsetReg)
10485         .addImm(X86::sub_32bit);
10486
10487     // Add the offset to the reg_save_area to get the final address.
10488     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10489       .addReg(OffsetReg64)
10490       .addReg(RegSaveReg);
10491
10492     // Compute the offset for the next argument
10493     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10494     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10495       .addReg(OffsetReg)
10496       .addImm(UseFPOffset ? 16 : 8);
10497
10498     // Store it back into the va_list.
10499     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10500       .addOperand(Base)
10501       .addOperand(Scale)
10502       .addOperand(Index)
10503       .addDisp(Disp, UseFPOffset ? 4 : 0)
10504       .addOperand(Segment)
10505       .addReg(NextOffsetReg)
10506       .setMemRefs(MMOBegin, MMOEnd);
10507
10508     // Jump to endMBB
10509     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10510       .addMBB(endMBB);
10511   }
10512
10513   //
10514   // Emit code to use overflow area
10515   //
10516
10517   // Load the overflow_area address into a register.
10518   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10519   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10520     .addOperand(Base)
10521     .addOperand(Scale)
10522     .addOperand(Index)
10523     .addDisp(Disp, 8)
10524     .addOperand(Segment)
10525     .setMemRefs(MMOBegin, MMOEnd);
10526
10527   // If we need to align it, do so. Otherwise, just copy the address
10528   // to OverflowDestReg.
10529   if (NeedsAlign) {
10530     // Align the overflow address
10531     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10532     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10533
10534     // aligned_addr = (addr + (align-1)) & ~(align-1)
10535     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10536       .addReg(OverflowAddrReg)
10537       .addImm(Align-1);
10538
10539     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10540       .addReg(TmpReg)
10541       .addImm(~(uint64_t)(Align-1));
10542   } else {
10543     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10544       .addReg(OverflowAddrReg);
10545   }
10546
10547   // Compute the next overflow address after this argument.
10548   // (the overflow address should be kept 8-byte aligned)
10549   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10550   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10551     .addReg(OverflowDestReg)
10552     .addImm(ArgSizeA8);
10553
10554   // Store the new overflow address.
10555   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10556     .addOperand(Base)
10557     .addOperand(Scale)
10558     .addOperand(Index)
10559     .addDisp(Disp, 8)
10560     .addOperand(Segment)
10561     .addReg(NextAddrReg)
10562     .setMemRefs(MMOBegin, MMOEnd);
10563
10564   // If we branched, emit the PHI to the front of endMBB.
10565   if (offsetMBB) {
10566     BuildMI(*endMBB, endMBB->begin(), DL,
10567             TII->get(X86::PHI), DestReg)
10568       .addReg(OffsetDestReg).addMBB(offsetMBB)
10569       .addReg(OverflowDestReg).addMBB(overflowMBB);
10570   }
10571
10572   // Erase the pseudo instruction
10573   MI->eraseFromParent();
10574
10575   return endMBB;
10576 }
10577
10578 MachineBasicBlock *
10579 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10580                                                  MachineInstr *MI,
10581                                                  MachineBasicBlock *MBB) const {
10582   // Emit code to save XMM registers to the stack. The ABI says that the
10583   // number of registers to save is given in %al, so it's theoretically
10584   // possible to do an indirect jump trick to avoid saving all of them,
10585   // however this code takes a simpler approach and just executes all
10586   // of the stores if %al is non-zero. It's less code, and it's probably
10587   // easier on the hardware branch predictor, and stores aren't all that
10588   // expensive anyway.
10589
10590   // Create the new basic blocks. One block contains all the XMM stores,
10591   // and one block is the final destination regardless of whether any
10592   // stores were performed.
10593   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10594   MachineFunction *F = MBB->getParent();
10595   MachineFunction::iterator MBBIter = MBB;
10596   ++MBBIter;
10597   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10598   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10599   F->insert(MBBIter, XMMSaveMBB);
10600   F->insert(MBBIter, EndMBB);
10601
10602   // Transfer the remainder of MBB and its successor edges to EndMBB.
10603   EndMBB->splice(EndMBB->begin(), MBB,
10604                  llvm::next(MachineBasicBlock::iterator(MI)),
10605                  MBB->end());
10606   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10607
10608   // The original block will now fall through to the XMM save block.
10609   MBB->addSuccessor(XMMSaveMBB);
10610   // The XMMSaveMBB will fall through to the end block.
10611   XMMSaveMBB->addSuccessor(EndMBB);
10612
10613   // Now add the instructions.
10614   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10615   DebugLoc DL = MI->getDebugLoc();
10616
10617   unsigned CountReg = MI->getOperand(0).getReg();
10618   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10619   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10620
10621   if (!Subtarget->isTargetWin64()) {
10622     // If %al is 0, branch around the XMM save block.
10623     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10624     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10625     MBB->addSuccessor(EndMBB);
10626   }
10627
10628   // In the XMM save block, save all the XMM argument registers.
10629   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10630     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10631     MachineMemOperand *MMO =
10632       F->getMachineMemOperand(
10633           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10634         MachineMemOperand::MOStore,
10635         /*Size=*/16, /*Align=*/16);
10636     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10637       .addFrameIndex(RegSaveFrameIndex)
10638       .addImm(/*Scale=*/1)
10639       .addReg(/*IndexReg=*/0)
10640       .addImm(/*Disp=*/Offset)
10641       .addReg(/*Segment=*/0)
10642       .addReg(MI->getOperand(i).getReg())
10643       .addMemOperand(MMO);
10644   }
10645
10646   MI->eraseFromParent();   // The pseudo instruction is gone now.
10647
10648   return EndMBB;
10649 }
10650
10651 MachineBasicBlock *
10652 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10653                                      MachineBasicBlock *BB) const {
10654   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10655   DebugLoc DL = MI->getDebugLoc();
10656
10657   // To "insert" a SELECT_CC instruction, we actually have to insert the
10658   // diamond control-flow pattern.  The incoming instruction knows the
10659   // destination vreg to set, the condition code register to branch on, the
10660   // true/false values to select between, and a branch opcode to use.
10661   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10662   MachineFunction::iterator It = BB;
10663   ++It;
10664
10665   //  thisMBB:
10666   //  ...
10667   //   TrueVal = ...
10668   //   cmpTY ccX, r1, r2
10669   //   bCC copy1MBB
10670   //   fallthrough --> copy0MBB
10671   MachineBasicBlock *thisMBB = BB;
10672   MachineFunction *F = BB->getParent();
10673   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10674   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10675   F->insert(It, copy0MBB);
10676   F->insert(It, sinkMBB);
10677
10678   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10679   // live into the sink and copy blocks.
10680   const MachineFunction *MF = BB->getParent();
10681   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10682   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10683
10684   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10685     const MachineOperand &MO = MI->getOperand(I);
10686     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10687     unsigned Reg = MO.getReg();
10688     if (Reg != X86::EFLAGS) continue;
10689     copy0MBB->addLiveIn(Reg);
10690     sinkMBB->addLiveIn(Reg);
10691   }
10692
10693   // Transfer the remainder of BB and its successor edges to sinkMBB.
10694   sinkMBB->splice(sinkMBB->begin(), BB,
10695                   llvm::next(MachineBasicBlock::iterator(MI)),
10696                   BB->end());
10697   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10698
10699   // Add the true and fallthrough blocks as its successors.
10700   BB->addSuccessor(copy0MBB);
10701   BB->addSuccessor(sinkMBB);
10702
10703   // Create the conditional branch instruction.
10704   unsigned Opc =
10705     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10706   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10707
10708   //  copy0MBB:
10709   //   %FalseValue = ...
10710   //   # fallthrough to sinkMBB
10711   copy0MBB->addSuccessor(sinkMBB);
10712
10713   //  sinkMBB:
10714   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10715   //  ...
10716   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10717           TII->get(X86::PHI), MI->getOperand(0).getReg())
10718     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10719     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10720
10721   MI->eraseFromParent();   // The pseudo instruction is gone now.
10722   return sinkMBB;
10723 }
10724
10725 MachineBasicBlock *
10726 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10727                                           MachineBasicBlock *BB) const {
10728   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10729   DebugLoc DL = MI->getDebugLoc();
10730
10731   assert(!Subtarget->isTargetEnvMacho());
10732
10733   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10734   // non-trivial part is impdef of ESP.
10735
10736   if (Subtarget->isTargetWin64()) {
10737     if (Subtarget->isTargetCygMing()) {
10738       // ___chkstk(Mingw64):
10739       // Clobbers R10, R11, RAX and EFLAGS.
10740       // Updates RSP.
10741       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10742         .addExternalSymbol("___chkstk")
10743         .addReg(X86::RAX, RegState::Implicit)
10744         .addReg(X86::RSP, RegState::Implicit)
10745         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10746         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10747         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10748     } else {
10749       // __chkstk(MSVCRT): does not update stack pointer.
10750       // Clobbers R10, R11 and EFLAGS.
10751       // FIXME: RAX(allocated size) might be reused and not killed.
10752       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10753         .addExternalSymbol("__chkstk")
10754         .addReg(X86::RAX, RegState::Implicit)
10755         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10756       // RAX has the offset to subtracted from RSP.
10757       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10758         .addReg(X86::RSP)
10759         .addReg(X86::RAX);
10760     }
10761   } else {
10762     const char *StackProbeSymbol =
10763       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10764
10765     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10766       .addExternalSymbol(StackProbeSymbol)
10767       .addReg(X86::EAX, RegState::Implicit)
10768       .addReg(X86::ESP, RegState::Implicit)
10769       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10770       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10771       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10772   }
10773
10774   MI->eraseFromParent();   // The pseudo instruction is gone now.
10775   return BB;
10776 }
10777
10778 MachineBasicBlock *
10779 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10780                                       MachineBasicBlock *BB) const {
10781   // This is pretty easy.  We're taking the value that we received from
10782   // our load from the relocation, sticking it in either RDI (x86-64)
10783   // or EAX and doing an indirect call.  The return value will then
10784   // be in the normal return register.
10785   const X86InstrInfo *TII
10786     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10787   DebugLoc DL = MI->getDebugLoc();
10788   MachineFunction *F = BB->getParent();
10789
10790   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10791   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10792
10793   if (Subtarget->is64Bit()) {
10794     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10795                                       TII->get(X86::MOV64rm), X86::RDI)
10796     .addReg(X86::RIP)
10797     .addImm(0).addReg(0)
10798     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10799                       MI->getOperand(3).getTargetFlags())
10800     .addReg(0);
10801     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10802     addDirectMem(MIB, X86::RDI);
10803   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10804     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10805                                       TII->get(X86::MOV32rm), X86::EAX)
10806     .addReg(0)
10807     .addImm(0).addReg(0)
10808     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10809                       MI->getOperand(3).getTargetFlags())
10810     .addReg(0);
10811     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10812     addDirectMem(MIB, X86::EAX);
10813   } else {
10814     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10815                                       TII->get(X86::MOV32rm), X86::EAX)
10816     .addReg(TII->getGlobalBaseReg(F))
10817     .addImm(0).addReg(0)
10818     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10819                       MI->getOperand(3).getTargetFlags())
10820     .addReg(0);
10821     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10822     addDirectMem(MIB, X86::EAX);
10823   }
10824
10825   MI->eraseFromParent(); // The pseudo instruction is gone now.
10826   return BB;
10827 }
10828
10829 MachineBasicBlock *
10830 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10831                                                MachineBasicBlock *BB) const {
10832   switch (MI->getOpcode()) {
10833   default: assert(false && "Unexpected instr type to insert");
10834   case X86::TAILJMPd64:
10835   case X86::TAILJMPr64:
10836   case X86::TAILJMPm64:
10837     assert(!"TAILJMP64 would not be touched here.");
10838   case X86::TCRETURNdi64:
10839   case X86::TCRETURNri64:
10840   case X86::TCRETURNmi64:
10841     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10842     // On AMD64, additional defs should be added before register allocation.
10843     if (!Subtarget->isTargetWin64()) {
10844       MI->addRegisterDefined(X86::RSI);
10845       MI->addRegisterDefined(X86::RDI);
10846       MI->addRegisterDefined(X86::XMM6);
10847       MI->addRegisterDefined(X86::XMM7);
10848       MI->addRegisterDefined(X86::XMM8);
10849       MI->addRegisterDefined(X86::XMM9);
10850       MI->addRegisterDefined(X86::XMM10);
10851       MI->addRegisterDefined(X86::XMM11);
10852       MI->addRegisterDefined(X86::XMM12);
10853       MI->addRegisterDefined(X86::XMM13);
10854       MI->addRegisterDefined(X86::XMM14);
10855       MI->addRegisterDefined(X86::XMM15);
10856     }
10857     return BB;
10858   case X86::WIN_ALLOCA:
10859     return EmitLoweredWinAlloca(MI, BB);
10860   case X86::TLSCall_32:
10861   case X86::TLSCall_64:
10862     return EmitLoweredTLSCall(MI, BB);
10863   case X86::CMOV_GR8:
10864   case X86::CMOV_FR32:
10865   case X86::CMOV_FR64:
10866   case X86::CMOV_V4F32:
10867   case X86::CMOV_V2F64:
10868   case X86::CMOV_V2I64:
10869   case X86::CMOV_GR16:
10870   case X86::CMOV_GR32:
10871   case X86::CMOV_RFP32:
10872   case X86::CMOV_RFP64:
10873   case X86::CMOV_RFP80:
10874     return EmitLoweredSelect(MI, BB);
10875
10876   case X86::FP32_TO_INT16_IN_MEM:
10877   case X86::FP32_TO_INT32_IN_MEM:
10878   case X86::FP32_TO_INT64_IN_MEM:
10879   case X86::FP64_TO_INT16_IN_MEM:
10880   case X86::FP64_TO_INT32_IN_MEM:
10881   case X86::FP64_TO_INT64_IN_MEM:
10882   case X86::FP80_TO_INT16_IN_MEM:
10883   case X86::FP80_TO_INT32_IN_MEM:
10884   case X86::FP80_TO_INT64_IN_MEM: {
10885     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10886     DebugLoc DL = MI->getDebugLoc();
10887
10888     // Change the floating point control register to use "round towards zero"
10889     // mode when truncating to an integer value.
10890     MachineFunction *F = BB->getParent();
10891     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10892     addFrameReference(BuildMI(*BB, MI, DL,
10893                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10894
10895     // Load the old value of the high byte of the control word...
10896     unsigned OldCW =
10897       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10898     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10899                       CWFrameIdx);
10900
10901     // Set the high part to be round to zero...
10902     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10903       .addImm(0xC7F);
10904
10905     // Reload the modified control word now...
10906     addFrameReference(BuildMI(*BB, MI, DL,
10907                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10908
10909     // Restore the memory image of control word to original value
10910     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10911       .addReg(OldCW);
10912
10913     // Get the X86 opcode to use.
10914     unsigned Opc;
10915     switch (MI->getOpcode()) {
10916     default: llvm_unreachable("illegal opcode!");
10917     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10918     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10919     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10920     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10921     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10922     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10923     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10924     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10925     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10926     }
10927
10928     X86AddressMode AM;
10929     MachineOperand &Op = MI->getOperand(0);
10930     if (Op.isReg()) {
10931       AM.BaseType = X86AddressMode::RegBase;
10932       AM.Base.Reg = Op.getReg();
10933     } else {
10934       AM.BaseType = X86AddressMode::FrameIndexBase;
10935       AM.Base.FrameIndex = Op.getIndex();
10936     }
10937     Op = MI->getOperand(1);
10938     if (Op.isImm())
10939       AM.Scale = Op.getImm();
10940     Op = MI->getOperand(2);
10941     if (Op.isImm())
10942       AM.IndexReg = Op.getImm();
10943     Op = MI->getOperand(3);
10944     if (Op.isGlobal()) {
10945       AM.GV = Op.getGlobal();
10946     } else {
10947       AM.Disp = Op.getImm();
10948     }
10949     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10950                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10951
10952     // Reload the original control word now.
10953     addFrameReference(BuildMI(*BB, MI, DL,
10954                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10955
10956     MI->eraseFromParent();   // The pseudo instruction is gone now.
10957     return BB;
10958   }
10959     // String/text processing lowering.
10960   case X86::PCMPISTRM128REG:
10961   case X86::VPCMPISTRM128REG:
10962     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10963   case X86::PCMPISTRM128MEM:
10964   case X86::VPCMPISTRM128MEM:
10965     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10966   case X86::PCMPESTRM128REG:
10967   case X86::VPCMPESTRM128REG:
10968     return EmitPCMP(MI, BB, 5, false /* in mem */);
10969   case X86::PCMPESTRM128MEM:
10970   case X86::VPCMPESTRM128MEM:
10971     return EmitPCMP(MI, BB, 5, true /* in mem */);
10972
10973     // Thread synchronization.
10974   case X86::MONITOR:
10975     return EmitMonitor(MI, BB);
10976   case X86::MWAIT:
10977     return EmitMwait(MI, BB);
10978
10979     // Atomic Lowering.
10980   case X86::ATOMAND32:
10981     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10982                                                X86::AND32ri, X86::MOV32rm,
10983                                                X86::LCMPXCHG32,
10984                                                X86::NOT32r, X86::EAX,
10985                                                X86::GR32RegisterClass);
10986   case X86::ATOMOR32:
10987     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10988                                                X86::OR32ri, X86::MOV32rm,
10989                                                X86::LCMPXCHG32,
10990                                                X86::NOT32r, X86::EAX,
10991                                                X86::GR32RegisterClass);
10992   case X86::ATOMXOR32:
10993     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10994                                                X86::XOR32ri, X86::MOV32rm,
10995                                                X86::LCMPXCHG32,
10996                                                X86::NOT32r, X86::EAX,
10997                                                X86::GR32RegisterClass);
10998   case X86::ATOMNAND32:
10999     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11000                                                X86::AND32ri, X86::MOV32rm,
11001                                                X86::LCMPXCHG32,
11002                                                X86::NOT32r, X86::EAX,
11003                                                X86::GR32RegisterClass, true);
11004   case X86::ATOMMIN32:
11005     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11006   case X86::ATOMMAX32:
11007     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11008   case X86::ATOMUMIN32:
11009     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11010   case X86::ATOMUMAX32:
11011     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11012
11013   case X86::ATOMAND16:
11014     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11015                                                X86::AND16ri, X86::MOV16rm,
11016                                                X86::LCMPXCHG16,
11017                                                X86::NOT16r, X86::AX,
11018                                                X86::GR16RegisterClass);
11019   case X86::ATOMOR16:
11020     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11021                                                X86::OR16ri, X86::MOV16rm,
11022                                                X86::LCMPXCHG16,
11023                                                X86::NOT16r, X86::AX,
11024                                                X86::GR16RegisterClass);
11025   case X86::ATOMXOR16:
11026     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11027                                                X86::XOR16ri, X86::MOV16rm,
11028                                                X86::LCMPXCHG16,
11029                                                X86::NOT16r, X86::AX,
11030                                                X86::GR16RegisterClass);
11031   case X86::ATOMNAND16:
11032     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11033                                                X86::AND16ri, X86::MOV16rm,
11034                                                X86::LCMPXCHG16,
11035                                                X86::NOT16r, X86::AX,
11036                                                X86::GR16RegisterClass, true);
11037   case X86::ATOMMIN16:
11038     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11039   case X86::ATOMMAX16:
11040     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11041   case X86::ATOMUMIN16:
11042     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11043   case X86::ATOMUMAX16:
11044     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11045
11046   case X86::ATOMAND8:
11047     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11048                                                X86::AND8ri, X86::MOV8rm,
11049                                                X86::LCMPXCHG8,
11050                                                X86::NOT8r, X86::AL,
11051                                                X86::GR8RegisterClass);
11052   case X86::ATOMOR8:
11053     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11054                                                X86::OR8ri, X86::MOV8rm,
11055                                                X86::LCMPXCHG8,
11056                                                X86::NOT8r, X86::AL,
11057                                                X86::GR8RegisterClass);
11058   case X86::ATOMXOR8:
11059     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11060                                                X86::XOR8ri, X86::MOV8rm,
11061                                                X86::LCMPXCHG8,
11062                                                X86::NOT8r, X86::AL,
11063                                                X86::GR8RegisterClass);
11064   case X86::ATOMNAND8:
11065     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11066                                                X86::AND8ri, X86::MOV8rm,
11067                                                X86::LCMPXCHG8,
11068                                                X86::NOT8r, X86::AL,
11069                                                X86::GR8RegisterClass, true);
11070   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11071   // This group is for 64-bit host.
11072   case X86::ATOMAND64:
11073     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11074                                                X86::AND64ri32, X86::MOV64rm,
11075                                                X86::LCMPXCHG64,
11076                                                X86::NOT64r, X86::RAX,
11077                                                X86::GR64RegisterClass);
11078   case X86::ATOMOR64:
11079     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11080                                                X86::OR64ri32, X86::MOV64rm,
11081                                                X86::LCMPXCHG64,
11082                                                X86::NOT64r, X86::RAX,
11083                                                X86::GR64RegisterClass);
11084   case X86::ATOMXOR64:
11085     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11086                                                X86::XOR64ri32, X86::MOV64rm,
11087                                                X86::LCMPXCHG64,
11088                                                X86::NOT64r, X86::RAX,
11089                                                X86::GR64RegisterClass);
11090   case X86::ATOMNAND64:
11091     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11092                                                X86::AND64ri32, X86::MOV64rm,
11093                                                X86::LCMPXCHG64,
11094                                                X86::NOT64r, X86::RAX,
11095                                                X86::GR64RegisterClass, true);
11096   case X86::ATOMMIN64:
11097     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11098   case X86::ATOMMAX64:
11099     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11100   case X86::ATOMUMIN64:
11101     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11102   case X86::ATOMUMAX64:
11103     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11104
11105   // This group does 64-bit operations on a 32-bit host.
11106   case X86::ATOMAND6432:
11107     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11108                                                X86::AND32rr, X86::AND32rr,
11109                                                X86::AND32ri, X86::AND32ri,
11110                                                false);
11111   case X86::ATOMOR6432:
11112     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11113                                                X86::OR32rr, X86::OR32rr,
11114                                                X86::OR32ri, X86::OR32ri,
11115                                                false);
11116   case X86::ATOMXOR6432:
11117     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11118                                                X86::XOR32rr, X86::XOR32rr,
11119                                                X86::XOR32ri, X86::XOR32ri,
11120                                                false);
11121   case X86::ATOMNAND6432:
11122     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11123                                                X86::AND32rr, X86::AND32rr,
11124                                                X86::AND32ri, X86::AND32ri,
11125                                                true);
11126   case X86::ATOMADD6432:
11127     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11128                                                X86::ADD32rr, X86::ADC32rr,
11129                                                X86::ADD32ri, X86::ADC32ri,
11130                                                false);
11131   case X86::ATOMSUB6432:
11132     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11133                                                X86::SUB32rr, X86::SBB32rr,
11134                                                X86::SUB32ri, X86::SBB32ri,
11135                                                false);
11136   case X86::ATOMSWAP6432:
11137     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11138                                                X86::MOV32rr, X86::MOV32rr,
11139                                                X86::MOV32ri, X86::MOV32ri,
11140                                                false);
11141   case X86::VASTART_SAVE_XMM_REGS:
11142     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11143
11144   case X86::VAARG_64:
11145     return EmitVAARG64WithCustomInserter(MI, BB);
11146   }
11147 }
11148
11149 //===----------------------------------------------------------------------===//
11150 //                           X86 Optimization Hooks
11151 //===----------------------------------------------------------------------===//
11152
11153 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11154                                                        const APInt &Mask,
11155                                                        APInt &KnownZero,
11156                                                        APInt &KnownOne,
11157                                                        const SelectionDAG &DAG,
11158                                                        unsigned Depth) const {
11159   unsigned Opc = Op.getOpcode();
11160   assert((Opc >= ISD::BUILTIN_OP_END ||
11161           Opc == ISD::INTRINSIC_WO_CHAIN ||
11162           Opc == ISD::INTRINSIC_W_CHAIN ||
11163           Opc == ISD::INTRINSIC_VOID) &&
11164          "Should use MaskedValueIsZero if you don't know whether Op"
11165          " is a target node!");
11166
11167   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11168   switch (Opc) {
11169   default: break;
11170   case X86ISD::ADD:
11171   case X86ISD::SUB:
11172   case X86ISD::ADC:
11173   case X86ISD::SBB:
11174   case X86ISD::SMUL:
11175   case X86ISD::UMUL:
11176   case X86ISD::INC:
11177   case X86ISD::DEC:
11178   case X86ISD::OR:
11179   case X86ISD::XOR:
11180   case X86ISD::AND:
11181     // These nodes' second result is a boolean.
11182     if (Op.getResNo() == 0)
11183       break;
11184     // Fallthrough
11185   case X86ISD::SETCC:
11186     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11187                                        Mask.getBitWidth() - 1);
11188     break;
11189   }
11190 }
11191
11192 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11193                                                          unsigned Depth) const {
11194   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11195   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11196     return Op.getValueType().getScalarType().getSizeInBits();
11197
11198   // Fallback case.
11199   return 1;
11200 }
11201
11202 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11203 /// node is a GlobalAddress + offset.
11204 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11205                                        const GlobalValue* &GA,
11206                                        int64_t &Offset) const {
11207   if (N->getOpcode() == X86ISD::Wrapper) {
11208     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11209       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11210       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11211       return true;
11212     }
11213   }
11214   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11215 }
11216
11217 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11218 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11219 /// if the load addresses are consecutive, non-overlapping, and in the right
11220 /// order.
11221 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11222                                      TargetLowering::DAGCombinerInfo &DCI) {
11223   DebugLoc dl = N->getDebugLoc();
11224   EVT VT = N->getValueType(0);
11225
11226   if (VT.getSizeInBits() != 128)
11227     return SDValue();
11228
11229   // Don't create instructions with illegal types after legalize types has run.
11230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11231   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11232     return SDValue();
11233
11234   SmallVector<SDValue, 16> Elts;
11235   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11236     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11237
11238   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11239 }
11240
11241 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11242 /// generation and convert it from being a bunch of shuffles and extracts
11243 /// to a simple store and scalar loads to extract the elements.
11244 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11245                                                 const TargetLowering &TLI) {
11246   SDValue InputVector = N->getOperand(0);
11247
11248   // Only operate on vectors of 4 elements, where the alternative shuffling
11249   // gets to be more expensive.
11250   if (InputVector.getValueType() != MVT::v4i32)
11251     return SDValue();
11252
11253   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11254   // single use which is a sign-extend or zero-extend, and all elements are
11255   // used.
11256   SmallVector<SDNode *, 4> Uses;
11257   unsigned ExtractedElements = 0;
11258   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11259        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11260     if (UI.getUse().getResNo() != InputVector.getResNo())
11261       return SDValue();
11262
11263     SDNode *Extract = *UI;
11264     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11265       return SDValue();
11266
11267     if (Extract->getValueType(0) != MVT::i32)
11268       return SDValue();
11269     if (!Extract->hasOneUse())
11270       return SDValue();
11271     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11272         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11273       return SDValue();
11274     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11275       return SDValue();
11276
11277     // Record which element was extracted.
11278     ExtractedElements |=
11279       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11280
11281     Uses.push_back(Extract);
11282   }
11283
11284   // If not all the elements were used, this may not be worthwhile.
11285   if (ExtractedElements != 15)
11286     return SDValue();
11287
11288   // Ok, we've now decided to do the transformation.
11289   DebugLoc dl = InputVector.getDebugLoc();
11290
11291   // Store the value to a temporary stack slot.
11292   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11293   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11294                             MachinePointerInfo(), false, false, 0);
11295
11296   // Replace each use (extract) with a load of the appropriate element.
11297   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11298        UE = Uses.end(); UI != UE; ++UI) {
11299     SDNode *Extract = *UI;
11300
11301     // cOMpute the element's address.
11302     SDValue Idx = Extract->getOperand(1);
11303     unsigned EltSize =
11304         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11305     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11306     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11307
11308     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11309                                      StackPtr, OffsetVal);
11310
11311     // Load the scalar.
11312     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11313                                      ScalarAddr, MachinePointerInfo(),
11314                                      false, false, 0);
11315
11316     // Replace the exact with the load.
11317     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11318   }
11319
11320   // The replacement was made in place; don't return anything.
11321   return SDValue();
11322 }
11323
11324 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11325 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11326                                     const X86Subtarget *Subtarget) {
11327   DebugLoc DL = N->getDebugLoc();
11328   SDValue Cond = N->getOperand(0);
11329   // Get the LHS/RHS of the select.
11330   SDValue LHS = N->getOperand(1);
11331   SDValue RHS = N->getOperand(2);
11332
11333   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11334   // instructions match the semantics of the common C idiom x<y?x:y but not
11335   // x<=y?x:y, because of how they handle negative zero (which can be
11336   // ignored in unsafe-math mode).
11337   if (Subtarget->hasSSE2() &&
11338       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11339       Cond.getOpcode() == ISD::SETCC) {
11340     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11341
11342     unsigned Opcode = 0;
11343     // Check for x CC y ? x : y.
11344     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11345         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11346       switch (CC) {
11347       default: break;
11348       case ISD::SETULT:
11349         // Converting this to a min would handle NaNs incorrectly, and swapping
11350         // the operands would cause it to handle comparisons between positive
11351         // and negative zero incorrectly.
11352         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11353           if (!UnsafeFPMath &&
11354               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11355             break;
11356           std::swap(LHS, RHS);
11357         }
11358         Opcode = X86ISD::FMIN;
11359         break;
11360       case ISD::SETOLE:
11361         // Converting this to a min would handle comparisons between positive
11362         // and negative zero incorrectly.
11363         if (!UnsafeFPMath &&
11364             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11365           break;
11366         Opcode = X86ISD::FMIN;
11367         break;
11368       case ISD::SETULE:
11369         // Converting this to a min would handle both negative zeros and NaNs
11370         // incorrectly, but we can swap the operands to fix both.
11371         std::swap(LHS, RHS);
11372       case ISD::SETOLT:
11373       case ISD::SETLT:
11374       case ISD::SETLE:
11375         Opcode = X86ISD::FMIN;
11376         break;
11377
11378       case ISD::SETOGE:
11379         // Converting this to a max would handle comparisons between positive
11380         // and negative zero incorrectly.
11381         if (!UnsafeFPMath &&
11382             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11383           break;
11384         Opcode = X86ISD::FMAX;
11385         break;
11386       case ISD::SETUGT:
11387         // Converting this to a max would handle NaNs incorrectly, and swapping
11388         // the operands would cause it to handle comparisons between positive
11389         // and negative zero incorrectly.
11390         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11391           if (!UnsafeFPMath &&
11392               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11393             break;
11394           std::swap(LHS, RHS);
11395         }
11396         Opcode = X86ISD::FMAX;
11397         break;
11398       case ISD::SETUGE:
11399         // Converting this to a max would handle both negative zeros and NaNs
11400         // incorrectly, but we can swap the operands to fix both.
11401         std::swap(LHS, RHS);
11402       case ISD::SETOGT:
11403       case ISD::SETGT:
11404       case ISD::SETGE:
11405         Opcode = X86ISD::FMAX;
11406         break;
11407       }
11408     // Check for x CC y ? y : x -- a min/max with reversed arms.
11409     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11410                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11411       switch (CC) {
11412       default: break;
11413       case ISD::SETOGE:
11414         // Converting this to a min would handle comparisons between positive
11415         // and negative zero incorrectly, and swapping the operands would
11416         // cause it to handle NaNs incorrectly.
11417         if (!UnsafeFPMath &&
11418             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11419           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11420             break;
11421           std::swap(LHS, RHS);
11422         }
11423         Opcode = X86ISD::FMIN;
11424         break;
11425       case ISD::SETUGT:
11426         // Converting this to a min would handle NaNs incorrectly.
11427         if (!UnsafeFPMath &&
11428             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11429           break;
11430         Opcode = X86ISD::FMIN;
11431         break;
11432       case ISD::SETUGE:
11433         // Converting this to a min would handle both negative zeros and NaNs
11434         // incorrectly, but we can swap the operands to fix both.
11435         std::swap(LHS, RHS);
11436       case ISD::SETOGT:
11437       case ISD::SETGT:
11438       case ISD::SETGE:
11439         Opcode = X86ISD::FMIN;
11440         break;
11441
11442       case ISD::SETULT:
11443         // Converting this to a max would handle NaNs incorrectly.
11444         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11445           break;
11446         Opcode = X86ISD::FMAX;
11447         break;
11448       case ISD::SETOLE:
11449         // Converting this to a max would handle comparisons between positive
11450         // and negative zero incorrectly, and swapping the operands would
11451         // cause it to handle NaNs incorrectly.
11452         if (!UnsafeFPMath &&
11453             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11454           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11455             break;
11456           std::swap(LHS, RHS);
11457         }
11458         Opcode = X86ISD::FMAX;
11459         break;
11460       case ISD::SETULE:
11461         // Converting this to a max would handle both negative zeros and NaNs
11462         // incorrectly, but we can swap the operands to fix both.
11463         std::swap(LHS, RHS);
11464       case ISD::SETOLT:
11465       case ISD::SETLT:
11466       case ISD::SETLE:
11467         Opcode = X86ISD::FMAX;
11468         break;
11469       }
11470     }
11471
11472     if (Opcode)
11473       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11474   }
11475
11476   // If this is a select between two integer constants, try to do some
11477   // optimizations.
11478   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11479     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11480       // Don't do this for crazy integer types.
11481       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11482         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11483         // so that TrueC (the true value) is larger than FalseC.
11484         bool NeedsCondInvert = false;
11485
11486         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11487             // Efficiently invertible.
11488             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11489              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11490               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11491           NeedsCondInvert = true;
11492           std::swap(TrueC, FalseC);
11493         }
11494
11495         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11496         if (FalseC->getAPIntValue() == 0 &&
11497             TrueC->getAPIntValue().isPowerOf2()) {
11498           if (NeedsCondInvert) // Invert the condition if needed.
11499             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11500                                DAG.getConstant(1, Cond.getValueType()));
11501
11502           // Zero extend the condition if needed.
11503           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11504
11505           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11506           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11507                              DAG.getConstant(ShAmt, MVT::i8));
11508         }
11509
11510         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11511         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11512           if (NeedsCondInvert) // Invert the condition if needed.
11513             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11514                                DAG.getConstant(1, Cond.getValueType()));
11515
11516           // Zero extend the condition if needed.
11517           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11518                              FalseC->getValueType(0), Cond);
11519           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11520                              SDValue(FalseC, 0));
11521         }
11522
11523         // Optimize cases that will turn into an LEA instruction.  This requires
11524         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11525         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11526           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11527           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11528
11529           bool isFastMultiplier = false;
11530           if (Diff < 10) {
11531             switch ((unsigned char)Diff) {
11532               default: break;
11533               case 1:  // result = add base, cond
11534               case 2:  // result = lea base(    , cond*2)
11535               case 3:  // result = lea base(cond, cond*2)
11536               case 4:  // result = lea base(    , cond*4)
11537               case 5:  // result = lea base(cond, cond*4)
11538               case 8:  // result = lea base(    , cond*8)
11539               case 9:  // result = lea base(cond, cond*8)
11540                 isFastMultiplier = true;
11541                 break;
11542             }
11543           }
11544
11545           if (isFastMultiplier) {
11546             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11547             if (NeedsCondInvert) // Invert the condition if needed.
11548               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11549                                  DAG.getConstant(1, Cond.getValueType()));
11550
11551             // Zero extend the condition if needed.
11552             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11553                                Cond);
11554             // Scale the condition by the difference.
11555             if (Diff != 1)
11556               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11557                                  DAG.getConstant(Diff, Cond.getValueType()));
11558
11559             // Add the base if non-zero.
11560             if (FalseC->getAPIntValue() != 0)
11561               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11562                                  SDValue(FalseC, 0));
11563             return Cond;
11564           }
11565         }
11566       }
11567   }
11568
11569   return SDValue();
11570 }
11571
11572 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11573 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11574                                   TargetLowering::DAGCombinerInfo &DCI) {
11575   DebugLoc DL = N->getDebugLoc();
11576
11577   // If the flag operand isn't dead, don't touch this CMOV.
11578   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11579     return SDValue();
11580
11581   SDValue FalseOp = N->getOperand(0);
11582   SDValue TrueOp = N->getOperand(1);
11583   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11584   SDValue Cond = N->getOperand(3);
11585   if (CC == X86::COND_E || CC == X86::COND_NE) {
11586     switch (Cond.getOpcode()) {
11587     default: break;
11588     case X86ISD::BSR:
11589     case X86ISD::BSF:
11590       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11591       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11592         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11593     }
11594   }
11595
11596   // If this is a select between two integer constants, try to do some
11597   // optimizations.  Note that the operands are ordered the opposite of SELECT
11598   // operands.
11599   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11600     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11601       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11602       // larger than FalseC (the false value).
11603       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11604         CC = X86::GetOppositeBranchCondition(CC);
11605         std::swap(TrueC, FalseC);
11606       }
11607
11608       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11609       // This is efficient for any integer data type (including i8/i16) and
11610       // shift amount.
11611       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11612         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11613                            DAG.getConstant(CC, MVT::i8), Cond);
11614
11615         // Zero extend the condition if needed.
11616         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11617
11618         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11619         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11620                            DAG.getConstant(ShAmt, MVT::i8));
11621         if (N->getNumValues() == 2)  // Dead flag value?
11622           return DCI.CombineTo(N, Cond, SDValue());
11623         return Cond;
11624       }
11625
11626       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11627       // for any integer data type, including i8/i16.
11628       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11629         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11630                            DAG.getConstant(CC, MVT::i8), Cond);
11631
11632         // Zero extend the condition if needed.
11633         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11634                            FalseC->getValueType(0), Cond);
11635         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11636                            SDValue(FalseC, 0));
11637
11638         if (N->getNumValues() == 2)  // Dead flag value?
11639           return DCI.CombineTo(N, Cond, SDValue());
11640         return Cond;
11641       }
11642
11643       // Optimize cases that will turn into an LEA instruction.  This requires
11644       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11645       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11646         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11647         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11648
11649         bool isFastMultiplier = false;
11650         if (Diff < 10) {
11651           switch ((unsigned char)Diff) {
11652           default: break;
11653           case 1:  // result = add base, cond
11654           case 2:  // result = lea base(    , cond*2)
11655           case 3:  // result = lea base(cond, cond*2)
11656           case 4:  // result = lea base(    , cond*4)
11657           case 5:  // result = lea base(cond, cond*4)
11658           case 8:  // result = lea base(    , cond*8)
11659           case 9:  // result = lea base(cond, cond*8)
11660             isFastMultiplier = true;
11661             break;
11662           }
11663         }
11664
11665         if (isFastMultiplier) {
11666           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11667           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11668                              DAG.getConstant(CC, MVT::i8), Cond);
11669           // Zero extend the condition if needed.
11670           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11671                              Cond);
11672           // Scale the condition by the difference.
11673           if (Diff != 1)
11674             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11675                                DAG.getConstant(Diff, Cond.getValueType()));
11676
11677           // Add the base if non-zero.
11678           if (FalseC->getAPIntValue() != 0)
11679             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11680                                SDValue(FalseC, 0));
11681           if (N->getNumValues() == 2)  // Dead flag value?
11682             return DCI.CombineTo(N, Cond, SDValue());
11683           return Cond;
11684         }
11685       }
11686     }
11687   }
11688   return SDValue();
11689 }
11690
11691
11692 /// PerformMulCombine - Optimize a single multiply with constant into two
11693 /// in order to implement it with two cheaper instructions, e.g.
11694 /// LEA + SHL, LEA + LEA.
11695 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11696                                  TargetLowering::DAGCombinerInfo &DCI) {
11697   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11698     return SDValue();
11699
11700   EVT VT = N->getValueType(0);
11701   if (VT != MVT::i64)
11702     return SDValue();
11703
11704   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11705   if (!C)
11706     return SDValue();
11707   uint64_t MulAmt = C->getZExtValue();
11708   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11709     return SDValue();
11710
11711   uint64_t MulAmt1 = 0;
11712   uint64_t MulAmt2 = 0;
11713   if ((MulAmt % 9) == 0) {
11714     MulAmt1 = 9;
11715     MulAmt2 = MulAmt / 9;
11716   } else if ((MulAmt % 5) == 0) {
11717     MulAmt1 = 5;
11718     MulAmt2 = MulAmt / 5;
11719   } else if ((MulAmt % 3) == 0) {
11720     MulAmt1 = 3;
11721     MulAmt2 = MulAmt / 3;
11722   }
11723   if (MulAmt2 &&
11724       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11725     DebugLoc DL = N->getDebugLoc();
11726
11727     if (isPowerOf2_64(MulAmt2) &&
11728         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11729       // If second multiplifer is pow2, issue it first. We want the multiply by
11730       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11731       // is an add.
11732       std::swap(MulAmt1, MulAmt2);
11733
11734     SDValue NewMul;
11735     if (isPowerOf2_64(MulAmt1))
11736       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11737                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11738     else
11739       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11740                            DAG.getConstant(MulAmt1, VT));
11741
11742     if (isPowerOf2_64(MulAmt2))
11743       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11744                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11745     else
11746       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11747                            DAG.getConstant(MulAmt2, VT));
11748
11749     // Do not add new nodes to DAG combiner worklist.
11750     DCI.CombineTo(N, NewMul, false);
11751   }
11752   return SDValue();
11753 }
11754
11755 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11756   SDValue N0 = N->getOperand(0);
11757   SDValue N1 = N->getOperand(1);
11758   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11759   EVT VT = N0.getValueType();
11760
11761   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11762   // since the result of setcc_c is all zero's or all ones.
11763   if (N1C && N0.getOpcode() == ISD::AND &&
11764       N0.getOperand(1).getOpcode() == ISD::Constant) {
11765     SDValue N00 = N0.getOperand(0);
11766     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11767         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11768           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11769          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11770       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11771       APInt ShAmt = N1C->getAPIntValue();
11772       Mask = Mask.shl(ShAmt);
11773       if (Mask != 0)
11774         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11775                            N00, DAG.getConstant(Mask, VT));
11776     }
11777   }
11778
11779   return SDValue();
11780 }
11781
11782 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11783 ///                       when possible.
11784 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11785                                    const X86Subtarget *Subtarget) {
11786   EVT VT = N->getValueType(0);
11787   if (!VT.isVector() && VT.isInteger() &&
11788       N->getOpcode() == ISD::SHL)
11789     return PerformSHLCombine(N, DAG);
11790
11791   // On X86 with SSE2 support, we can transform this to a vector shift if
11792   // all elements are shifted by the same amount.  We can't do this in legalize
11793   // because the a constant vector is typically transformed to a constant pool
11794   // so we have no knowledge of the shift amount.
11795   if (!Subtarget->hasSSE2())
11796     return SDValue();
11797
11798   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11799     return SDValue();
11800
11801   SDValue ShAmtOp = N->getOperand(1);
11802   EVT EltVT = VT.getVectorElementType();
11803   DebugLoc DL = N->getDebugLoc();
11804   SDValue BaseShAmt = SDValue();
11805   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11806     unsigned NumElts = VT.getVectorNumElements();
11807     unsigned i = 0;
11808     for (; i != NumElts; ++i) {
11809       SDValue Arg = ShAmtOp.getOperand(i);
11810       if (Arg.getOpcode() == ISD::UNDEF) continue;
11811       BaseShAmt = Arg;
11812       break;
11813     }
11814     for (; i != NumElts; ++i) {
11815       SDValue Arg = ShAmtOp.getOperand(i);
11816       if (Arg.getOpcode() == ISD::UNDEF) continue;
11817       if (Arg != BaseShAmt) {
11818         return SDValue();
11819       }
11820     }
11821   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11822              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11823     SDValue InVec = ShAmtOp.getOperand(0);
11824     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11825       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11826       unsigned i = 0;
11827       for (; i != NumElts; ++i) {
11828         SDValue Arg = InVec.getOperand(i);
11829         if (Arg.getOpcode() == ISD::UNDEF) continue;
11830         BaseShAmt = Arg;
11831         break;
11832       }
11833     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11834        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11835          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11836          if (C->getZExtValue() == SplatIdx)
11837            BaseShAmt = InVec.getOperand(1);
11838        }
11839     }
11840     if (BaseShAmt.getNode() == 0)
11841       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11842                               DAG.getIntPtrConstant(0));
11843   } else
11844     return SDValue();
11845
11846   // The shift amount is an i32.
11847   if (EltVT.bitsGT(MVT::i32))
11848     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11849   else if (EltVT.bitsLT(MVT::i32))
11850     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11851
11852   // The shift amount is identical so we can do a vector shift.
11853   SDValue  ValOp = N->getOperand(0);
11854   switch (N->getOpcode()) {
11855   default:
11856     llvm_unreachable("Unknown shift opcode!");
11857     break;
11858   case ISD::SHL:
11859     if (VT == MVT::v2i64)
11860       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11861                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11862                          ValOp, BaseShAmt);
11863     if (VT == MVT::v4i32)
11864       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11865                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11866                          ValOp, BaseShAmt);
11867     if (VT == MVT::v8i16)
11868       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11869                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11870                          ValOp, BaseShAmt);
11871     break;
11872   case ISD::SRA:
11873     if (VT == MVT::v4i32)
11874       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11875                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11876                          ValOp, BaseShAmt);
11877     if (VT == MVT::v8i16)
11878       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11879                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11880                          ValOp, BaseShAmt);
11881     break;
11882   case ISD::SRL:
11883     if (VT == MVT::v2i64)
11884       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11885                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11886                          ValOp, BaseShAmt);
11887     if (VT == MVT::v4i32)
11888       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11889                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11890                          ValOp, BaseShAmt);
11891     if (VT ==  MVT::v8i16)
11892       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11893                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11894                          ValOp, BaseShAmt);
11895     break;
11896   }
11897   return SDValue();
11898 }
11899
11900
11901 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11902 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11903 // and friends.  Likewise for OR -> CMPNEQSS.
11904 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11905                             TargetLowering::DAGCombinerInfo &DCI,
11906                             const X86Subtarget *Subtarget) {
11907   unsigned opcode;
11908
11909   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11910   // we're requiring SSE2 for both.
11911   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11912     SDValue N0 = N->getOperand(0);
11913     SDValue N1 = N->getOperand(1);
11914     SDValue CMP0 = N0->getOperand(1);
11915     SDValue CMP1 = N1->getOperand(1);
11916     DebugLoc DL = N->getDebugLoc();
11917
11918     // The SETCCs should both refer to the same CMP.
11919     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11920       return SDValue();
11921
11922     SDValue CMP00 = CMP0->getOperand(0);
11923     SDValue CMP01 = CMP0->getOperand(1);
11924     EVT     VT    = CMP00.getValueType();
11925
11926     if (VT == MVT::f32 || VT == MVT::f64) {
11927       bool ExpectingFlags = false;
11928       // Check for any users that want flags:
11929       for (SDNode::use_iterator UI = N->use_begin(),
11930              UE = N->use_end();
11931            !ExpectingFlags && UI != UE; ++UI)
11932         switch (UI->getOpcode()) {
11933         default:
11934         case ISD::BR_CC:
11935         case ISD::BRCOND:
11936         case ISD::SELECT:
11937           ExpectingFlags = true;
11938           break;
11939         case ISD::CopyToReg:
11940         case ISD::SIGN_EXTEND:
11941         case ISD::ZERO_EXTEND:
11942         case ISD::ANY_EXTEND:
11943           break;
11944         }
11945
11946       if (!ExpectingFlags) {
11947         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11948         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11949
11950         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11951           X86::CondCode tmp = cc0;
11952           cc0 = cc1;
11953           cc1 = tmp;
11954         }
11955
11956         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11957             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11958           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11959           X86ISD::NodeType NTOperator = is64BitFP ?
11960             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11961           // FIXME: need symbolic constants for these magic numbers.
11962           // See X86ATTInstPrinter.cpp:printSSECC().
11963           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11964           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11965                                               DAG.getConstant(x86cc, MVT::i8));
11966           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11967                                               OnesOrZeroesF);
11968           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11969                                       DAG.getConstant(1, MVT::i32));
11970           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11971           return OneBitOfTruth;
11972         }
11973       }
11974     }
11975   }
11976   return SDValue();
11977 }
11978
11979 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11980                                  TargetLowering::DAGCombinerInfo &DCI,
11981                                  const X86Subtarget *Subtarget) {
11982   if (DCI.isBeforeLegalizeOps())
11983     return SDValue();
11984
11985   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11986   if (R.getNode())
11987     return R;
11988
11989   // Want to form ANDNP nodes:
11990   // 1) In the hopes of then easily combining them with OR and AND nodes
11991   //    to form PBLEND/PSIGN.
11992   // 2) To match ANDN packed intrinsics
11993   EVT VT = N->getValueType(0);
11994   if (VT != MVT::v2i64 && VT != MVT::v4i64)
11995     return SDValue();
11996
11997   SDValue N0 = N->getOperand(0);
11998   SDValue N1 = N->getOperand(1);
11999   DebugLoc DL = N->getDebugLoc();
12000
12001   // Check LHS for vnot
12002   if (N0.getOpcode() == ISD::XOR &&
12003       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12004     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12005
12006   // Check RHS for vnot
12007   if (N1.getOpcode() == ISD::XOR &&
12008       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12009     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12010
12011   return SDValue();
12012 }
12013
12014 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12015                                 TargetLowering::DAGCombinerInfo &DCI,
12016                                 const X86Subtarget *Subtarget) {
12017   if (DCI.isBeforeLegalizeOps())
12018     return SDValue();
12019
12020   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12021   if (R.getNode())
12022     return R;
12023
12024   EVT VT = N->getValueType(0);
12025   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12026     return SDValue();
12027
12028   SDValue N0 = N->getOperand(0);
12029   SDValue N1 = N->getOperand(1);
12030
12031   // look for psign/blend
12032   if (Subtarget->hasSSSE3()) {
12033     if (VT == MVT::v2i64) {
12034       // Canonicalize pandn to RHS
12035       if (N0.getOpcode() == X86ISD::ANDNP)
12036         std::swap(N0, N1);
12037       // or (and (m, x), (pandn m, y))
12038       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12039         SDValue Mask = N1.getOperand(0);
12040         SDValue X    = N1.getOperand(1);
12041         SDValue Y;
12042         if (N0.getOperand(0) == Mask)
12043           Y = N0.getOperand(1);
12044         if (N0.getOperand(1) == Mask)
12045           Y = N0.getOperand(0);
12046
12047         // Check to see if the mask appeared in both the AND and ANDNP and
12048         if (!Y.getNode())
12049           return SDValue();
12050
12051         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12052         if (Mask.getOpcode() != ISD::BITCAST ||
12053             X.getOpcode() != ISD::BITCAST ||
12054             Y.getOpcode() != ISD::BITCAST)
12055           return SDValue();
12056
12057         // Look through mask bitcast.
12058         Mask = Mask.getOperand(0);
12059         EVT MaskVT = Mask.getValueType();
12060
12061         // Validate that the Mask operand is a vector sra node.  The sra node
12062         // will be an intrinsic.
12063         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12064           return SDValue();
12065
12066         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12067         // there is no psrai.b
12068         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12069         case Intrinsic::x86_sse2_psrai_w:
12070         case Intrinsic::x86_sse2_psrai_d:
12071           break;
12072         default: return SDValue();
12073         }
12074
12075         // Check that the SRA is all signbits.
12076         SDValue SraC = Mask.getOperand(2);
12077         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
12078         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12079         if ((SraAmt + 1) != EltBits)
12080           return SDValue();
12081
12082         DebugLoc DL = N->getDebugLoc();
12083
12084         // Now we know we at least have a plendvb with the mask val.  See if
12085         // we can form a psignb/w/d.
12086         // psign = x.type == y.type == mask.type && y = sub(0, x);
12087         X = X.getOperand(0);
12088         Y = Y.getOperand(0);
12089         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12090             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12091             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12092           unsigned Opc = 0;
12093           switch (EltBits) {
12094           case 8: Opc = X86ISD::PSIGNB; break;
12095           case 16: Opc = X86ISD::PSIGNW; break;
12096           case 32: Opc = X86ISD::PSIGND; break;
12097           default: break;
12098           }
12099           if (Opc) {
12100             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12101             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12102           }
12103         }
12104         // PBLENDVB only available on SSE 4.1
12105         if (!Subtarget->hasSSE41())
12106           return SDValue();
12107
12108         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12109         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12110         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12111         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12112         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12113       }
12114     }
12115   }
12116
12117   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12118   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12119     std::swap(N0, N1);
12120   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12121     return SDValue();
12122   if (!N0.hasOneUse() || !N1.hasOneUse())
12123     return SDValue();
12124
12125   SDValue ShAmt0 = N0.getOperand(1);
12126   if (ShAmt0.getValueType() != MVT::i8)
12127     return SDValue();
12128   SDValue ShAmt1 = N1.getOperand(1);
12129   if (ShAmt1.getValueType() != MVT::i8)
12130     return SDValue();
12131   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12132     ShAmt0 = ShAmt0.getOperand(0);
12133   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12134     ShAmt1 = ShAmt1.getOperand(0);
12135
12136   DebugLoc DL = N->getDebugLoc();
12137   unsigned Opc = X86ISD::SHLD;
12138   SDValue Op0 = N0.getOperand(0);
12139   SDValue Op1 = N1.getOperand(0);
12140   if (ShAmt0.getOpcode() == ISD::SUB) {
12141     Opc = X86ISD::SHRD;
12142     std::swap(Op0, Op1);
12143     std::swap(ShAmt0, ShAmt1);
12144   }
12145
12146   unsigned Bits = VT.getSizeInBits();
12147   if (ShAmt1.getOpcode() == ISD::SUB) {
12148     SDValue Sum = ShAmt1.getOperand(0);
12149     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12150       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12151       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12152         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12153       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12154         return DAG.getNode(Opc, DL, VT,
12155                            Op0, Op1,
12156                            DAG.getNode(ISD::TRUNCATE, DL,
12157                                        MVT::i8, ShAmt0));
12158     }
12159   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12160     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12161     if (ShAmt0C &&
12162         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12163       return DAG.getNode(Opc, DL, VT,
12164                          N0.getOperand(0), N1.getOperand(0),
12165                          DAG.getNode(ISD::TRUNCATE, DL,
12166                                        MVT::i8, ShAmt0));
12167   }
12168
12169   return SDValue();
12170 }
12171
12172 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12173 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12174                                    const X86Subtarget *Subtarget) {
12175   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12176   // the FP state in cases where an emms may be missing.
12177   // A preferable solution to the general problem is to figure out the right
12178   // places to insert EMMS.  This qualifies as a quick hack.
12179
12180   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12181   StoreSDNode *St = cast<StoreSDNode>(N);
12182   EVT VT = St->getValue().getValueType();
12183   if (VT.getSizeInBits() != 64)
12184     return SDValue();
12185
12186   const Function *F = DAG.getMachineFunction().getFunction();
12187   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12188   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12189     && Subtarget->hasSSE2();
12190   if ((VT.isVector() ||
12191        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12192       isa<LoadSDNode>(St->getValue()) &&
12193       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12194       St->getChain().hasOneUse() && !St->isVolatile()) {
12195     SDNode* LdVal = St->getValue().getNode();
12196     LoadSDNode *Ld = 0;
12197     int TokenFactorIndex = -1;
12198     SmallVector<SDValue, 8> Ops;
12199     SDNode* ChainVal = St->getChain().getNode();
12200     // Must be a store of a load.  We currently handle two cases:  the load
12201     // is a direct child, and it's under an intervening TokenFactor.  It is
12202     // possible to dig deeper under nested TokenFactors.
12203     if (ChainVal == LdVal)
12204       Ld = cast<LoadSDNode>(St->getChain());
12205     else if (St->getValue().hasOneUse() &&
12206              ChainVal->getOpcode() == ISD::TokenFactor) {
12207       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12208         if (ChainVal->getOperand(i).getNode() == LdVal) {
12209           TokenFactorIndex = i;
12210           Ld = cast<LoadSDNode>(St->getValue());
12211         } else
12212           Ops.push_back(ChainVal->getOperand(i));
12213       }
12214     }
12215
12216     if (!Ld || !ISD::isNormalLoad(Ld))
12217       return SDValue();
12218
12219     // If this is not the MMX case, i.e. we are just turning i64 load/store
12220     // into f64 load/store, avoid the transformation if there are multiple
12221     // uses of the loaded value.
12222     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12223       return SDValue();
12224
12225     DebugLoc LdDL = Ld->getDebugLoc();
12226     DebugLoc StDL = N->getDebugLoc();
12227     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12228     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12229     // pair instead.
12230     if (Subtarget->is64Bit() || F64IsLegal) {
12231       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12232       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12233                                   Ld->getPointerInfo(), Ld->isVolatile(),
12234                                   Ld->isNonTemporal(), Ld->getAlignment());
12235       SDValue NewChain = NewLd.getValue(1);
12236       if (TokenFactorIndex != -1) {
12237         Ops.push_back(NewChain);
12238         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12239                                Ops.size());
12240       }
12241       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12242                           St->getPointerInfo(),
12243                           St->isVolatile(), St->isNonTemporal(),
12244                           St->getAlignment());
12245     }
12246
12247     // Otherwise, lower to two pairs of 32-bit loads / stores.
12248     SDValue LoAddr = Ld->getBasePtr();
12249     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12250                                  DAG.getConstant(4, MVT::i32));
12251
12252     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12253                                Ld->getPointerInfo(),
12254                                Ld->isVolatile(), Ld->isNonTemporal(),
12255                                Ld->getAlignment());
12256     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12257                                Ld->getPointerInfo().getWithOffset(4),
12258                                Ld->isVolatile(), Ld->isNonTemporal(),
12259                                MinAlign(Ld->getAlignment(), 4));
12260
12261     SDValue NewChain = LoLd.getValue(1);
12262     if (TokenFactorIndex != -1) {
12263       Ops.push_back(LoLd);
12264       Ops.push_back(HiLd);
12265       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12266                              Ops.size());
12267     }
12268
12269     LoAddr = St->getBasePtr();
12270     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12271                          DAG.getConstant(4, MVT::i32));
12272
12273     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12274                                 St->getPointerInfo(),
12275                                 St->isVolatile(), St->isNonTemporal(),
12276                                 St->getAlignment());
12277     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12278                                 St->getPointerInfo().getWithOffset(4),
12279                                 St->isVolatile(),
12280                                 St->isNonTemporal(),
12281                                 MinAlign(St->getAlignment(), 4));
12282     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12283   }
12284   return SDValue();
12285 }
12286
12287 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12288 /// X86ISD::FXOR nodes.
12289 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12290   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12291   // F[X]OR(0.0, x) -> x
12292   // F[X]OR(x, 0.0) -> x
12293   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12294     if (C->getValueAPF().isPosZero())
12295       return N->getOperand(1);
12296   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12297     if (C->getValueAPF().isPosZero())
12298       return N->getOperand(0);
12299   return SDValue();
12300 }
12301
12302 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12303 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12304   // FAND(0.0, x) -> 0.0
12305   // FAND(x, 0.0) -> 0.0
12306   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12307     if (C->getValueAPF().isPosZero())
12308       return N->getOperand(0);
12309   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12310     if (C->getValueAPF().isPosZero())
12311       return N->getOperand(1);
12312   return SDValue();
12313 }
12314
12315 static SDValue PerformBTCombine(SDNode *N,
12316                                 SelectionDAG &DAG,
12317                                 TargetLowering::DAGCombinerInfo &DCI) {
12318   // BT ignores high bits in the bit index operand.
12319   SDValue Op1 = N->getOperand(1);
12320   if (Op1.hasOneUse()) {
12321     unsigned BitWidth = Op1.getValueSizeInBits();
12322     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12323     APInt KnownZero, KnownOne;
12324     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12325                                           !DCI.isBeforeLegalizeOps());
12326     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12327     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12328         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12329       DCI.CommitTargetLoweringOpt(TLO);
12330   }
12331   return SDValue();
12332 }
12333
12334 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12335   SDValue Op = N->getOperand(0);
12336   if (Op.getOpcode() == ISD::BITCAST)
12337     Op = Op.getOperand(0);
12338   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12339   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12340       VT.getVectorElementType().getSizeInBits() ==
12341       OpVT.getVectorElementType().getSizeInBits()) {
12342     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12343   }
12344   return SDValue();
12345 }
12346
12347 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12348   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12349   //           (and (i32 x86isd::setcc_carry), 1)
12350   // This eliminates the zext. This transformation is necessary because
12351   // ISD::SETCC is always legalized to i8.
12352   DebugLoc dl = N->getDebugLoc();
12353   SDValue N0 = N->getOperand(0);
12354   EVT VT = N->getValueType(0);
12355   if (N0.getOpcode() == ISD::AND &&
12356       N0.hasOneUse() &&
12357       N0.getOperand(0).hasOneUse()) {
12358     SDValue N00 = N0.getOperand(0);
12359     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12360       return SDValue();
12361     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12362     if (!C || C->getZExtValue() != 1)
12363       return SDValue();
12364     return DAG.getNode(ISD::AND, dl, VT,
12365                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12366                                    N00.getOperand(0), N00.getOperand(1)),
12367                        DAG.getConstant(1, VT));
12368   }
12369
12370   return SDValue();
12371 }
12372
12373 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12374 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12375   unsigned X86CC = N->getConstantOperandVal(0);
12376   SDValue EFLAG = N->getOperand(1);
12377   DebugLoc DL = N->getDebugLoc();
12378
12379   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12380   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12381   // cases.
12382   if (X86CC == X86::COND_B)
12383     return DAG.getNode(ISD::AND, DL, MVT::i8,
12384                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12385                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12386                        DAG.getConstant(1, MVT::i8));
12387
12388   return SDValue();
12389 }
12390
12391 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12392                                         const X86TargetLowering *XTLI) {
12393   SDValue Op0 = N->getOperand(0);
12394   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12395   // a 32-bit target where SSE doesn't support i64->FP operations.
12396   if (Op0.getOpcode() == ISD::LOAD) {
12397     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12398     EVT VT = Ld->getValueType(0);
12399     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12400         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12401         !XTLI->getSubtarget()->is64Bit() &&
12402         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12403       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12404                                           Ld->getChain(), Op0, DAG);
12405       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12406       return FILDChain;
12407     }
12408   }
12409   return SDValue();
12410 }
12411
12412 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12413 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12414                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12415   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12416   // the result is either zero or one (depending on the input carry bit).
12417   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12418   if (X86::isZeroNode(N->getOperand(0)) &&
12419       X86::isZeroNode(N->getOperand(1)) &&
12420       // We don't have a good way to replace an EFLAGS use, so only do this when
12421       // dead right now.
12422       SDValue(N, 1).use_empty()) {
12423     DebugLoc DL = N->getDebugLoc();
12424     EVT VT = N->getValueType(0);
12425     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12426     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12427                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12428                                            DAG.getConstant(X86::COND_B,MVT::i8),
12429                                            N->getOperand(2)),
12430                                DAG.getConstant(1, VT));
12431     return DCI.CombineTo(N, Res1, CarryOut);
12432   }
12433
12434   return SDValue();
12435 }
12436
12437 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12438 //      (add Y, (setne X, 0)) -> sbb -1, Y
12439 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12440 //      (sub (setne X, 0), Y) -> adc -1, Y
12441 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12442   DebugLoc DL = N->getDebugLoc();
12443
12444   // Look through ZExts.
12445   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12446   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12447     return SDValue();
12448
12449   SDValue SetCC = Ext.getOperand(0);
12450   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12451     return SDValue();
12452
12453   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12454   if (CC != X86::COND_E && CC != X86::COND_NE)
12455     return SDValue();
12456
12457   SDValue Cmp = SetCC.getOperand(1);
12458   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12459       !X86::isZeroNode(Cmp.getOperand(1)) ||
12460       !Cmp.getOperand(0).getValueType().isInteger())
12461     return SDValue();
12462
12463   SDValue CmpOp0 = Cmp.getOperand(0);
12464   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12465                                DAG.getConstant(1, CmpOp0.getValueType()));
12466
12467   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12468   if (CC == X86::COND_NE)
12469     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12470                        DL, OtherVal.getValueType(), OtherVal,
12471                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12472   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12473                      DL, OtherVal.getValueType(), OtherVal,
12474                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12475 }
12476
12477 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12478                                              DAGCombinerInfo &DCI) const {
12479   SelectionDAG &DAG = DCI.DAG;
12480   switch (N->getOpcode()) {
12481   default: break;
12482   case ISD::EXTRACT_VECTOR_ELT:
12483     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12484   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12485   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12486   case ISD::ADD:
12487   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12488   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12489   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12490   case ISD::SHL:
12491   case ISD::SRA:
12492   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12493   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12494   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12495   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12496   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12497   case X86ISD::FXOR:
12498   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12499   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12500   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12501   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12502   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12503   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12504   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12505   case X86ISD::SHUFPD:
12506   case X86ISD::PALIGN:
12507   case X86ISD::PUNPCKHBW:
12508   case X86ISD::PUNPCKHWD:
12509   case X86ISD::PUNPCKHDQ:
12510   case X86ISD::PUNPCKHQDQ:
12511   case X86ISD::UNPCKHPS:
12512   case X86ISD::UNPCKHPD:
12513   case X86ISD::PUNPCKLBW:
12514   case X86ISD::PUNPCKLWD:
12515   case X86ISD::PUNPCKLDQ:
12516   case X86ISD::PUNPCKLQDQ:
12517   case X86ISD::UNPCKLPS:
12518   case X86ISD::UNPCKLPD:
12519   case X86ISD::VUNPCKLPS:
12520   case X86ISD::VUNPCKLPD:
12521   case X86ISD::VUNPCKLPSY:
12522   case X86ISD::VUNPCKLPDY:
12523   case X86ISD::MOVHLPS:
12524   case X86ISD::MOVLHPS:
12525   case X86ISD::PSHUFD:
12526   case X86ISD::PSHUFHW:
12527   case X86ISD::PSHUFLW:
12528   case X86ISD::MOVSS:
12529   case X86ISD::MOVSD:
12530   case X86ISD::VPERMIL:
12531   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12532   }
12533
12534   return SDValue();
12535 }
12536
12537 /// isTypeDesirableForOp - Return true if the target has native support for
12538 /// the specified value type and it is 'desirable' to use the type for the
12539 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12540 /// instruction encodings are longer and some i16 instructions are slow.
12541 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12542   if (!isTypeLegal(VT))
12543     return false;
12544   if (VT != MVT::i16)
12545     return true;
12546
12547   switch (Opc) {
12548   default:
12549     return true;
12550   case ISD::LOAD:
12551   case ISD::SIGN_EXTEND:
12552   case ISD::ZERO_EXTEND:
12553   case ISD::ANY_EXTEND:
12554   case ISD::SHL:
12555   case ISD::SRL:
12556   case ISD::SUB:
12557   case ISD::ADD:
12558   case ISD::MUL:
12559   case ISD::AND:
12560   case ISD::OR:
12561   case ISD::XOR:
12562     return false;
12563   }
12564 }
12565
12566 /// IsDesirableToPromoteOp - This method query the target whether it is
12567 /// beneficial for dag combiner to promote the specified node. If true, it
12568 /// should return the desired promotion type by reference.
12569 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12570   EVT VT = Op.getValueType();
12571   if (VT != MVT::i16)
12572     return false;
12573
12574   bool Promote = false;
12575   bool Commute = false;
12576   switch (Op.getOpcode()) {
12577   default: break;
12578   case ISD::LOAD: {
12579     LoadSDNode *LD = cast<LoadSDNode>(Op);
12580     // If the non-extending load has a single use and it's not live out, then it
12581     // might be folded.
12582     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12583                                                      Op.hasOneUse()*/) {
12584       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12585              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12586         // The only case where we'd want to promote LOAD (rather then it being
12587         // promoted as an operand is when it's only use is liveout.
12588         if (UI->getOpcode() != ISD::CopyToReg)
12589           return false;
12590       }
12591     }
12592     Promote = true;
12593     break;
12594   }
12595   case ISD::SIGN_EXTEND:
12596   case ISD::ZERO_EXTEND:
12597   case ISD::ANY_EXTEND:
12598     Promote = true;
12599     break;
12600   case ISD::SHL:
12601   case ISD::SRL: {
12602     SDValue N0 = Op.getOperand(0);
12603     // Look out for (store (shl (load), x)).
12604     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12605       return false;
12606     Promote = true;
12607     break;
12608   }
12609   case ISD::ADD:
12610   case ISD::MUL:
12611   case ISD::AND:
12612   case ISD::OR:
12613   case ISD::XOR:
12614     Commute = true;
12615     // fallthrough
12616   case ISD::SUB: {
12617     SDValue N0 = Op.getOperand(0);
12618     SDValue N1 = Op.getOperand(1);
12619     if (!Commute && MayFoldLoad(N1))
12620       return false;
12621     // Avoid disabling potential load folding opportunities.
12622     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12623       return false;
12624     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12625       return false;
12626     Promote = true;
12627   }
12628   }
12629
12630   PVT = MVT::i32;
12631   return Promote;
12632 }
12633
12634 //===----------------------------------------------------------------------===//
12635 //                           X86 Inline Assembly Support
12636 //===----------------------------------------------------------------------===//
12637
12638 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12639   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12640
12641   std::string AsmStr = IA->getAsmString();
12642
12643   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12644   SmallVector<StringRef, 4> AsmPieces;
12645   SplitString(AsmStr, AsmPieces, ";\n");
12646
12647   switch (AsmPieces.size()) {
12648   default: return false;
12649   case 1:
12650     AsmStr = AsmPieces[0];
12651     AsmPieces.clear();
12652     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12653
12654     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12655     // we will turn this bswap into something that will be lowered to logical ops
12656     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12657     // so don't worry about this.
12658     // bswap $0
12659     if (AsmPieces.size() == 2 &&
12660         (AsmPieces[0] == "bswap" ||
12661          AsmPieces[0] == "bswapq" ||
12662          AsmPieces[0] == "bswapl") &&
12663         (AsmPieces[1] == "$0" ||
12664          AsmPieces[1] == "${0:q}")) {
12665       // No need to check constraints, nothing other than the equivalent of
12666       // "=r,0" would be valid here.
12667       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12668       if (!Ty || Ty->getBitWidth() % 16 != 0)
12669         return false;
12670       return IntrinsicLowering::LowerToByteSwap(CI);
12671     }
12672     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12673     if (CI->getType()->isIntegerTy(16) &&
12674         AsmPieces.size() == 3 &&
12675         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12676         AsmPieces[1] == "$$8," &&
12677         AsmPieces[2] == "${0:w}" &&
12678         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12679       AsmPieces.clear();
12680       const std::string &ConstraintsStr = IA->getConstraintString();
12681       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12682       std::sort(AsmPieces.begin(), AsmPieces.end());
12683       if (AsmPieces.size() == 4 &&
12684           AsmPieces[0] == "~{cc}" &&
12685           AsmPieces[1] == "~{dirflag}" &&
12686           AsmPieces[2] == "~{flags}" &&
12687           AsmPieces[3] == "~{fpsr}") {
12688         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12689         if (!Ty || Ty->getBitWidth() % 16 != 0)
12690           return false;
12691         return IntrinsicLowering::LowerToByteSwap(CI);
12692       }
12693     }
12694     break;
12695   case 3:
12696     if (CI->getType()->isIntegerTy(32) &&
12697         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12698       SmallVector<StringRef, 4> Words;
12699       SplitString(AsmPieces[0], Words, " \t,");
12700       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12701           Words[2] == "${0:w}") {
12702         Words.clear();
12703         SplitString(AsmPieces[1], Words, " \t,");
12704         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12705             Words[2] == "$0") {
12706           Words.clear();
12707           SplitString(AsmPieces[2], Words, " \t,");
12708           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12709               Words[2] == "${0:w}") {
12710             AsmPieces.clear();
12711             const std::string &ConstraintsStr = IA->getConstraintString();
12712             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12713             std::sort(AsmPieces.begin(), AsmPieces.end());
12714             if (AsmPieces.size() == 4 &&
12715                 AsmPieces[0] == "~{cc}" &&
12716                 AsmPieces[1] == "~{dirflag}" &&
12717                 AsmPieces[2] == "~{flags}" &&
12718                 AsmPieces[3] == "~{fpsr}") {
12719               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12720               if (!Ty || Ty->getBitWidth() % 16 != 0)
12721                 return false;
12722               return IntrinsicLowering::LowerToByteSwap(CI);
12723             }
12724           }
12725         }
12726       }
12727     }
12728
12729     if (CI->getType()->isIntegerTy(64)) {
12730       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12731       if (Constraints.size() >= 2 &&
12732           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12733           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12734         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12735         SmallVector<StringRef, 4> Words;
12736         SplitString(AsmPieces[0], Words, " \t");
12737         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12738           Words.clear();
12739           SplitString(AsmPieces[1], Words, " \t");
12740           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12741             Words.clear();
12742             SplitString(AsmPieces[2], Words, " \t,");
12743             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12744                 Words[2] == "%edx") {
12745               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12746               if (!Ty || Ty->getBitWidth() % 16 != 0)
12747                 return false;
12748               return IntrinsicLowering::LowerToByteSwap(CI);
12749             }
12750           }
12751         }
12752       }
12753     }
12754     break;
12755   }
12756   return false;
12757 }
12758
12759
12760
12761 /// getConstraintType - Given a constraint letter, return the type of
12762 /// constraint it is for this target.
12763 X86TargetLowering::ConstraintType
12764 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12765   if (Constraint.size() == 1) {
12766     switch (Constraint[0]) {
12767     case 'R':
12768     case 'q':
12769     case 'Q':
12770     case 'f':
12771     case 't':
12772     case 'u':
12773     case 'y':
12774     case 'x':
12775     case 'Y':
12776     case 'l':
12777       return C_RegisterClass;
12778     case 'a':
12779     case 'b':
12780     case 'c':
12781     case 'd':
12782     case 'S':
12783     case 'D':
12784     case 'A':
12785       return C_Register;
12786     case 'I':
12787     case 'J':
12788     case 'K':
12789     case 'L':
12790     case 'M':
12791     case 'N':
12792     case 'G':
12793     case 'C':
12794     case 'e':
12795     case 'Z':
12796       return C_Other;
12797     default:
12798       break;
12799     }
12800   }
12801   return TargetLowering::getConstraintType(Constraint);
12802 }
12803
12804 /// Examine constraint type and operand type and determine a weight value.
12805 /// This object must already have been set up with the operand type
12806 /// and the current alternative constraint selected.
12807 TargetLowering::ConstraintWeight
12808   X86TargetLowering::getSingleConstraintMatchWeight(
12809     AsmOperandInfo &info, const char *constraint) const {
12810   ConstraintWeight weight = CW_Invalid;
12811   Value *CallOperandVal = info.CallOperandVal;
12812     // If we don't have a value, we can't do a match,
12813     // but allow it at the lowest weight.
12814   if (CallOperandVal == NULL)
12815     return CW_Default;
12816   Type *type = CallOperandVal->getType();
12817   // Look at the constraint type.
12818   switch (*constraint) {
12819   default:
12820     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12821   case 'R':
12822   case 'q':
12823   case 'Q':
12824   case 'a':
12825   case 'b':
12826   case 'c':
12827   case 'd':
12828   case 'S':
12829   case 'D':
12830   case 'A':
12831     if (CallOperandVal->getType()->isIntegerTy())
12832       weight = CW_SpecificReg;
12833     break;
12834   case 'f':
12835   case 't':
12836   case 'u':
12837       if (type->isFloatingPointTy())
12838         weight = CW_SpecificReg;
12839       break;
12840   case 'y':
12841       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12842         weight = CW_SpecificReg;
12843       break;
12844   case 'x':
12845   case 'Y':
12846     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12847       weight = CW_Register;
12848     break;
12849   case 'I':
12850     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12851       if (C->getZExtValue() <= 31)
12852         weight = CW_Constant;
12853     }
12854     break;
12855   case 'J':
12856     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12857       if (C->getZExtValue() <= 63)
12858         weight = CW_Constant;
12859     }
12860     break;
12861   case 'K':
12862     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12863       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12864         weight = CW_Constant;
12865     }
12866     break;
12867   case 'L':
12868     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12869       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12870         weight = CW_Constant;
12871     }
12872     break;
12873   case 'M':
12874     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12875       if (C->getZExtValue() <= 3)
12876         weight = CW_Constant;
12877     }
12878     break;
12879   case 'N':
12880     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12881       if (C->getZExtValue() <= 0xff)
12882         weight = CW_Constant;
12883     }
12884     break;
12885   case 'G':
12886   case 'C':
12887     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12888       weight = CW_Constant;
12889     }
12890     break;
12891   case 'e':
12892     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12893       if ((C->getSExtValue() >= -0x80000000LL) &&
12894           (C->getSExtValue() <= 0x7fffffffLL))
12895         weight = CW_Constant;
12896     }
12897     break;
12898   case 'Z':
12899     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12900       if (C->getZExtValue() <= 0xffffffff)
12901         weight = CW_Constant;
12902     }
12903     break;
12904   }
12905   return weight;
12906 }
12907
12908 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12909 /// with another that has more specific requirements based on the type of the
12910 /// corresponding operand.
12911 const char *X86TargetLowering::
12912 LowerXConstraint(EVT ConstraintVT) const {
12913   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12914   // 'f' like normal targets.
12915   if (ConstraintVT.isFloatingPoint()) {
12916     if (Subtarget->hasXMMInt())
12917       return "Y";
12918     if (Subtarget->hasXMM())
12919       return "x";
12920   }
12921
12922   return TargetLowering::LowerXConstraint(ConstraintVT);
12923 }
12924
12925 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12926 /// vector.  If it is invalid, don't add anything to Ops.
12927 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12928                                                      std::string &Constraint,
12929                                                      std::vector<SDValue>&Ops,
12930                                                      SelectionDAG &DAG) const {
12931   SDValue Result(0, 0);
12932
12933   // Only support length 1 constraints for now.
12934   if (Constraint.length() > 1) return;
12935
12936   char ConstraintLetter = Constraint[0];
12937   switch (ConstraintLetter) {
12938   default: break;
12939   case 'I':
12940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12941       if (C->getZExtValue() <= 31) {
12942         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12943         break;
12944       }
12945     }
12946     return;
12947   case 'J':
12948     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12949       if (C->getZExtValue() <= 63) {
12950         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12951         break;
12952       }
12953     }
12954     return;
12955   case 'K':
12956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12957       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12958         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12959         break;
12960       }
12961     }
12962     return;
12963   case 'N':
12964     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12965       if (C->getZExtValue() <= 255) {
12966         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12967         break;
12968       }
12969     }
12970     return;
12971   case 'e': {
12972     // 32-bit signed value
12973     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12974       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12975                                            C->getSExtValue())) {
12976         // Widen to 64 bits here to get it sign extended.
12977         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12978         break;
12979       }
12980     // FIXME gcc accepts some relocatable values here too, but only in certain
12981     // memory models; it's complicated.
12982     }
12983     return;
12984   }
12985   case 'Z': {
12986     // 32-bit unsigned value
12987     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12988       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12989                                            C->getZExtValue())) {
12990         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12991         break;
12992       }
12993     }
12994     // FIXME gcc accepts some relocatable values here too, but only in certain
12995     // memory models; it's complicated.
12996     return;
12997   }
12998   case 'i': {
12999     // Literal immediates are always ok.
13000     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13001       // Widen to 64 bits here to get it sign extended.
13002       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13003       break;
13004     }
13005
13006     // In any sort of PIC mode addresses need to be computed at runtime by
13007     // adding in a register or some sort of table lookup.  These can't
13008     // be used as immediates.
13009     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13010       return;
13011
13012     // If we are in non-pic codegen mode, we allow the address of a global (with
13013     // an optional displacement) to be used with 'i'.
13014     GlobalAddressSDNode *GA = 0;
13015     int64_t Offset = 0;
13016
13017     // Match either (GA), (GA+C), (GA+C1+C2), etc.
13018     while (1) {
13019       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13020         Offset += GA->getOffset();
13021         break;
13022       } else if (Op.getOpcode() == ISD::ADD) {
13023         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13024           Offset += C->getZExtValue();
13025           Op = Op.getOperand(0);
13026           continue;
13027         }
13028       } else if (Op.getOpcode() == ISD::SUB) {
13029         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13030           Offset += -C->getZExtValue();
13031           Op = Op.getOperand(0);
13032           continue;
13033         }
13034       }
13035
13036       // Otherwise, this isn't something we can handle, reject it.
13037       return;
13038     }
13039
13040     const GlobalValue *GV = GA->getGlobal();
13041     // If we require an extra load to get this address, as in PIC mode, we
13042     // can't accept it.
13043     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
13044                                                         getTargetMachine())))
13045       return;
13046
13047     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
13048                                         GA->getValueType(0), Offset);
13049     break;
13050   }
13051   }
13052
13053   if (Result.getNode()) {
13054     Ops.push_back(Result);
13055     return;
13056   }
13057   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13058 }
13059
13060 std::pair<unsigned, const TargetRegisterClass*>
13061 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
13062                                                 EVT VT) const {
13063   // First, see if this is a constraint that directly corresponds to an LLVM
13064   // register class.
13065   if (Constraint.size() == 1) {
13066     // GCC Constraint Letters
13067     switch (Constraint[0]) {
13068     default: break;
13069       // TODO: Slight differences here in allocation order and leaving
13070       // RIP in the class. Do they matter any more here than they do
13071       // in the normal allocation?
13072     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13073       if (Subtarget->is64Bit()) {
13074         if (VT == MVT::i32 || VT == MVT::f32)
13075           return std::make_pair(0U, X86::GR32RegisterClass);
13076         else if (VT == MVT::i16)
13077           return std::make_pair(0U, X86::GR16RegisterClass);
13078         else if (VT == MVT::i8 || VT == MVT::i1)
13079           return std::make_pair(0U, X86::GR8RegisterClass);
13080         else if (VT == MVT::i64 || VT == MVT::f64)
13081           return std::make_pair(0U, X86::GR64RegisterClass);
13082         break;
13083       }
13084       // 32-bit fallthrough
13085     case 'Q':   // Q_REGS
13086       if (VT == MVT::i32 || VT == MVT::f32)
13087         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
13088       else if (VT == MVT::i16)
13089         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
13090       else if (VT == MVT::i8 || VT == MVT::i1)
13091         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
13092       else if (VT == MVT::i64)
13093         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
13094       break;
13095     case 'r':   // GENERAL_REGS
13096     case 'l':   // INDEX_REGS
13097       if (VT == MVT::i8 || VT == MVT::i1)
13098         return std::make_pair(0U, X86::GR8RegisterClass);
13099       if (VT == MVT::i16)
13100         return std::make_pair(0U, X86::GR16RegisterClass);
13101       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
13102         return std::make_pair(0U, X86::GR32RegisterClass);
13103       return std::make_pair(0U, X86::GR64RegisterClass);
13104     case 'R':   // LEGACY_REGS
13105       if (VT == MVT::i8 || VT == MVT::i1)
13106         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13107       if (VT == MVT::i16)
13108         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13109       if (VT == MVT::i32 || !Subtarget->is64Bit())
13110         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13111       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13112     case 'f':  // FP Stack registers.
13113       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13114       // value to the correct fpstack register class.
13115       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13116         return std::make_pair(0U, X86::RFP32RegisterClass);
13117       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13118         return std::make_pair(0U, X86::RFP64RegisterClass);
13119       return std::make_pair(0U, X86::RFP80RegisterClass);
13120     case 'y':   // MMX_REGS if MMX allowed.
13121       if (!Subtarget->hasMMX()) break;
13122       return std::make_pair(0U, X86::VR64RegisterClass);
13123     case 'Y':   // SSE_REGS if SSE2 allowed
13124       if (!Subtarget->hasXMMInt()) break;
13125       // FALL THROUGH.
13126     case 'x':   // SSE_REGS if SSE1 allowed
13127       if (!Subtarget->hasXMM()) break;
13128
13129       switch (VT.getSimpleVT().SimpleTy) {
13130       default: break;
13131       // Scalar SSE types.
13132       case MVT::f32:
13133       case MVT::i32:
13134         return std::make_pair(0U, X86::FR32RegisterClass);
13135       case MVT::f64:
13136       case MVT::i64:
13137         return std::make_pair(0U, X86::FR64RegisterClass);
13138       // Vector types.
13139       case MVT::v16i8:
13140       case MVT::v8i16:
13141       case MVT::v4i32:
13142       case MVT::v2i64:
13143       case MVT::v4f32:
13144       case MVT::v2f64:
13145         return std::make_pair(0U, X86::VR128RegisterClass);
13146       }
13147       break;
13148     }
13149   }
13150
13151   // Use the default implementation in TargetLowering to convert the register
13152   // constraint into a member of a register class.
13153   std::pair<unsigned, const TargetRegisterClass*> Res;
13154   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13155
13156   // Not found as a standard register?
13157   if (Res.second == 0) {
13158     // Map st(0) -> st(7) -> ST0
13159     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13160         tolower(Constraint[1]) == 's' &&
13161         tolower(Constraint[2]) == 't' &&
13162         Constraint[3] == '(' &&
13163         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13164         Constraint[5] == ')' &&
13165         Constraint[6] == '}') {
13166
13167       Res.first = X86::ST0+Constraint[4]-'0';
13168       Res.second = X86::RFP80RegisterClass;
13169       return Res;
13170     }
13171
13172     // GCC allows "st(0)" to be called just plain "st".
13173     if (StringRef("{st}").equals_lower(Constraint)) {
13174       Res.first = X86::ST0;
13175       Res.second = X86::RFP80RegisterClass;
13176       return Res;
13177     }
13178
13179     // flags -> EFLAGS
13180     if (StringRef("{flags}").equals_lower(Constraint)) {
13181       Res.first = X86::EFLAGS;
13182       Res.second = X86::CCRRegisterClass;
13183       return Res;
13184     }
13185
13186     // 'A' means EAX + EDX.
13187     if (Constraint == "A") {
13188       Res.first = X86::EAX;
13189       Res.second = X86::GR32_ADRegisterClass;
13190       return Res;
13191     }
13192     return Res;
13193   }
13194
13195   // Otherwise, check to see if this is a register class of the wrong value
13196   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13197   // turn into {ax},{dx}.
13198   if (Res.second->hasType(VT))
13199     return Res;   // Correct type already, nothing to do.
13200
13201   // All of the single-register GCC register classes map their values onto
13202   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13203   // really want an 8-bit or 32-bit register, map to the appropriate register
13204   // class and return the appropriate register.
13205   if (Res.second == X86::GR16RegisterClass) {
13206     if (VT == MVT::i8) {
13207       unsigned DestReg = 0;
13208       switch (Res.first) {
13209       default: break;
13210       case X86::AX: DestReg = X86::AL; break;
13211       case X86::DX: DestReg = X86::DL; break;
13212       case X86::CX: DestReg = X86::CL; break;
13213       case X86::BX: DestReg = X86::BL; break;
13214       }
13215       if (DestReg) {
13216         Res.first = DestReg;
13217         Res.second = X86::GR8RegisterClass;
13218       }
13219     } else if (VT == MVT::i32) {
13220       unsigned DestReg = 0;
13221       switch (Res.first) {
13222       default: break;
13223       case X86::AX: DestReg = X86::EAX; break;
13224       case X86::DX: DestReg = X86::EDX; break;
13225       case X86::CX: DestReg = X86::ECX; break;
13226       case X86::BX: DestReg = X86::EBX; break;
13227       case X86::SI: DestReg = X86::ESI; break;
13228       case X86::DI: DestReg = X86::EDI; break;
13229       case X86::BP: DestReg = X86::EBP; break;
13230       case X86::SP: DestReg = X86::ESP; break;
13231       }
13232       if (DestReg) {
13233         Res.first = DestReg;
13234         Res.second = X86::GR32RegisterClass;
13235       }
13236     } else if (VT == MVT::i64) {
13237       unsigned DestReg = 0;
13238       switch (Res.first) {
13239       default: break;
13240       case X86::AX: DestReg = X86::RAX; break;
13241       case X86::DX: DestReg = X86::RDX; break;
13242       case X86::CX: DestReg = X86::RCX; break;
13243       case X86::BX: DestReg = X86::RBX; break;
13244       case X86::SI: DestReg = X86::RSI; break;
13245       case X86::DI: DestReg = X86::RDI; break;
13246       case X86::BP: DestReg = X86::RBP; break;
13247       case X86::SP: DestReg = X86::RSP; break;
13248       }
13249       if (DestReg) {
13250         Res.first = DestReg;
13251         Res.second = X86::GR64RegisterClass;
13252       }
13253     }
13254   } else if (Res.second == X86::FR32RegisterClass ||
13255              Res.second == X86::FR64RegisterClass ||
13256              Res.second == X86::VR128RegisterClass) {
13257     // Handle references to XMM physical registers that got mapped into the
13258     // wrong class.  This can happen with constraints like {xmm0} where the
13259     // target independent register mapper will just pick the first match it can
13260     // find, ignoring the required type.
13261     if (VT == MVT::f32)
13262       Res.second = X86::FR32RegisterClass;
13263     else if (VT == MVT::f64)
13264       Res.second = X86::FR64RegisterClass;
13265     else if (X86::VR128RegisterClass->hasType(VT))
13266       Res.second = X86::VR128RegisterClass;
13267   }
13268
13269   return Res;
13270 }