- Move all MOVSS and MOVSD patterns close to their definitions
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
173   X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184
185   // For 64-bit since we have so many registers use the ILP scheduler, for
186   // 32-bit code use the register pressure specific scheduling.
187   if (Subtarget->is64Bit())
188     setSchedulingPreference(Sched::ILP);
189   else
190     setSchedulingPreference(Sched::RegPressure);
191   setStackPointerRegisterToSaveRestore(X86StackPtr);
192
193   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
194     // Setup Windows compiler runtime calls.
195     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
196     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
197     setLibcallName(RTLIB::SREM_I64, "_allrem");
198     setLibcallName(RTLIB::UREM_I64, "_aullrem");
199     setLibcallName(RTLIB::MUL_I64, "_allmul");
200     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
201     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
202     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
203     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
208     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
209   }
210
211   if (Subtarget->isTargetDarwin()) {
212     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
213     setUseUnderscoreSetJmp(false);
214     setUseUnderscoreLongJmp(false);
215   } else if (Subtarget->isTargetMingw()) {
216     // MS runtime is weird: it exports _setjmp, but longjmp!
217     setUseUnderscoreSetJmp(true);
218     setUseUnderscoreLongJmp(false);
219   } else {
220     setUseUnderscoreSetJmp(true);
221     setUseUnderscoreLongJmp(true);
222   }
223
224   // Set up the register classes.
225   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
226   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
227   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
228   if (Subtarget->is64Bit())
229     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
230
231   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232
233   // We don't accept any truncstore of integer registers.
234   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
236   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
237   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
240
241   // SETOEQ and SETUNE require checking two conditions.
242   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
244   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248
249   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250   // operation.
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
254
255   if (Subtarget->is64Bit()) {
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
257     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
258   } else if (!UseSoftFloat) {
259     // We have an algorithm for SSE2->double, and we turn this into a
260     // 64-bit FILD followed by conditional FADD for other targets.
261     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
262     // We have an algorithm for SSE2, and we turn this into a 64-bit
263     // FILD for other targets.
264     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
265   }
266
267   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268   // this operation.
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
270   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
271
272   if (!UseSoftFloat) {
273     // SSE has no i16 to fp conversion, only i32
274     if (X86ScalarSSEf32) {
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
276       // f32 and f64 cases are Legal, f80 case is not
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
278     } else {
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
280       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
281     }
282   } else {
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
284     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
285   }
286
287   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
288   // are Legal, f80 is custom lowered.
289   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
290   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
291
292   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293   // this operation.
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
295   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
296
297   if (X86ScalarSSEf32) {
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
299     // f32 and f64 cases are Legal, f80 case is not
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
301   } else {
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
303     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
304   }
305
306   // Handle FP_TO_UINT by promoting the destination to a larger signed
307   // conversion.
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
311
312   if (Subtarget->is64Bit()) {
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
314     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
315   } else if (!UseSoftFloat) {
316     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
317       // Expand FP_TO_UINT into a select.
318       // FIXME: We would like to use a Custom expander here eventually to do
319       // the optimal thing for SSE vs. the default expansion in the legalizer.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321     else
322       // With SSE3 we can use fisttpll to convert to a signed i64; without
323       // SSE, we're stuck with a fistpll.
324       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325   }
326
327   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
328   if (!X86ScalarSSEf64) {
329     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
330     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
331     if (Subtarget->is64Bit()) {
332       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
333       // Without SSE, i64->f64 goes through memory.
334       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
335     }
336   }
337
338   // Scalar integer divide and remainder are lowered to use operations that
339   // produce two results, to match the available instructions. This exposes
340   // the two-result form to trivial CSE, which is able to combine x/y and x%y
341   // into a single instruction.
342   //
343   // Scalar integer multiply-high is also lowered to use two-result
344   // operations, to match the available instructions. However, plain multiply
345   // (low) operations are left as Legal, as there are single-result
346   // instructions for this in x86. Using the two-result multiply instructions
347   // when both high and low results are needed must be arranged by dagcombine.
348   for (unsigned i = 0, e = 4; i != e; ++i) {
349     MVT VT = IntVTs[i];
350     setOperationAction(ISD::MULHS, VT, Expand);
351     setOperationAction(ISD::MULHU, VT, Expand);
352     setOperationAction(ISD::SDIV, VT, Expand);
353     setOperationAction(ISD::UDIV, VT, Expand);
354     setOperationAction(ISD::SREM, VT, Expand);
355     setOperationAction(ISD::UREM, VT, Expand);
356
357     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
358     setOperationAction(ISD::ADDC, VT, Custom);
359     setOperationAction(ISD::ADDE, VT, Custom);
360     setOperationAction(ISD::SUBC, VT, Custom);
361     setOperationAction(ISD::SUBE, VT, Custom);
362   }
363
364   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
365   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
366   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
367   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
368   if (Subtarget->is64Bit())
369     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
370   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
371   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
373   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
374   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
375   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
377   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
378
379   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
380   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
381   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
382   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
383   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
384   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
385   if (Subtarget->is64Bit()) {
386     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
387     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
388   }
389
390   if (Subtarget->hasPOPCNT()) {
391     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
392   } else {
393     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
395     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
396     if (Subtarget->is64Bit())
397       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
398   }
399
400   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
401   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
402
403   // These should be promoted to a larger select which is supported.
404   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
405   // X86 wants to expand cmov itself.
406   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
418   if (Subtarget->is64Bit()) {
419     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
420     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
421   }
422   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
423
424   // Darwin ABI issue.
425   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
426   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
427   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
428   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
429   if (Subtarget->is64Bit())
430     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
431   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
432   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
433   if (Subtarget->is64Bit()) {
434     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
435     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
436     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
437     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
438     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
439   }
440   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
441   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
442   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
443   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
444   if (Subtarget->is64Bit()) {
445     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
446     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
447     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
448   }
449
450   if (Subtarget->hasXMM())
451     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
452
453   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
454   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
455
456   // On X86 and X86-64, atomic operations are lowered to locked instructions.
457   // Locked instructions, in turn, have implicit fence semantics (all memory
458   // operations are flushed before issuing the locked instruction, and they
459   // are not buffered), so we can fold away the common pattern of
460   // fence-atomic-fence.
461   setShouldFoldAtomicFences(true);
462
463   // Expand certain atomics
464   for (unsigned i = 0, e = 4; i != e; ++i) {
465     MVT VT = IntVTs[i];
466     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
467     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
468     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
469   }
470
471   if (!Subtarget->is64Bit()) {
472     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
473     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
474     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
475     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
476     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
477     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
478     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
479     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
480   }
481
482   if (Subtarget->hasCmpxchg16b()) {
483     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
484   }
485
486   // FIXME - use subtarget debug flags
487   if (!Subtarget->isTargetDarwin() &&
488       !Subtarget->isTargetELF() &&
489       !Subtarget->isTargetCygMing()) {
490     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
491   }
492
493   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
494   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
495   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
496   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
497   if (Subtarget->is64Bit()) {
498     setExceptionPointerRegister(X86::RAX);
499     setExceptionSelectorRegister(X86::RDX);
500   } else {
501     setExceptionPointerRegister(X86::EAX);
502     setExceptionSelectorRegister(X86::EDX);
503   }
504   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
505   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
506
507   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
508
509   setOperationAction(ISD::TRAP, MVT::Other, Legal);
510
511   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
512   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
513   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
514   if (Subtarget->is64Bit()) {
515     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
516     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
517   } else {
518     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
519     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
523   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
524   setOperationAction(ISD::DYNAMIC_STACKALLOC,
525                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
526                      ((Subtarget->isTargetCOFF()
527                        && !Subtarget->isTargetEnvMacho()) ||
528                       EnableSegmentedStacks
529                       ? Custom : Expand));
530
531   if (!UseSoftFloat && X86ScalarSSEf64) {
532     // f32 and f64 use SSE.
533     // Set up the FP register classes.
534     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
535     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
536
537     // Use ANDPD to simulate FABS.
538     setOperationAction(ISD::FABS , MVT::f64, Custom);
539     setOperationAction(ISD::FABS , MVT::f32, Custom);
540
541     // Use XORP to simulate FNEG.
542     setOperationAction(ISD::FNEG , MVT::f64, Custom);
543     setOperationAction(ISD::FNEG , MVT::f32, Custom);
544
545     // Use ANDPD and ORPD to simulate FCOPYSIGN.
546     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
547     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
548
549     // Lower this to FGETSIGNx86 plus an AND.
550     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
551     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
552
553     // We don't support sin/cos/fmod
554     setOperationAction(ISD::FSIN , MVT::f64, Expand);
555     setOperationAction(ISD::FCOS , MVT::f64, Expand);
556     setOperationAction(ISD::FSIN , MVT::f32, Expand);
557     setOperationAction(ISD::FCOS , MVT::f32, Expand);
558
559     // Expand FP immediates into loads from the stack, except for the special
560     // cases we handle.
561     addLegalFPImmediate(APFloat(+0.0)); // xorpd
562     addLegalFPImmediate(APFloat(+0.0f)); // xorps
563   } else if (!UseSoftFloat && X86ScalarSSEf32) {
564     // Use SSE for f32, x87 for f64.
565     // Set up the FP register classes.
566     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
567     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
568
569     // Use ANDPS to simulate FABS.
570     setOperationAction(ISD::FABS , MVT::f32, Custom);
571
572     // Use XORP to simulate FNEG.
573     setOperationAction(ISD::FNEG , MVT::f32, Custom);
574
575     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
576
577     // Use ANDPS and ORPS to simulate FCOPYSIGN.
578     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
579     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
580
581     // We don't support sin/cos/fmod
582     setOperationAction(ISD::FSIN , MVT::f32, Expand);
583     setOperationAction(ISD::FCOS , MVT::f32, Expand);
584
585     // Special cases we handle for FP constants.
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587     addLegalFPImmediate(APFloat(+0.0)); // FLD0
588     addLegalFPImmediate(APFloat(+1.0)); // FLD1
589     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
590     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
591
592     if (!UnsafeFPMath) {
593       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
594       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
595     }
596   } else if (!UseSoftFloat) {
597     // f32 and f64 in x87.
598     // Set up the FP register classes.
599     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
600     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
601
602     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
603     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
604     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
605     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
606
607     if (!UnsafeFPMath) {
608       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
609       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
610     }
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
619   }
620
621   // We don't support FMA.
622   setOperationAction(ISD::FMA, MVT::f64, Expand);
623   setOperationAction(ISD::FMA, MVT::f32, Expand);
624
625   // Long double always uses X87.
626   if (!UseSoftFloat) {
627     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
628     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
630     {
631       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
632       addLegalFPImmediate(TmpFlt);  // FLD0
633       TmpFlt.changeSign();
634       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
635
636       bool ignored;
637       APFloat TmpFlt2(+1.0);
638       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
639                       &ignored);
640       addLegalFPImmediate(TmpFlt2);  // FLD1
641       TmpFlt2.changeSign();
642       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
643     }
644
645     if (!UnsafeFPMath) {
646       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
647       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
648     }
649
650     setOperationAction(ISD::FMA, MVT::f80, Expand);
651   }
652
653   // Always use a library call for pow.
654   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
656   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
657
658   setOperationAction(ISD::FLOG, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
660   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP, MVT::f80, Expand);
662   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
663
664   // First set operation action for all vector types to either promote
665   // (for widening) or expand (for scalarization). Then we will selectively
666   // turn on ones that can be effectively codegen'd.
667   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
668        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
669     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
670     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
671     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
672     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
673     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
674     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
675     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
676     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
677     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
678     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
679     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
680     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
681     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
687     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
719     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
723     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
724          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
725       setTruncStoreAction((MVT::SimpleValueType)VT,
726                           (MVT::SimpleValueType)InnerVT, Expand);
727     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
728     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
729     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
730   }
731
732   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
733   // with -msoft-float, disable use of MMX as well.
734   if (!UseSoftFloat && Subtarget->hasMMX()) {
735     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
736     // No operations on x86mmx supported, everything uses intrinsics.
737   }
738
739   // MMX-sized vectors (other than x86mmx) are expected to be expanded
740   // into smaller operations.
741   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
742   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
743   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
744   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
745   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
746   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
747   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
748   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
749   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
750   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
751   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
752   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
753   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
754   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
755   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
756   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
757   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
758   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
759   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
760   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
761   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
762   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
763   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
764   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
765   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
766   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
767   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
768   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
769   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
770
771   if (!UseSoftFloat && Subtarget->hasXMM()) {
772     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
781     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
782     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
783     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
784     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
785     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
786   }
787
788   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
789     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
790
791     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
792     // registers cannot be used even for integer operations.
793     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
794     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
795     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
796     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
797
798     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
799     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
800     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
801     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
802     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
803     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
804     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
805     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
806     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
807     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
808     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
809     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
810     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
811     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
812     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
813     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
814
815     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
816     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
817     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
818     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
819
820     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
821     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
822     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
823     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
824     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
825
826     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
827     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
828     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
829     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
830     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
831
832     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
833     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
834       EVT VT = (MVT::SimpleValueType)i;
835       // Do not attempt to custom lower non-power-of-2 vectors
836       if (!isPowerOf2_32(VT.getVectorNumElements()))
837         continue;
838       // Do not attempt to custom lower non-128-bit vectors
839       if (!VT.is128BitVector())
840         continue;
841       setOperationAction(ISD::BUILD_VECTOR,
842                          VT.getSimpleVT().SimpleTy, Custom);
843       setOperationAction(ISD::VECTOR_SHUFFLE,
844                          VT.getSimpleVT().SimpleTy, Custom);
845       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
846                          VT.getSimpleVT().SimpleTy, Custom);
847     }
848
849     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
850     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
851     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
852     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
853     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
854     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
855
856     if (Subtarget->is64Bit()) {
857       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
858       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
859     }
860
861     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
862     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
863       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
864       EVT VT = SVT;
865
866       // Do not attempt to promote non-128-bit vectors
867       if (!VT.is128BitVector())
868         continue;
869
870       setOperationAction(ISD::AND,    SVT, Promote);
871       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
872       setOperationAction(ISD::OR,     SVT, Promote);
873       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
874       setOperationAction(ISD::XOR,    SVT, Promote);
875       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
876       setOperationAction(ISD::LOAD,   SVT, Promote);
877       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
878       setOperationAction(ISD::SELECT, SVT, Promote);
879       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
880     }
881
882     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
883
884     // Custom lower v2i64 and v2f64 selects.
885     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
886     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
887     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
888     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
889
890     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
891     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
892   }
893
894   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
895     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
896     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
897     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
898     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
899     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
900     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
901     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
902     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
903     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
904     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
905
906     // FIXME: Do we need to handle scalar-to-vector here?
907     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
908
909     // Can turn SHL into an integer multiply.
910     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
911     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
912
913     // i8 and i16 vectors are custom , because the source register and source
914     // source memory operand types are not the same width.  f32 vectors are
915     // custom since the immediate controlling the insert encodes additional
916     // information.
917     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
918     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
919     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
920     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
921
922     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
924     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926
927     if (Subtarget->is64Bit()) {
928       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
929       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
930     }
931   }
932
933   if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
934     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
935     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
936     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
937     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
938
939     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
940     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
941     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
942
943     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
944     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
945   }
946
947   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
948     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
949
950   if (!UseSoftFloat && Subtarget->hasAVX()) {
951     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
952     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
953     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
954     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
955     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
956     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
957
958     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
959     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
960     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
961
962     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
963     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
964     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
965     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
966     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
967     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
968
969     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
970     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
971     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
972     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
973     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
974     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
975
976     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
977     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
978     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
979
980     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
981     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
982     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
983     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
984     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
985     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
986
987     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
988     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
989     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
990     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
991
992     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
993     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
994     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
995     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
996
997     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
998     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
999
1000     setOperationAction(ISD::VSETCC,            MVT::v32i8, Custom);
1001     setOperationAction(ISD::VSETCC,            MVT::v16i16, Custom);
1002     setOperationAction(ISD::VSETCC,            MVT::v8i32, Custom);
1003     setOperationAction(ISD::VSETCC,            MVT::v4i64, Custom);
1004
1005     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1006     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1007     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1008
1009     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1010     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1011     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1012     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1013
1014     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1015     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1016     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1017     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1018
1019     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1020     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1021     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1022     // Don't lower v32i8 because there is no 128-bit byte mul
1023
1024     // Custom lower several nodes for 256-bit types.
1025     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1026                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1027       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1028       EVT VT = SVT;
1029
1030       // Extract subvector is special because the value type
1031       // (result) is 128-bit but the source is 256-bit wide.
1032       if (VT.is128BitVector())
1033         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1034
1035       // Do not attempt to custom lower other non-256-bit vectors
1036       if (!VT.is256BitVector())
1037         continue;
1038
1039       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1040       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1041       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1042       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1043       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1044       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1045     }
1046
1047     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1048     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1049       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1050       EVT VT = SVT;
1051
1052       // Do not attempt to promote non-256-bit vectors
1053       if (!VT.is256BitVector())
1054         continue;
1055
1056       setOperationAction(ISD::AND,    SVT, Promote);
1057       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1058       setOperationAction(ISD::OR,     SVT, Promote);
1059       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1060       setOperationAction(ISD::XOR,    SVT, Promote);
1061       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1062       setOperationAction(ISD::LOAD,   SVT, Promote);
1063       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1064       setOperationAction(ISD::SELECT, SVT, Promote);
1065       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1066     }
1067   }
1068
1069   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1070   // of this type with custom code.
1071   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1072          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1073     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1074   }
1075
1076   // We want to custom lower some of our intrinsics.
1077   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1078
1079
1080   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1081   // handle type legalization for these operations here.
1082   //
1083   // FIXME: We really should do custom legalization for addition and
1084   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1085   // than generic legalization for 64-bit multiplication-with-overflow, though.
1086   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1087     // Add/Sub/Mul with overflow operations are custom lowered.
1088     MVT VT = IntVTs[i];
1089     setOperationAction(ISD::SADDO, VT, Custom);
1090     setOperationAction(ISD::UADDO, VT, Custom);
1091     setOperationAction(ISD::SSUBO, VT, Custom);
1092     setOperationAction(ISD::USUBO, VT, Custom);
1093     setOperationAction(ISD::SMULO, VT, Custom);
1094     setOperationAction(ISD::UMULO, VT, Custom);
1095   }
1096
1097   // There are no 8-bit 3-address imul/mul instructions
1098   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1099   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1100
1101   if (!Subtarget->is64Bit()) {
1102     // These libcalls are not available in 32-bit.
1103     setLibcallName(RTLIB::SHL_I128, 0);
1104     setLibcallName(RTLIB::SRL_I128, 0);
1105     setLibcallName(RTLIB::SRA_I128, 0);
1106   }
1107
1108   // We have target-specific dag combine patterns for the following nodes:
1109   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1110   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1111   setTargetDAGCombine(ISD::BUILD_VECTOR);
1112   setTargetDAGCombine(ISD::SELECT);
1113   setTargetDAGCombine(ISD::SHL);
1114   setTargetDAGCombine(ISD::SRA);
1115   setTargetDAGCombine(ISD::SRL);
1116   setTargetDAGCombine(ISD::OR);
1117   setTargetDAGCombine(ISD::AND);
1118   setTargetDAGCombine(ISD::ADD);
1119   setTargetDAGCombine(ISD::SUB);
1120   setTargetDAGCombine(ISD::STORE);
1121   setTargetDAGCombine(ISD::ZERO_EXTEND);
1122   setTargetDAGCombine(ISD::SINT_TO_FP);
1123   if (Subtarget->is64Bit())
1124     setTargetDAGCombine(ISD::MUL);
1125
1126   computeRegisterProperties();
1127
1128   // On Darwin, -Os means optimize for size without hurting performance,
1129   // do not reduce the limit.
1130   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1131   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1132   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1133   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1134   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1135   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1136   setPrefLoopAlignment(16);
1137   benefitFromCodePlacementOpt = true;
1138
1139   setPrefFunctionAlignment(4);
1140 }
1141
1142
1143 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1144   return MVT::i8;
1145 }
1146
1147
1148 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1149 /// the desired ByVal argument alignment.
1150 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1151   if (MaxAlign == 16)
1152     return;
1153   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1154     if (VTy->getBitWidth() == 128)
1155       MaxAlign = 16;
1156   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1157     unsigned EltAlign = 0;
1158     getMaxByValAlign(ATy->getElementType(), EltAlign);
1159     if (EltAlign > MaxAlign)
1160       MaxAlign = EltAlign;
1161   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1162     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1163       unsigned EltAlign = 0;
1164       getMaxByValAlign(STy->getElementType(i), EltAlign);
1165       if (EltAlign > MaxAlign)
1166         MaxAlign = EltAlign;
1167       if (MaxAlign == 16)
1168         break;
1169     }
1170   }
1171   return;
1172 }
1173
1174 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1175 /// function arguments in the caller parameter area. For X86, aggregates
1176 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1177 /// are at 4-byte boundaries.
1178 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1179   if (Subtarget->is64Bit()) {
1180     // Max of 8 and alignment of type.
1181     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1182     if (TyAlign > 8)
1183       return TyAlign;
1184     return 8;
1185   }
1186
1187   unsigned Align = 4;
1188   if (Subtarget->hasXMM())
1189     getMaxByValAlign(Ty, Align);
1190   return Align;
1191 }
1192
1193 /// getOptimalMemOpType - Returns the target specific optimal type for load
1194 /// and store operations as a result of memset, memcpy, and memmove
1195 /// lowering. If DstAlign is zero that means it's safe to destination
1196 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1197 /// means there isn't a need to check it against alignment requirement,
1198 /// probably because the source does not need to be loaded. If
1199 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1200 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1201 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1202 /// constant so it does not need to be loaded.
1203 /// It returns EVT::Other if the type should be determined using generic
1204 /// target-independent logic.
1205 EVT
1206 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1207                                        unsigned DstAlign, unsigned SrcAlign,
1208                                        bool NonScalarIntSafe,
1209                                        bool MemcpyStrSrc,
1210                                        MachineFunction &MF) const {
1211   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1212   // linux.  This is because the stack realignment code can't handle certain
1213   // cases like PR2962.  This should be removed when PR2962 is fixed.
1214   const Function *F = MF.getFunction();
1215   if (NonScalarIntSafe &&
1216       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1217     if (Size >= 16 &&
1218         (Subtarget->isUnalignedMemAccessFast() ||
1219          ((DstAlign == 0 || DstAlign >= 16) &&
1220           (SrcAlign == 0 || SrcAlign >= 16))) &&
1221         Subtarget->getStackAlignment() >= 16) {
1222       if (Subtarget->hasSSE2())
1223         return MVT::v4i32;
1224       if (Subtarget->hasSSE1())
1225         return MVT::v4f32;
1226     } else if (!MemcpyStrSrc && Size >= 8 &&
1227                !Subtarget->is64Bit() &&
1228                Subtarget->getStackAlignment() >= 8 &&
1229                Subtarget->hasXMMInt()) {
1230       // Do not use f64 to lower memcpy if source is string constant. It's
1231       // better to use i32 to avoid the loads.
1232       return MVT::f64;
1233     }
1234   }
1235   if (Subtarget->is64Bit() && Size >= 8)
1236     return MVT::i64;
1237   return MVT::i32;
1238 }
1239
1240 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1241 /// current function.  The returned value is a member of the
1242 /// MachineJumpTableInfo::JTEntryKind enum.
1243 unsigned X86TargetLowering::getJumpTableEncoding() const {
1244   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1245   // symbol.
1246   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1247       Subtarget->isPICStyleGOT())
1248     return MachineJumpTableInfo::EK_Custom32;
1249
1250   // Otherwise, use the normal jump table encoding heuristics.
1251   return TargetLowering::getJumpTableEncoding();
1252 }
1253
1254 const MCExpr *
1255 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1256                                              const MachineBasicBlock *MBB,
1257                                              unsigned uid,MCContext &Ctx) const{
1258   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1259          Subtarget->isPICStyleGOT());
1260   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1261   // entries.
1262   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1263                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1264 }
1265
1266 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1267 /// jumptable.
1268 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1269                                                     SelectionDAG &DAG) const {
1270   if (!Subtarget->is64Bit())
1271     // This doesn't have DebugLoc associated with it, but is not really the
1272     // same as a Register.
1273     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1274   return Table;
1275 }
1276
1277 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1278 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1279 /// MCExpr.
1280 const MCExpr *X86TargetLowering::
1281 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1282                              MCContext &Ctx) const {
1283   // X86-64 uses RIP relative addressing based on the jump table label.
1284   if (Subtarget->isPICStyleRIPRel())
1285     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1286
1287   // Otherwise, the reference is relative to the PIC base.
1288   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1289 }
1290
1291 // FIXME: Why this routine is here? Move to RegInfo!
1292 std::pair<const TargetRegisterClass*, uint8_t>
1293 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1294   const TargetRegisterClass *RRC = 0;
1295   uint8_t Cost = 1;
1296   switch (VT.getSimpleVT().SimpleTy) {
1297   default:
1298     return TargetLowering::findRepresentativeClass(VT);
1299   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1300     RRC = (Subtarget->is64Bit()
1301            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1302     break;
1303   case MVT::x86mmx:
1304     RRC = X86::VR64RegisterClass;
1305     break;
1306   case MVT::f32: case MVT::f64:
1307   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1308   case MVT::v4f32: case MVT::v2f64:
1309   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1310   case MVT::v4f64:
1311     RRC = X86::VR128RegisterClass;
1312     break;
1313   }
1314   return std::make_pair(RRC, Cost);
1315 }
1316
1317 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1318                                                unsigned &Offset) const {
1319   if (!Subtarget->isTargetLinux())
1320     return false;
1321
1322   if (Subtarget->is64Bit()) {
1323     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1324     Offset = 0x28;
1325     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1326       AddressSpace = 256;
1327     else
1328       AddressSpace = 257;
1329   } else {
1330     // %gs:0x14 on i386
1331     Offset = 0x14;
1332     AddressSpace = 256;
1333   }
1334   return true;
1335 }
1336
1337
1338 //===----------------------------------------------------------------------===//
1339 //               Return Value Calling Convention Implementation
1340 //===----------------------------------------------------------------------===//
1341
1342 #include "X86GenCallingConv.inc"
1343
1344 bool
1345 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1346                                   MachineFunction &MF, bool isVarArg,
1347                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1348                         LLVMContext &Context) const {
1349   SmallVector<CCValAssign, 16> RVLocs;
1350   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1351                  RVLocs, Context);
1352   return CCInfo.CheckReturn(Outs, RetCC_X86);
1353 }
1354
1355 SDValue
1356 X86TargetLowering::LowerReturn(SDValue Chain,
1357                                CallingConv::ID CallConv, bool isVarArg,
1358                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1359                                const SmallVectorImpl<SDValue> &OutVals,
1360                                DebugLoc dl, SelectionDAG &DAG) const {
1361   MachineFunction &MF = DAG.getMachineFunction();
1362   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1363
1364   SmallVector<CCValAssign, 16> RVLocs;
1365   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1366                  RVLocs, *DAG.getContext());
1367   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1368
1369   // Add the regs to the liveout set for the function.
1370   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1371   for (unsigned i = 0; i != RVLocs.size(); ++i)
1372     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1373       MRI.addLiveOut(RVLocs[i].getLocReg());
1374
1375   SDValue Flag;
1376
1377   SmallVector<SDValue, 6> RetOps;
1378   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1379   // Operand #1 = Bytes To Pop
1380   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1381                    MVT::i16));
1382
1383   // Copy the result values into the output registers.
1384   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1385     CCValAssign &VA = RVLocs[i];
1386     assert(VA.isRegLoc() && "Can only return in registers!");
1387     SDValue ValToCopy = OutVals[i];
1388     EVT ValVT = ValToCopy.getValueType();
1389
1390     // If this is x86-64, and we disabled SSE, we can't return FP values,
1391     // or SSE or MMX vectors.
1392     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1393          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1394           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1395       report_fatal_error("SSE register return with SSE disabled");
1396     }
1397     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1398     // llvm-gcc has never done it right and no one has noticed, so this
1399     // should be OK for now.
1400     if (ValVT == MVT::f64 &&
1401         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1402       report_fatal_error("SSE2 register return with SSE2 disabled");
1403
1404     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1405     // the RET instruction and handled by the FP Stackifier.
1406     if (VA.getLocReg() == X86::ST0 ||
1407         VA.getLocReg() == X86::ST1) {
1408       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1409       // change the value to the FP stack register class.
1410       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1411         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1412       RetOps.push_back(ValToCopy);
1413       // Don't emit a copytoreg.
1414       continue;
1415     }
1416
1417     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1418     // which is returned in RAX / RDX.
1419     if (Subtarget->is64Bit()) {
1420       if (ValVT == MVT::x86mmx) {
1421         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1422           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1423           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1424                                   ValToCopy);
1425           // If we don't have SSE2 available, convert to v4f32 so the generated
1426           // register is legal.
1427           if (!Subtarget->hasSSE2())
1428             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1429         }
1430       }
1431     }
1432
1433     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1434     Flag = Chain.getValue(1);
1435   }
1436
1437   // The x86-64 ABI for returning structs by value requires that we copy
1438   // the sret argument into %rax for the return. We saved the argument into
1439   // a virtual register in the entry block, so now we copy the value out
1440   // and into %rax.
1441   if (Subtarget->is64Bit() &&
1442       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1443     MachineFunction &MF = DAG.getMachineFunction();
1444     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1445     unsigned Reg = FuncInfo->getSRetReturnReg();
1446     assert(Reg &&
1447            "SRetReturnReg should have been set in LowerFormalArguments().");
1448     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1449
1450     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1451     Flag = Chain.getValue(1);
1452
1453     // RAX now acts like a return value.
1454     MRI.addLiveOut(X86::RAX);
1455   }
1456
1457   RetOps[0] = Chain;  // Update chain.
1458
1459   // Add the flag if we have it.
1460   if (Flag.getNode())
1461     RetOps.push_back(Flag);
1462
1463   return DAG.getNode(X86ISD::RET_FLAG, dl,
1464                      MVT::Other, &RetOps[0], RetOps.size());
1465 }
1466
1467 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1468   if (N->getNumValues() != 1)
1469     return false;
1470   if (!N->hasNUsesOfValue(1, 0))
1471     return false;
1472
1473   SDNode *Copy = *N->use_begin();
1474   if (Copy->getOpcode() != ISD::CopyToReg &&
1475       Copy->getOpcode() != ISD::FP_EXTEND)
1476     return false;
1477
1478   bool HasRet = false;
1479   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1480        UI != UE; ++UI) {
1481     if (UI->getOpcode() != X86ISD::RET_FLAG)
1482       return false;
1483     HasRet = true;
1484   }
1485
1486   return HasRet;
1487 }
1488
1489 EVT
1490 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1491                                             ISD::NodeType ExtendKind) const {
1492   MVT ReturnMVT;
1493   // TODO: Is this also valid on 32-bit?
1494   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1495     ReturnMVT = MVT::i8;
1496   else
1497     ReturnMVT = MVT::i32;
1498
1499   EVT MinVT = getRegisterType(Context, ReturnMVT);
1500   return VT.bitsLT(MinVT) ? MinVT : VT;
1501 }
1502
1503 /// LowerCallResult - Lower the result values of a call into the
1504 /// appropriate copies out of appropriate physical registers.
1505 ///
1506 SDValue
1507 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1508                                    CallingConv::ID CallConv, bool isVarArg,
1509                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1510                                    DebugLoc dl, SelectionDAG &DAG,
1511                                    SmallVectorImpl<SDValue> &InVals) const {
1512
1513   // Assign locations to each value returned by this call.
1514   SmallVector<CCValAssign, 16> RVLocs;
1515   bool Is64Bit = Subtarget->is64Bit();
1516   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1517                  getTargetMachine(), RVLocs, *DAG.getContext());
1518   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1519
1520   // Copy all of the result registers out of their specified physreg.
1521   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1522     CCValAssign &VA = RVLocs[i];
1523     EVT CopyVT = VA.getValVT();
1524
1525     // If this is x86-64, and we disabled SSE, we can't return FP values
1526     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1527         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1528       report_fatal_error("SSE register return with SSE disabled");
1529     }
1530
1531     SDValue Val;
1532
1533     // If this is a call to a function that returns an fp value on the floating
1534     // point stack, we must guarantee the the value is popped from the stack, so
1535     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1536     // if the return value is not used. We use the FpPOP_RETVAL instruction
1537     // instead.
1538     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1539       // If we prefer to use the value in xmm registers, copy it out as f80 and
1540       // use a truncate to move it from fp stack reg to xmm reg.
1541       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1542       SDValue Ops[] = { Chain, InFlag };
1543       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1544                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1545       Val = Chain.getValue(0);
1546
1547       // Round the f80 to the right size, which also moves it to the appropriate
1548       // xmm register.
1549       if (CopyVT != VA.getValVT())
1550         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1551                           // This truncation won't change the value.
1552                           DAG.getIntPtrConstant(1));
1553     } else {
1554       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1555                                  CopyVT, InFlag).getValue(1);
1556       Val = Chain.getValue(0);
1557     }
1558     InFlag = Chain.getValue(2);
1559     InVals.push_back(Val);
1560   }
1561
1562   return Chain;
1563 }
1564
1565
1566 //===----------------------------------------------------------------------===//
1567 //                C & StdCall & Fast Calling Convention implementation
1568 //===----------------------------------------------------------------------===//
1569 //  StdCall calling convention seems to be standard for many Windows' API
1570 //  routines and around. It differs from C calling convention just a little:
1571 //  callee should clean up the stack, not caller. Symbols should be also
1572 //  decorated in some fancy way :) It doesn't support any vector arguments.
1573 //  For info on fast calling convention see Fast Calling Convention (tail call)
1574 //  implementation LowerX86_32FastCCCallTo.
1575
1576 /// CallIsStructReturn - Determines whether a call uses struct return
1577 /// semantics.
1578 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1579   if (Outs.empty())
1580     return false;
1581
1582   return Outs[0].Flags.isSRet();
1583 }
1584
1585 /// ArgsAreStructReturn - Determines whether a function uses struct
1586 /// return semantics.
1587 static bool
1588 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1589   if (Ins.empty())
1590     return false;
1591
1592   return Ins[0].Flags.isSRet();
1593 }
1594
1595 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1596 /// by "Src" to address "Dst" with size and alignment information specified by
1597 /// the specific parameter attribute. The copy will be passed as a byval
1598 /// function parameter.
1599 static SDValue
1600 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1601                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1602                           DebugLoc dl) {
1603   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1604
1605   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1606                        /*isVolatile*/false, /*AlwaysInline=*/true,
1607                        MachinePointerInfo(), MachinePointerInfo());
1608 }
1609
1610 /// IsTailCallConvention - Return true if the calling convention is one that
1611 /// supports tail call optimization.
1612 static bool IsTailCallConvention(CallingConv::ID CC) {
1613   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1614 }
1615
1616 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1617   if (!CI->isTailCall())
1618     return false;
1619
1620   CallSite CS(CI);
1621   CallingConv::ID CalleeCC = CS.getCallingConv();
1622   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1623     return false;
1624
1625   return true;
1626 }
1627
1628 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1629 /// a tailcall target by changing its ABI.
1630 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1631   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1632 }
1633
1634 SDValue
1635 X86TargetLowering::LowerMemArgument(SDValue Chain,
1636                                     CallingConv::ID CallConv,
1637                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1638                                     DebugLoc dl, SelectionDAG &DAG,
1639                                     const CCValAssign &VA,
1640                                     MachineFrameInfo *MFI,
1641                                     unsigned i) const {
1642   // Create the nodes corresponding to a load from this parameter slot.
1643   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1644   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1645   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1646   EVT ValVT;
1647
1648   // If value is passed by pointer we have address passed instead of the value
1649   // itself.
1650   if (VA.getLocInfo() == CCValAssign::Indirect)
1651     ValVT = VA.getLocVT();
1652   else
1653     ValVT = VA.getValVT();
1654
1655   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1656   // changed with more analysis.
1657   // In case of tail call optimization mark all arguments mutable. Since they
1658   // could be overwritten by lowering of arguments in case of a tail call.
1659   if (Flags.isByVal()) {
1660     unsigned Bytes = Flags.getByValSize();
1661     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1662     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1663     return DAG.getFrameIndex(FI, getPointerTy());
1664   } else {
1665     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1666                                     VA.getLocMemOffset(), isImmutable);
1667     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1668     return DAG.getLoad(ValVT, dl, Chain, FIN,
1669                        MachinePointerInfo::getFixedStack(FI),
1670                        false, false, 0);
1671   }
1672 }
1673
1674 SDValue
1675 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1676                                         CallingConv::ID CallConv,
1677                                         bool isVarArg,
1678                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1679                                         DebugLoc dl,
1680                                         SelectionDAG &DAG,
1681                                         SmallVectorImpl<SDValue> &InVals)
1682                                           const {
1683   MachineFunction &MF = DAG.getMachineFunction();
1684   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1685
1686   const Function* Fn = MF.getFunction();
1687   if (Fn->hasExternalLinkage() &&
1688       Subtarget->isTargetCygMing() &&
1689       Fn->getName() == "main")
1690     FuncInfo->setForceFramePointer(true);
1691
1692   MachineFrameInfo *MFI = MF.getFrameInfo();
1693   bool Is64Bit = Subtarget->is64Bit();
1694   bool IsWin64 = Subtarget->isTargetWin64();
1695
1696   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1697          "Var args not supported with calling convention fastcc or ghc");
1698
1699   // Assign locations to all of the incoming arguments.
1700   SmallVector<CCValAssign, 16> ArgLocs;
1701   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1702                  ArgLocs, *DAG.getContext());
1703
1704   // Allocate shadow area for Win64
1705   if (IsWin64) {
1706     CCInfo.AllocateStack(32, 8);
1707   }
1708
1709   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1710
1711   unsigned LastVal = ~0U;
1712   SDValue ArgValue;
1713   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1714     CCValAssign &VA = ArgLocs[i];
1715     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1716     // places.
1717     assert(VA.getValNo() != LastVal &&
1718            "Don't support value assigned to multiple locs yet");
1719     LastVal = VA.getValNo();
1720
1721     if (VA.isRegLoc()) {
1722       EVT RegVT = VA.getLocVT();
1723       TargetRegisterClass *RC = NULL;
1724       if (RegVT == MVT::i32)
1725         RC = X86::GR32RegisterClass;
1726       else if (Is64Bit && RegVT == MVT::i64)
1727         RC = X86::GR64RegisterClass;
1728       else if (RegVT == MVT::f32)
1729         RC = X86::FR32RegisterClass;
1730       else if (RegVT == MVT::f64)
1731         RC = X86::FR64RegisterClass;
1732       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1733         RC = X86::VR256RegisterClass;
1734       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1735         RC = X86::VR128RegisterClass;
1736       else if (RegVT == MVT::x86mmx)
1737         RC = X86::VR64RegisterClass;
1738       else
1739         llvm_unreachable("Unknown argument type!");
1740
1741       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1742       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1743
1744       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1745       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1746       // right size.
1747       if (VA.getLocInfo() == CCValAssign::SExt)
1748         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1749                                DAG.getValueType(VA.getValVT()));
1750       else if (VA.getLocInfo() == CCValAssign::ZExt)
1751         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1752                                DAG.getValueType(VA.getValVT()));
1753       else if (VA.getLocInfo() == CCValAssign::BCvt)
1754         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1755
1756       if (VA.isExtInLoc()) {
1757         // Handle MMX values passed in XMM regs.
1758         if (RegVT.isVector()) {
1759           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1760                                  ArgValue);
1761         } else
1762           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1763       }
1764     } else {
1765       assert(VA.isMemLoc());
1766       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1767     }
1768
1769     // If value is passed via pointer - do a load.
1770     if (VA.getLocInfo() == CCValAssign::Indirect)
1771       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1772                              MachinePointerInfo(), false, false, 0);
1773
1774     InVals.push_back(ArgValue);
1775   }
1776
1777   // The x86-64 ABI for returning structs by value requires that we copy
1778   // the sret argument into %rax for the return. Save the argument into
1779   // a virtual register so that we can access it from the return points.
1780   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1781     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1782     unsigned Reg = FuncInfo->getSRetReturnReg();
1783     if (!Reg) {
1784       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1785       FuncInfo->setSRetReturnReg(Reg);
1786     }
1787     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1788     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1789   }
1790
1791   unsigned StackSize = CCInfo.getNextStackOffset();
1792   // Align stack specially for tail calls.
1793   if (FuncIsMadeTailCallSafe(CallConv))
1794     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1795
1796   // If the function takes variable number of arguments, make a frame index for
1797   // the start of the first vararg value... for expansion of llvm.va_start.
1798   if (isVarArg) {
1799     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1800                     CallConv != CallingConv::X86_ThisCall)) {
1801       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1802     }
1803     if (Is64Bit) {
1804       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1805
1806       // FIXME: We should really autogenerate these arrays
1807       static const unsigned GPR64ArgRegsWin64[] = {
1808         X86::RCX, X86::RDX, X86::R8,  X86::R9
1809       };
1810       static const unsigned GPR64ArgRegs64Bit[] = {
1811         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1812       };
1813       static const unsigned XMMArgRegs64Bit[] = {
1814         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1815         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1816       };
1817       const unsigned *GPR64ArgRegs;
1818       unsigned NumXMMRegs = 0;
1819
1820       if (IsWin64) {
1821         // The XMM registers which might contain var arg parameters are shadowed
1822         // in their paired GPR.  So we only need to save the GPR to their home
1823         // slots.
1824         TotalNumIntRegs = 4;
1825         GPR64ArgRegs = GPR64ArgRegsWin64;
1826       } else {
1827         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1828         GPR64ArgRegs = GPR64ArgRegs64Bit;
1829
1830         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1831       }
1832       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1833                                                        TotalNumIntRegs);
1834
1835       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1836       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1837              "SSE register cannot be used when SSE is disabled!");
1838       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1839              "SSE register cannot be used when SSE is disabled!");
1840       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1841         // Kernel mode asks for SSE to be disabled, so don't push them
1842         // on the stack.
1843         TotalNumXMMRegs = 0;
1844
1845       if (IsWin64) {
1846         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1847         // Get to the caller-allocated home save location.  Add 8 to account
1848         // for the return address.
1849         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1850         FuncInfo->setRegSaveFrameIndex(
1851           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1852         // Fixup to set vararg frame on shadow area (4 x i64).
1853         if (NumIntRegs < 4)
1854           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1855       } else {
1856         // For X86-64, if there are vararg parameters that are passed via
1857         // registers, then we must store them to their spots on the stack so they
1858         // may be loaded by deferencing the result of va_next.
1859         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1860         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1861         FuncInfo->setRegSaveFrameIndex(
1862           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1863                                false));
1864       }
1865
1866       // Store the integer parameter registers.
1867       SmallVector<SDValue, 8> MemOps;
1868       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1869                                         getPointerTy());
1870       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1871       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1872         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1873                                   DAG.getIntPtrConstant(Offset));
1874         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1875                                      X86::GR64RegisterClass);
1876         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1877         SDValue Store =
1878           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1879                        MachinePointerInfo::getFixedStack(
1880                          FuncInfo->getRegSaveFrameIndex(), Offset),
1881                        false, false, 0);
1882         MemOps.push_back(Store);
1883         Offset += 8;
1884       }
1885
1886       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1887         // Now store the XMM (fp + vector) parameter registers.
1888         SmallVector<SDValue, 11> SaveXMMOps;
1889         SaveXMMOps.push_back(Chain);
1890
1891         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1892         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1893         SaveXMMOps.push_back(ALVal);
1894
1895         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1896                                FuncInfo->getRegSaveFrameIndex()));
1897         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1898                                FuncInfo->getVarArgsFPOffset()));
1899
1900         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1901           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1902                                        X86::VR128RegisterClass);
1903           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1904           SaveXMMOps.push_back(Val);
1905         }
1906         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1907                                      MVT::Other,
1908                                      &SaveXMMOps[0], SaveXMMOps.size()));
1909       }
1910
1911       if (!MemOps.empty())
1912         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1913                             &MemOps[0], MemOps.size());
1914     }
1915   }
1916
1917   // Some CCs need callee pop.
1918   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1919     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1920   } else {
1921     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1922     // If this is an sret function, the return should pop the hidden pointer.
1923     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1924       FuncInfo->setBytesToPopOnReturn(4);
1925   }
1926
1927   if (!Is64Bit) {
1928     // RegSaveFrameIndex is X86-64 only.
1929     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1930     if (CallConv == CallingConv::X86_FastCall ||
1931         CallConv == CallingConv::X86_ThisCall)
1932       // fastcc functions can't have varargs.
1933       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1934   }
1935
1936   FuncInfo->setArgumentStackSize(StackSize);
1937
1938   return Chain;
1939 }
1940
1941 SDValue
1942 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1943                                     SDValue StackPtr, SDValue Arg,
1944                                     DebugLoc dl, SelectionDAG &DAG,
1945                                     const CCValAssign &VA,
1946                                     ISD::ArgFlagsTy Flags) const {
1947   unsigned LocMemOffset = VA.getLocMemOffset();
1948   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1949   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1950   if (Flags.isByVal())
1951     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1952
1953   return DAG.getStore(Chain, dl, Arg, PtrOff,
1954                       MachinePointerInfo::getStack(LocMemOffset),
1955                       false, false, 0);
1956 }
1957
1958 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1959 /// optimization is performed and it is required.
1960 SDValue
1961 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1962                                            SDValue &OutRetAddr, SDValue Chain,
1963                                            bool IsTailCall, bool Is64Bit,
1964                                            int FPDiff, DebugLoc dl) const {
1965   // Adjust the Return address stack slot.
1966   EVT VT = getPointerTy();
1967   OutRetAddr = getReturnAddressFrameIndex(DAG);
1968
1969   // Load the "old" Return address.
1970   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1971                            false, false, 0);
1972   return SDValue(OutRetAddr.getNode(), 1);
1973 }
1974
1975 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1976 /// optimization is performed and it is required (FPDiff!=0).
1977 static SDValue
1978 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1979                          SDValue Chain, SDValue RetAddrFrIdx,
1980                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1981   // Store the return address to the appropriate stack slot.
1982   if (!FPDiff) return Chain;
1983   // Calculate the new stack slot for the return address.
1984   int SlotSize = Is64Bit ? 8 : 4;
1985   int NewReturnAddrFI =
1986     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1987   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1988   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1989   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1990                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1991                        false, false, 0);
1992   return Chain;
1993 }
1994
1995 SDValue
1996 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1997                              CallingConv::ID CallConv, bool isVarArg,
1998                              bool &isTailCall,
1999                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2000                              const SmallVectorImpl<SDValue> &OutVals,
2001                              const SmallVectorImpl<ISD::InputArg> &Ins,
2002                              DebugLoc dl, SelectionDAG &DAG,
2003                              SmallVectorImpl<SDValue> &InVals) const {
2004   MachineFunction &MF = DAG.getMachineFunction();
2005   bool Is64Bit        = Subtarget->is64Bit();
2006   bool IsWin64        = Subtarget->isTargetWin64();
2007   bool IsStructRet    = CallIsStructReturn(Outs);
2008   bool IsSibcall      = false;
2009
2010   if (isTailCall) {
2011     // Check if it's really possible to do a tail call.
2012     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2013                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2014                                                    Outs, OutVals, Ins, DAG);
2015
2016     // Sibcalls are automatically detected tailcalls which do not require
2017     // ABI changes.
2018     if (!GuaranteedTailCallOpt && isTailCall)
2019       IsSibcall = true;
2020
2021     if (isTailCall)
2022       ++NumTailCalls;
2023   }
2024
2025   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2026          "Var args not supported with calling convention fastcc or ghc");
2027
2028   // Analyze operands of the call, assigning locations to each operand.
2029   SmallVector<CCValAssign, 16> ArgLocs;
2030   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2031                  ArgLocs, *DAG.getContext());
2032
2033   // Allocate shadow area for Win64
2034   if (IsWin64) {
2035     CCInfo.AllocateStack(32, 8);
2036   }
2037
2038   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2039
2040   // Get a count of how many bytes are to be pushed on the stack.
2041   unsigned NumBytes = CCInfo.getNextStackOffset();
2042   if (IsSibcall)
2043     // This is a sibcall. The memory operands are available in caller's
2044     // own caller's stack.
2045     NumBytes = 0;
2046   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2047     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2048
2049   int FPDiff = 0;
2050   if (isTailCall && !IsSibcall) {
2051     // Lower arguments at fp - stackoffset + fpdiff.
2052     unsigned NumBytesCallerPushed =
2053       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2054     FPDiff = NumBytesCallerPushed - NumBytes;
2055
2056     // Set the delta of movement of the returnaddr stackslot.
2057     // But only set if delta is greater than previous delta.
2058     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2059       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2060   }
2061
2062   if (!IsSibcall)
2063     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2064
2065   SDValue RetAddrFrIdx;
2066   // Load return address for tail calls.
2067   if (isTailCall && FPDiff)
2068     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2069                                     Is64Bit, FPDiff, dl);
2070
2071   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2072   SmallVector<SDValue, 8> MemOpChains;
2073   SDValue StackPtr;
2074
2075   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2076   // of tail call optimization arguments are handle later.
2077   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2078     CCValAssign &VA = ArgLocs[i];
2079     EVT RegVT = VA.getLocVT();
2080     SDValue Arg = OutVals[i];
2081     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2082     bool isByVal = Flags.isByVal();
2083
2084     // Promote the value if needed.
2085     switch (VA.getLocInfo()) {
2086     default: llvm_unreachable("Unknown loc info!");
2087     case CCValAssign::Full: break;
2088     case CCValAssign::SExt:
2089       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2090       break;
2091     case CCValAssign::ZExt:
2092       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2093       break;
2094     case CCValAssign::AExt:
2095       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2096         // Special case: passing MMX values in XMM registers.
2097         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2098         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2099         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2100       } else
2101         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2102       break;
2103     case CCValAssign::BCvt:
2104       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2105       break;
2106     case CCValAssign::Indirect: {
2107       // Store the argument.
2108       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2109       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2110       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2111                            MachinePointerInfo::getFixedStack(FI),
2112                            false, false, 0);
2113       Arg = SpillSlot;
2114       break;
2115     }
2116     }
2117
2118     if (VA.isRegLoc()) {
2119       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2120       if (isVarArg && IsWin64) {
2121         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2122         // shadow reg if callee is a varargs function.
2123         unsigned ShadowReg = 0;
2124         switch (VA.getLocReg()) {
2125         case X86::XMM0: ShadowReg = X86::RCX; break;
2126         case X86::XMM1: ShadowReg = X86::RDX; break;
2127         case X86::XMM2: ShadowReg = X86::R8; break;
2128         case X86::XMM3: ShadowReg = X86::R9; break;
2129         }
2130         if (ShadowReg)
2131           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2132       }
2133     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2134       assert(VA.isMemLoc());
2135       if (StackPtr.getNode() == 0)
2136         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2137       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2138                                              dl, DAG, VA, Flags));
2139     }
2140   }
2141
2142   if (!MemOpChains.empty())
2143     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2144                         &MemOpChains[0], MemOpChains.size());
2145
2146   // Build a sequence of copy-to-reg nodes chained together with token chain
2147   // and flag operands which copy the outgoing args into registers.
2148   SDValue InFlag;
2149   // Tail call byval lowering might overwrite argument registers so in case of
2150   // tail call optimization the copies to registers are lowered later.
2151   if (!isTailCall)
2152     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2153       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2154                                RegsToPass[i].second, InFlag);
2155       InFlag = Chain.getValue(1);
2156     }
2157
2158   if (Subtarget->isPICStyleGOT()) {
2159     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2160     // GOT pointer.
2161     if (!isTailCall) {
2162       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2163                                DAG.getNode(X86ISD::GlobalBaseReg,
2164                                            DebugLoc(), getPointerTy()),
2165                                InFlag);
2166       InFlag = Chain.getValue(1);
2167     } else {
2168       // If we are tail calling and generating PIC/GOT style code load the
2169       // address of the callee into ECX. The value in ecx is used as target of
2170       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2171       // for tail calls on PIC/GOT architectures. Normally we would just put the
2172       // address of GOT into ebx and then call target@PLT. But for tail calls
2173       // ebx would be restored (since ebx is callee saved) before jumping to the
2174       // target@PLT.
2175
2176       // Note: The actual moving to ECX is done further down.
2177       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2178       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2179           !G->getGlobal()->hasProtectedVisibility())
2180         Callee = LowerGlobalAddress(Callee, DAG);
2181       else if (isa<ExternalSymbolSDNode>(Callee))
2182         Callee = LowerExternalSymbol(Callee, DAG);
2183     }
2184   }
2185
2186   if (Is64Bit && isVarArg && !IsWin64) {
2187     // From AMD64 ABI document:
2188     // For calls that may call functions that use varargs or stdargs
2189     // (prototype-less calls or calls to functions containing ellipsis (...) in
2190     // the declaration) %al is used as hidden argument to specify the number
2191     // of SSE registers used. The contents of %al do not need to match exactly
2192     // the number of registers, but must be an ubound on the number of SSE
2193     // registers used and is in the range 0 - 8 inclusive.
2194
2195     // Count the number of XMM registers allocated.
2196     static const unsigned XMMArgRegs[] = {
2197       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2198       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2199     };
2200     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2201     assert((Subtarget->hasXMM() || !NumXMMRegs)
2202            && "SSE registers cannot be used when SSE is disabled");
2203
2204     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2205                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2206     InFlag = Chain.getValue(1);
2207   }
2208
2209
2210   // For tail calls lower the arguments to the 'real' stack slot.
2211   if (isTailCall) {
2212     // Force all the incoming stack arguments to be loaded from the stack
2213     // before any new outgoing arguments are stored to the stack, because the
2214     // outgoing stack slots may alias the incoming argument stack slots, and
2215     // the alias isn't otherwise explicit. This is slightly more conservative
2216     // than necessary, because it means that each store effectively depends
2217     // on every argument instead of just those arguments it would clobber.
2218     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2219
2220     SmallVector<SDValue, 8> MemOpChains2;
2221     SDValue FIN;
2222     int FI = 0;
2223     // Do not flag preceding copytoreg stuff together with the following stuff.
2224     InFlag = SDValue();
2225     if (GuaranteedTailCallOpt) {
2226       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2227         CCValAssign &VA = ArgLocs[i];
2228         if (VA.isRegLoc())
2229           continue;
2230         assert(VA.isMemLoc());
2231         SDValue Arg = OutVals[i];
2232         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2233         // Create frame index.
2234         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2235         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2236         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2237         FIN = DAG.getFrameIndex(FI, getPointerTy());
2238
2239         if (Flags.isByVal()) {
2240           // Copy relative to framepointer.
2241           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2242           if (StackPtr.getNode() == 0)
2243             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2244                                           getPointerTy());
2245           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2246
2247           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2248                                                            ArgChain,
2249                                                            Flags, DAG, dl));
2250         } else {
2251           // Store relative to framepointer.
2252           MemOpChains2.push_back(
2253             DAG.getStore(ArgChain, dl, Arg, FIN,
2254                          MachinePointerInfo::getFixedStack(FI),
2255                          false, false, 0));
2256         }
2257       }
2258     }
2259
2260     if (!MemOpChains2.empty())
2261       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2262                           &MemOpChains2[0], MemOpChains2.size());
2263
2264     // Copy arguments to their registers.
2265     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2266       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2267                                RegsToPass[i].second, InFlag);
2268       InFlag = Chain.getValue(1);
2269     }
2270     InFlag =SDValue();
2271
2272     // Store the return address to the appropriate stack slot.
2273     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2274                                      FPDiff, dl);
2275   }
2276
2277   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2278     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2279     // In the 64-bit large code model, we have to make all calls
2280     // through a register, since the call instruction's 32-bit
2281     // pc-relative offset may not be large enough to hold the whole
2282     // address.
2283   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2284     // If the callee is a GlobalAddress node (quite common, every direct call
2285     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2286     // it.
2287
2288     // We should use extra load for direct calls to dllimported functions in
2289     // non-JIT mode.
2290     const GlobalValue *GV = G->getGlobal();
2291     if (!GV->hasDLLImportLinkage()) {
2292       unsigned char OpFlags = 0;
2293       bool ExtraLoad = false;
2294       unsigned WrapperKind = ISD::DELETED_NODE;
2295
2296       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2297       // external symbols most go through the PLT in PIC mode.  If the symbol
2298       // has hidden or protected visibility, or if it is static or local, then
2299       // we don't need to use the PLT - we can directly call it.
2300       if (Subtarget->isTargetELF() &&
2301           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2302           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2303         OpFlags = X86II::MO_PLT;
2304       } else if (Subtarget->isPICStyleStubAny() &&
2305                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2306                  (!Subtarget->getTargetTriple().isMacOSX() ||
2307                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2308         // PC-relative references to external symbols should go through $stub,
2309         // unless we're building with the leopard linker or later, which
2310         // automatically synthesizes these stubs.
2311         OpFlags = X86II::MO_DARWIN_STUB;
2312       } else if (Subtarget->isPICStyleRIPRel() &&
2313                  isa<Function>(GV) &&
2314                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2315         // If the function is marked as non-lazy, generate an indirect call
2316         // which loads from the GOT directly. This avoids runtime overhead
2317         // at the cost of eager binding (and one extra byte of encoding).
2318         OpFlags = X86II::MO_GOTPCREL;
2319         WrapperKind = X86ISD::WrapperRIP;
2320         ExtraLoad = true;
2321       }
2322
2323       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2324                                           G->getOffset(), OpFlags);
2325
2326       // Add a wrapper if needed.
2327       if (WrapperKind != ISD::DELETED_NODE)
2328         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2329       // Add extra indirection if needed.
2330       if (ExtraLoad)
2331         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2332                              MachinePointerInfo::getGOT(),
2333                              false, false, 0);
2334     }
2335   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2336     unsigned char OpFlags = 0;
2337
2338     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2339     // external symbols should go through the PLT.
2340     if (Subtarget->isTargetELF() &&
2341         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2342       OpFlags = X86II::MO_PLT;
2343     } else if (Subtarget->isPICStyleStubAny() &&
2344                (!Subtarget->getTargetTriple().isMacOSX() ||
2345                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2346       // PC-relative references to external symbols should go through $stub,
2347       // unless we're building with the leopard linker or later, which
2348       // automatically synthesizes these stubs.
2349       OpFlags = X86II::MO_DARWIN_STUB;
2350     }
2351
2352     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2353                                          OpFlags);
2354   }
2355
2356   // Returns a chain & a flag for retval copy to use.
2357   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2358   SmallVector<SDValue, 8> Ops;
2359
2360   if (!IsSibcall && isTailCall) {
2361     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2362                            DAG.getIntPtrConstant(0, true), InFlag);
2363     InFlag = Chain.getValue(1);
2364   }
2365
2366   Ops.push_back(Chain);
2367   Ops.push_back(Callee);
2368
2369   if (isTailCall)
2370     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2371
2372   // Add argument registers to the end of the list so that they are known live
2373   // into the call.
2374   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2375     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2376                                   RegsToPass[i].second.getValueType()));
2377
2378   // Add an implicit use GOT pointer in EBX.
2379   if (!isTailCall && Subtarget->isPICStyleGOT())
2380     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2381
2382   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2383   if (Is64Bit && isVarArg && !IsWin64)
2384     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2385
2386   if (InFlag.getNode())
2387     Ops.push_back(InFlag);
2388
2389   if (isTailCall) {
2390     // We used to do:
2391     //// If this is the first return lowered for this function, add the regs
2392     //// to the liveout set for the function.
2393     // This isn't right, although it's probably harmless on x86; liveouts
2394     // should be computed from returns not tail calls.  Consider a void
2395     // function making a tail call to a function returning int.
2396     return DAG.getNode(X86ISD::TC_RETURN, dl,
2397                        NodeTys, &Ops[0], Ops.size());
2398   }
2399
2400   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2401   InFlag = Chain.getValue(1);
2402
2403   // Create the CALLSEQ_END node.
2404   unsigned NumBytesForCalleeToPush;
2405   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2406     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2407   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2408     // If this is a call to a struct-return function, the callee
2409     // pops the hidden struct pointer, so we have to push it back.
2410     // This is common for Darwin/X86, Linux & Mingw32 targets.
2411     NumBytesForCalleeToPush = 4;
2412   else
2413     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2414
2415   // Returns a flag for retval copy to use.
2416   if (!IsSibcall) {
2417     Chain = DAG.getCALLSEQ_END(Chain,
2418                                DAG.getIntPtrConstant(NumBytes, true),
2419                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2420                                                      true),
2421                                InFlag);
2422     InFlag = Chain.getValue(1);
2423   }
2424
2425   // Handle result values, copying them out of physregs into vregs that we
2426   // return.
2427   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2428                          Ins, dl, DAG, InVals);
2429 }
2430
2431
2432 //===----------------------------------------------------------------------===//
2433 //                Fast Calling Convention (tail call) implementation
2434 //===----------------------------------------------------------------------===//
2435
2436 //  Like std call, callee cleans arguments, convention except that ECX is
2437 //  reserved for storing the tail called function address. Only 2 registers are
2438 //  free for argument passing (inreg). Tail call optimization is performed
2439 //  provided:
2440 //                * tailcallopt is enabled
2441 //                * caller/callee are fastcc
2442 //  On X86_64 architecture with GOT-style position independent code only local
2443 //  (within module) calls are supported at the moment.
2444 //  To keep the stack aligned according to platform abi the function
2445 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2446 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2447 //  If a tail called function callee has more arguments than the caller the
2448 //  caller needs to make sure that there is room to move the RETADDR to. This is
2449 //  achieved by reserving an area the size of the argument delta right after the
2450 //  original REtADDR, but before the saved framepointer or the spilled registers
2451 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2452 //  stack layout:
2453 //    arg1
2454 //    arg2
2455 //    RETADDR
2456 //    [ new RETADDR
2457 //      move area ]
2458 //    (possible EBP)
2459 //    ESI
2460 //    EDI
2461 //    local1 ..
2462
2463 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2464 /// for a 16 byte align requirement.
2465 unsigned
2466 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2467                                                SelectionDAG& DAG) const {
2468   MachineFunction &MF = DAG.getMachineFunction();
2469   const TargetMachine &TM = MF.getTarget();
2470   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2471   unsigned StackAlignment = TFI.getStackAlignment();
2472   uint64_t AlignMask = StackAlignment - 1;
2473   int64_t Offset = StackSize;
2474   uint64_t SlotSize = TD->getPointerSize();
2475   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2476     // Number smaller than 12 so just add the difference.
2477     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2478   } else {
2479     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2480     Offset = ((~AlignMask) & Offset) + StackAlignment +
2481       (StackAlignment-SlotSize);
2482   }
2483   return Offset;
2484 }
2485
2486 /// MatchingStackOffset - Return true if the given stack call argument is
2487 /// already available in the same position (relatively) of the caller's
2488 /// incoming argument stack.
2489 static
2490 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2491                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2492                          const X86InstrInfo *TII) {
2493   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2494   int FI = INT_MAX;
2495   if (Arg.getOpcode() == ISD::CopyFromReg) {
2496     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2497     if (!TargetRegisterInfo::isVirtualRegister(VR))
2498       return false;
2499     MachineInstr *Def = MRI->getVRegDef(VR);
2500     if (!Def)
2501       return false;
2502     if (!Flags.isByVal()) {
2503       if (!TII->isLoadFromStackSlot(Def, FI))
2504         return false;
2505     } else {
2506       unsigned Opcode = Def->getOpcode();
2507       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2508           Def->getOperand(1).isFI()) {
2509         FI = Def->getOperand(1).getIndex();
2510         Bytes = Flags.getByValSize();
2511       } else
2512         return false;
2513     }
2514   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2515     if (Flags.isByVal())
2516       // ByVal argument is passed in as a pointer but it's now being
2517       // dereferenced. e.g.
2518       // define @foo(%struct.X* %A) {
2519       //   tail call @bar(%struct.X* byval %A)
2520       // }
2521       return false;
2522     SDValue Ptr = Ld->getBasePtr();
2523     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2524     if (!FINode)
2525       return false;
2526     FI = FINode->getIndex();
2527   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2528     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2529     FI = FINode->getIndex();
2530     Bytes = Flags.getByValSize();
2531   } else
2532     return false;
2533
2534   assert(FI != INT_MAX);
2535   if (!MFI->isFixedObjectIndex(FI))
2536     return false;
2537   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2538 }
2539
2540 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2541 /// for tail call optimization. Targets which want to do tail call
2542 /// optimization should implement this function.
2543 bool
2544 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2545                                                      CallingConv::ID CalleeCC,
2546                                                      bool isVarArg,
2547                                                      bool isCalleeStructRet,
2548                                                      bool isCallerStructRet,
2549                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2550                                     const SmallVectorImpl<SDValue> &OutVals,
2551                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2552                                                      SelectionDAG& DAG) const {
2553   if (!IsTailCallConvention(CalleeCC) &&
2554       CalleeCC != CallingConv::C)
2555     return false;
2556
2557   // If -tailcallopt is specified, make fastcc functions tail-callable.
2558   const MachineFunction &MF = DAG.getMachineFunction();
2559   const Function *CallerF = DAG.getMachineFunction().getFunction();
2560   CallingConv::ID CallerCC = CallerF->getCallingConv();
2561   bool CCMatch = CallerCC == CalleeCC;
2562
2563   if (GuaranteedTailCallOpt) {
2564     if (IsTailCallConvention(CalleeCC) && CCMatch)
2565       return true;
2566     return false;
2567   }
2568
2569   // Look for obvious safe cases to perform tail call optimization that do not
2570   // require ABI changes. This is what gcc calls sibcall.
2571
2572   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2573   // emit a special epilogue.
2574   if (RegInfo->needsStackRealignment(MF))
2575     return false;
2576
2577   // Also avoid sibcall optimization if either caller or callee uses struct
2578   // return semantics.
2579   if (isCalleeStructRet || isCallerStructRet)
2580     return false;
2581
2582   // An stdcall caller is expected to clean up its arguments; the callee
2583   // isn't going to do that.
2584   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2585     return false;
2586
2587   // Do not sibcall optimize vararg calls unless all arguments are passed via
2588   // registers.
2589   if (isVarArg && !Outs.empty()) {
2590
2591     // Optimizing for varargs on Win64 is unlikely to be safe without
2592     // additional testing.
2593     if (Subtarget->isTargetWin64())
2594       return false;
2595
2596     SmallVector<CCValAssign, 16> ArgLocs;
2597     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2598                    getTargetMachine(), ArgLocs, *DAG.getContext());
2599
2600     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2601     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2602       if (!ArgLocs[i].isRegLoc())
2603         return false;
2604   }
2605
2606   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2607   // Therefore if it's not used by the call it is not safe to optimize this into
2608   // a sibcall.
2609   bool Unused = false;
2610   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2611     if (!Ins[i].Used) {
2612       Unused = true;
2613       break;
2614     }
2615   }
2616   if (Unused) {
2617     SmallVector<CCValAssign, 16> RVLocs;
2618     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2619                    getTargetMachine(), RVLocs, *DAG.getContext());
2620     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2621     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2622       CCValAssign &VA = RVLocs[i];
2623       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2624         return false;
2625     }
2626   }
2627
2628   // If the calling conventions do not match, then we'd better make sure the
2629   // results are returned in the same way as what the caller expects.
2630   if (!CCMatch) {
2631     SmallVector<CCValAssign, 16> RVLocs1;
2632     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2633                     getTargetMachine(), RVLocs1, *DAG.getContext());
2634     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2635
2636     SmallVector<CCValAssign, 16> RVLocs2;
2637     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2638                     getTargetMachine(), RVLocs2, *DAG.getContext());
2639     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2640
2641     if (RVLocs1.size() != RVLocs2.size())
2642       return false;
2643     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2644       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2645         return false;
2646       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2647         return false;
2648       if (RVLocs1[i].isRegLoc()) {
2649         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2650           return false;
2651       } else {
2652         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2653           return false;
2654       }
2655     }
2656   }
2657
2658   // If the callee takes no arguments then go on to check the results of the
2659   // call.
2660   if (!Outs.empty()) {
2661     // Check if stack adjustment is needed. For now, do not do this if any
2662     // argument is passed on the stack.
2663     SmallVector<CCValAssign, 16> ArgLocs;
2664     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2665                    getTargetMachine(), ArgLocs, *DAG.getContext());
2666
2667     // Allocate shadow area for Win64
2668     if (Subtarget->isTargetWin64()) {
2669       CCInfo.AllocateStack(32, 8);
2670     }
2671
2672     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2673     if (CCInfo.getNextStackOffset()) {
2674       MachineFunction &MF = DAG.getMachineFunction();
2675       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2676         return false;
2677
2678       // Check if the arguments are already laid out in the right way as
2679       // the caller's fixed stack objects.
2680       MachineFrameInfo *MFI = MF.getFrameInfo();
2681       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2682       const X86InstrInfo *TII =
2683         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2684       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2685         CCValAssign &VA = ArgLocs[i];
2686         SDValue Arg = OutVals[i];
2687         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2688         if (VA.getLocInfo() == CCValAssign::Indirect)
2689           return false;
2690         if (!VA.isRegLoc()) {
2691           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2692                                    MFI, MRI, TII))
2693             return false;
2694         }
2695       }
2696     }
2697
2698     // If the tailcall address may be in a register, then make sure it's
2699     // possible to register allocate for it. In 32-bit, the call address can
2700     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2701     // callee-saved registers are restored. These happen to be the same
2702     // registers used to pass 'inreg' arguments so watch out for those.
2703     if (!Subtarget->is64Bit() &&
2704         !isa<GlobalAddressSDNode>(Callee) &&
2705         !isa<ExternalSymbolSDNode>(Callee)) {
2706       unsigned NumInRegs = 0;
2707       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2708         CCValAssign &VA = ArgLocs[i];
2709         if (!VA.isRegLoc())
2710           continue;
2711         unsigned Reg = VA.getLocReg();
2712         switch (Reg) {
2713         default: break;
2714         case X86::EAX: case X86::EDX: case X86::ECX:
2715           if (++NumInRegs == 3)
2716             return false;
2717           break;
2718         }
2719       }
2720     }
2721   }
2722
2723   return true;
2724 }
2725
2726 FastISel *
2727 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2728   return X86::createFastISel(funcInfo);
2729 }
2730
2731
2732 //===----------------------------------------------------------------------===//
2733 //                           Other Lowering Hooks
2734 //===----------------------------------------------------------------------===//
2735
2736 static bool MayFoldLoad(SDValue Op) {
2737   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2738 }
2739
2740 static bool MayFoldIntoStore(SDValue Op) {
2741   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2742 }
2743
2744 static bool isTargetShuffle(unsigned Opcode) {
2745   switch(Opcode) {
2746   default: return false;
2747   case X86ISD::PSHUFD:
2748   case X86ISD::PSHUFHW:
2749   case X86ISD::PSHUFLW:
2750   case X86ISD::SHUFPD:
2751   case X86ISD::PALIGN:
2752   case X86ISD::SHUFPS:
2753   case X86ISD::MOVLHPS:
2754   case X86ISD::MOVLHPD:
2755   case X86ISD::MOVHLPS:
2756   case X86ISD::MOVLPS:
2757   case X86ISD::MOVLPD:
2758   case X86ISD::MOVSHDUP:
2759   case X86ISD::MOVSLDUP:
2760   case X86ISD::MOVDDUP:
2761   case X86ISD::MOVSS:
2762   case X86ISD::MOVSD:
2763   case X86ISD::UNPCKLPS:
2764   case X86ISD::UNPCKLPD:
2765   case X86ISD::VUNPCKLPSY:
2766   case X86ISD::VUNPCKLPDY:
2767   case X86ISD::PUNPCKLWD:
2768   case X86ISD::PUNPCKLBW:
2769   case X86ISD::PUNPCKLDQ:
2770   case X86ISD::PUNPCKLQDQ:
2771   case X86ISD::UNPCKHPS:
2772   case X86ISD::UNPCKHPD:
2773   case X86ISD::VUNPCKHPSY:
2774   case X86ISD::VUNPCKHPDY:
2775   case X86ISD::PUNPCKHWD:
2776   case X86ISD::PUNPCKHBW:
2777   case X86ISD::PUNPCKHDQ:
2778   case X86ISD::PUNPCKHQDQ:
2779   case X86ISD::VPERMILPS:
2780   case X86ISD::VPERMILPSY:
2781   case X86ISD::VPERMILPD:
2782   case X86ISD::VPERMILPDY:
2783   case X86ISD::VPERM2F128:
2784     return true;
2785   }
2786   return false;
2787 }
2788
2789 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2790                                                SDValue V1, SelectionDAG &DAG) {
2791   switch(Opc) {
2792   default: llvm_unreachable("Unknown x86 shuffle node");
2793   case X86ISD::MOVSHDUP:
2794   case X86ISD::MOVSLDUP:
2795   case X86ISD::MOVDDUP:
2796     return DAG.getNode(Opc, dl, VT, V1);
2797   }
2798
2799   return SDValue();
2800 }
2801
2802 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2803                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2804   switch(Opc) {
2805   default: llvm_unreachable("Unknown x86 shuffle node");
2806   case X86ISD::PSHUFD:
2807   case X86ISD::PSHUFHW:
2808   case X86ISD::PSHUFLW:
2809   case X86ISD::VPERMILPS:
2810   case X86ISD::VPERMILPSY:
2811   case X86ISD::VPERMILPD:
2812   case X86ISD::VPERMILPDY:
2813     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2814   }
2815
2816   return SDValue();
2817 }
2818
2819 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2820                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2821   switch(Opc) {
2822   default: llvm_unreachable("Unknown x86 shuffle node");
2823   case X86ISD::PALIGN:
2824   case X86ISD::SHUFPD:
2825   case X86ISD::SHUFPS:
2826   case X86ISD::VPERM2F128:
2827     return DAG.getNode(Opc, dl, VT, V1, V2,
2828                        DAG.getConstant(TargetMask, MVT::i8));
2829   }
2830   return SDValue();
2831 }
2832
2833 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2834                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2835   switch(Opc) {
2836   default: llvm_unreachable("Unknown x86 shuffle node");
2837   case X86ISD::MOVLHPS:
2838   case X86ISD::MOVLHPD:
2839   case X86ISD::MOVHLPS:
2840   case X86ISD::MOVLPS:
2841   case X86ISD::MOVLPD:
2842   case X86ISD::MOVSS:
2843   case X86ISD::MOVSD:
2844   case X86ISD::UNPCKLPS:
2845   case X86ISD::UNPCKLPD:
2846   case X86ISD::VUNPCKLPSY:
2847   case X86ISD::VUNPCKLPDY:
2848   case X86ISD::PUNPCKLWD:
2849   case X86ISD::PUNPCKLBW:
2850   case X86ISD::PUNPCKLDQ:
2851   case X86ISD::PUNPCKLQDQ:
2852   case X86ISD::UNPCKHPS:
2853   case X86ISD::UNPCKHPD:
2854   case X86ISD::VUNPCKHPSY:
2855   case X86ISD::VUNPCKHPDY:
2856   case X86ISD::PUNPCKHWD:
2857   case X86ISD::PUNPCKHBW:
2858   case X86ISD::PUNPCKHDQ:
2859   case X86ISD::PUNPCKHQDQ:
2860     return DAG.getNode(Opc, dl, VT, V1, V2);
2861   }
2862   return SDValue();
2863 }
2864
2865 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2868   int ReturnAddrIndex = FuncInfo->getRAIndex();
2869
2870   if (ReturnAddrIndex == 0) {
2871     // Set up a frame object for the return address.
2872     uint64_t SlotSize = TD->getPointerSize();
2873     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2874                                                            false);
2875     FuncInfo->setRAIndex(ReturnAddrIndex);
2876   }
2877
2878   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2879 }
2880
2881
2882 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2883                                        bool hasSymbolicDisplacement) {
2884   // Offset should fit into 32 bit immediate field.
2885   if (!isInt<32>(Offset))
2886     return false;
2887
2888   // If we don't have a symbolic displacement - we don't have any extra
2889   // restrictions.
2890   if (!hasSymbolicDisplacement)
2891     return true;
2892
2893   // FIXME: Some tweaks might be needed for medium code model.
2894   if (M != CodeModel::Small && M != CodeModel::Kernel)
2895     return false;
2896
2897   // For small code model we assume that latest object is 16MB before end of 31
2898   // bits boundary. We may also accept pretty large negative constants knowing
2899   // that all objects are in the positive half of address space.
2900   if (M == CodeModel::Small && Offset < 16*1024*1024)
2901     return true;
2902
2903   // For kernel code model we know that all object resist in the negative half
2904   // of 32bits address space. We may not accept negative offsets, since they may
2905   // be just off and we may accept pretty large positive ones.
2906   if (M == CodeModel::Kernel && Offset > 0)
2907     return true;
2908
2909   return false;
2910 }
2911
2912 /// isCalleePop - Determines whether the callee is required to pop its
2913 /// own arguments. Callee pop is necessary to support tail calls.
2914 bool X86::isCalleePop(CallingConv::ID CallingConv,
2915                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2916   if (IsVarArg)
2917     return false;
2918
2919   switch (CallingConv) {
2920   default:
2921     return false;
2922   case CallingConv::X86_StdCall:
2923     return !is64Bit;
2924   case CallingConv::X86_FastCall:
2925     return !is64Bit;
2926   case CallingConv::X86_ThisCall:
2927     return !is64Bit;
2928   case CallingConv::Fast:
2929     return TailCallOpt;
2930   case CallingConv::GHC:
2931     return TailCallOpt;
2932   }
2933 }
2934
2935 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2936 /// specific condition code, returning the condition code and the LHS/RHS of the
2937 /// comparison to make.
2938 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2939                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2940   if (!isFP) {
2941     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2942       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2943         // X > -1   -> X == 0, jump !sign.
2944         RHS = DAG.getConstant(0, RHS.getValueType());
2945         return X86::COND_NS;
2946       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2947         // X < 0   -> X == 0, jump on sign.
2948         return X86::COND_S;
2949       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2950         // X < 1   -> X <= 0
2951         RHS = DAG.getConstant(0, RHS.getValueType());
2952         return X86::COND_LE;
2953       }
2954     }
2955
2956     switch (SetCCOpcode) {
2957     default: llvm_unreachable("Invalid integer condition!");
2958     case ISD::SETEQ:  return X86::COND_E;
2959     case ISD::SETGT:  return X86::COND_G;
2960     case ISD::SETGE:  return X86::COND_GE;
2961     case ISD::SETLT:  return X86::COND_L;
2962     case ISD::SETLE:  return X86::COND_LE;
2963     case ISD::SETNE:  return X86::COND_NE;
2964     case ISD::SETULT: return X86::COND_B;
2965     case ISD::SETUGT: return X86::COND_A;
2966     case ISD::SETULE: return X86::COND_BE;
2967     case ISD::SETUGE: return X86::COND_AE;
2968     }
2969   }
2970
2971   // First determine if it is required or is profitable to flip the operands.
2972
2973   // If LHS is a foldable load, but RHS is not, flip the condition.
2974   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2975       !ISD::isNON_EXTLoad(RHS.getNode())) {
2976     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2977     std::swap(LHS, RHS);
2978   }
2979
2980   switch (SetCCOpcode) {
2981   default: break;
2982   case ISD::SETOLT:
2983   case ISD::SETOLE:
2984   case ISD::SETUGT:
2985   case ISD::SETUGE:
2986     std::swap(LHS, RHS);
2987     break;
2988   }
2989
2990   // On a floating point condition, the flags are set as follows:
2991   // ZF  PF  CF   op
2992   //  0 | 0 | 0 | X > Y
2993   //  0 | 0 | 1 | X < Y
2994   //  1 | 0 | 0 | X == Y
2995   //  1 | 1 | 1 | unordered
2996   switch (SetCCOpcode) {
2997   default: llvm_unreachable("Condcode should be pre-legalized away");
2998   case ISD::SETUEQ:
2999   case ISD::SETEQ:   return X86::COND_E;
3000   case ISD::SETOLT:              // flipped
3001   case ISD::SETOGT:
3002   case ISD::SETGT:   return X86::COND_A;
3003   case ISD::SETOLE:              // flipped
3004   case ISD::SETOGE:
3005   case ISD::SETGE:   return X86::COND_AE;
3006   case ISD::SETUGT:              // flipped
3007   case ISD::SETULT:
3008   case ISD::SETLT:   return X86::COND_B;
3009   case ISD::SETUGE:              // flipped
3010   case ISD::SETULE:
3011   case ISD::SETLE:   return X86::COND_BE;
3012   case ISD::SETONE:
3013   case ISD::SETNE:   return X86::COND_NE;
3014   case ISD::SETUO:   return X86::COND_P;
3015   case ISD::SETO:    return X86::COND_NP;
3016   case ISD::SETOEQ:
3017   case ISD::SETUNE:  return X86::COND_INVALID;
3018   }
3019 }
3020
3021 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3022 /// code. Current x86 isa includes the following FP cmov instructions:
3023 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3024 static bool hasFPCMov(unsigned X86CC) {
3025   switch (X86CC) {
3026   default:
3027     return false;
3028   case X86::COND_B:
3029   case X86::COND_BE:
3030   case X86::COND_E:
3031   case X86::COND_P:
3032   case X86::COND_A:
3033   case X86::COND_AE:
3034   case X86::COND_NE:
3035   case X86::COND_NP:
3036     return true;
3037   }
3038 }
3039
3040 /// isFPImmLegal - Returns true if the target can instruction select the
3041 /// specified FP immediate natively. If false, the legalizer will
3042 /// materialize the FP immediate as a load from a constant pool.
3043 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3044   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3045     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3046       return true;
3047   }
3048   return false;
3049 }
3050
3051 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3052 /// the specified range (L, H].
3053 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3054   return (Val < 0) || (Val >= Low && Val < Hi);
3055 }
3056
3057 /// isUndefOrInRange - Return true if every element in Mask, begining
3058 /// from position Pos and ending in Pos+Size, falls within the specified
3059 /// range (L, L+Pos]. or is undef.
3060 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3061                              int Pos, int Size, int Low, int Hi) {
3062   for (int i = Pos, e = Pos+Size; i != e; ++i)
3063     if (!isUndefOrInRange(Mask[i], Low, Hi))
3064       return false;
3065   return true;
3066 }
3067
3068 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3069 /// specified value.
3070 static bool isUndefOrEqual(int Val, int CmpVal) {
3071   if (Val < 0 || Val == CmpVal)
3072     return true;
3073   return false;
3074 }
3075
3076 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3077 /// from position Pos and ending in Pos+Size, falls within the specified
3078 /// sequential range (L, L+Pos]. or is undef.
3079 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3080                                        int Pos, int Size, int Low) {
3081   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3082     if (!isUndefOrEqual(Mask[i], Low))
3083       return false;
3084   return true;
3085 }
3086
3087 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3088 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3089 /// the second operand.
3090 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3091   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3092     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3093   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3094     return (Mask[0] < 2 && Mask[1] < 2);
3095   return false;
3096 }
3097
3098 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3099   SmallVector<int, 8> M;
3100   N->getMask(M);
3101   return ::isPSHUFDMask(M, N->getValueType(0));
3102 }
3103
3104 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3105 /// is suitable for input to PSHUFHW.
3106 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3107   if (VT != MVT::v8i16)
3108     return false;
3109
3110   // Lower quadword copied in order or undef.
3111   for (int i = 0; i != 4; ++i)
3112     if (Mask[i] >= 0 && Mask[i] != i)
3113       return false;
3114
3115   // Upper quadword shuffled.
3116   for (int i = 4; i != 8; ++i)
3117     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3118       return false;
3119
3120   return true;
3121 }
3122
3123 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3124   SmallVector<int, 8> M;
3125   N->getMask(M);
3126   return ::isPSHUFHWMask(M, N->getValueType(0));
3127 }
3128
3129 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3130 /// is suitable for input to PSHUFLW.
3131 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3132   if (VT != MVT::v8i16)
3133     return false;
3134
3135   // Upper quadword copied in order.
3136   for (int i = 4; i != 8; ++i)
3137     if (Mask[i] >= 0 && Mask[i] != i)
3138       return false;
3139
3140   // Lower quadword shuffled.
3141   for (int i = 0; i != 4; ++i)
3142     if (Mask[i] >= 4)
3143       return false;
3144
3145   return true;
3146 }
3147
3148 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3149   SmallVector<int, 8> M;
3150   N->getMask(M);
3151   return ::isPSHUFLWMask(M, N->getValueType(0));
3152 }
3153
3154 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3155 /// is suitable for input to PALIGNR.
3156 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3157                           bool hasSSSE3) {
3158   int i, e = VT.getVectorNumElements();
3159   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3160     return false;
3161
3162   // Do not handle v2i64 / v2f64 shuffles with palignr.
3163   if (e < 4 || !hasSSSE3)
3164     return false;
3165
3166   for (i = 0; i != e; ++i)
3167     if (Mask[i] >= 0)
3168       break;
3169
3170   // All undef, not a palignr.
3171   if (i == e)
3172     return false;
3173
3174   // Make sure we're shifting in the right direction.
3175   if (Mask[i] <= i)
3176     return false;
3177
3178   int s = Mask[i] - i;
3179
3180   // Check the rest of the elements to see if they are consecutive.
3181   for (++i; i != e; ++i) {
3182     int m = Mask[i];
3183     if (m >= 0 && m != s+i)
3184       return false;
3185   }
3186   return true;
3187 }
3188
3189 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3190 /// specifies a shuffle of elements that is suitable for input to 256-bit
3191 /// VSHUFPSY.
3192 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3193                           const X86Subtarget *Subtarget) {
3194   int NumElems = VT.getVectorNumElements();
3195
3196   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3197     return false;
3198
3199   if (NumElems != 8)
3200     return false;
3201
3202   // VSHUFPSY divides the resulting vector into 4 chunks.
3203   // The sources are also splitted into 4 chunks, and each destination
3204   // chunk must come from a different source chunk.
3205   //
3206   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3207   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3208   //
3209   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3210   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3211   //
3212   int QuarterSize = NumElems/4;
3213   int HalfSize = QuarterSize*2;
3214   for (int i = 0; i < QuarterSize; ++i)
3215     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3216       return false;
3217   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3218     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3219       return false;
3220
3221   // The mask of the second half must be the same as the first but with
3222   // the appropriate offsets. This works in the same way as VPERMILPS
3223   // works with masks.
3224   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3225     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3226       return false;
3227     int FstHalfIdx = i-HalfSize;
3228     if (Mask[FstHalfIdx] < 0)
3229       continue;
3230     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3231       return false;
3232   }
3233   for (int i = QuarterSize*3; i < NumElems; ++i) {
3234     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3235       return false;
3236     int FstHalfIdx = i-HalfSize;
3237     if (Mask[FstHalfIdx] < 0)
3238       continue;
3239     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3240       return false;
3241
3242   }
3243
3244   return true;
3245 }
3246
3247 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3248 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3249 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3250   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3251   EVT VT = SVOp->getValueType(0);
3252   int NumElems = VT.getVectorNumElements();
3253
3254   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3255          "Only supports v8i32 and v8f32 types");
3256
3257   int HalfSize = NumElems/2;
3258   unsigned Mask = 0;
3259   for (int i = 0; i != NumElems ; ++i) {
3260     if (SVOp->getMaskElt(i) < 0)
3261       continue;
3262     // The mask of the first half must be equal to the second one.
3263     unsigned Shamt = (i%HalfSize)*2;
3264     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3265     Mask |= Elt << Shamt;
3266   }
3267
3268   return Mask;
3269 }
3270
3271 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to 256-bit
3273 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3274 /// version and the mask of the second half isn't binded with the first
3275 /// one.
3276 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3277                            const X86Subtarget *Subtarget) {
3278   int NumElems = VT.getVectorNumElements();
3279
3280   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3281     return false;
3282
3283   if (NumElems != 4)
3284     return false;
3285
3286   // VSHUFPSY divides the resulting vector into 4 chunks.
3287   // The sources are also splitted into 4 chunks, and each destination
3288   // chunk must come from a different source chunk.
3289   //
3290   //  SRC1 =>      X3       X2       X1       X0
3291   //  SRC2 =>      Y3       Y2       Y1       Y0
3292   //
3293   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3294   //
3295   int QuarterSize = NumElems/4;
3296   int HalfSize = QuarterSize*2;
3297   for (int i = 0; i < QuarterSize; ++i)
3298     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3299       return false;
3300   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3301     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3302       return false;
3303   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3304     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3305       return false;
3306   for (int i = QuarterSize*3; i < NumElems; ++i)
3307     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3308       return false;
3309
3310   return true;
3311 }
3312
3313 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3314 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3315 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3316   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3317   EVT VT = SVOp->getValueType(0);
3318   int NumElems = VT.getVectorNumElements();
3319
3320   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3321          "Only supports v4i64 and v4f64 types");
3322
3323   int HalfSize = NumElems/2;
3324   unsigned Mask = 0;
3325   for (int i = 0; i != NumElems ; ++i) {
3326     if (SVOp->getMaskElt(i) < 0)
3327       continue;
3328     int Elt = SVOp->getMaskElt(i) % HalfSize;
3329     Mask |= Elt << i;
3330   }
3331
3332   return Mask;
3333 }
3334
3335 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3336 /// specifies a shuffle of elements that is suitable for input to 128-bit
3337 /// SHUFPS and SHUFPD.
3338 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3339   int NumElems = VT.getVectorNumElements();
3340
3341   if (VT.getSizeInBits() != 128)
3342     return false;
3343
3344   if (NumElems != 2 && NumElems != 4)
3345     return false;
3346
3347   int Half = NumElems / 2;
3348   for (int i = 0; i < Half; ++i)
3349     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3350       return false;
3351   for (int i = Half; i < NumElems; ++i)
3352     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3353       return false;
3354
3355   return true;
3356 }
3357
3358 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3359   SmallVector<int, 8> M;
3360   N->getMask(M);
3361   return ::isSHUFPMask(M, N->getValueType(0));
3362 }
3363
3364 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3365 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3366 /// half elements to come from vector 1 (which would equal the dest.) and
3367 /// the upper half to come from vector 2.
3368 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3369   int NumElems = VT.getVectorNumElements();
3370
3371   if (NumElems != 2 && NumElems != 4)
3372     return false;
3373
3374   int Half = NumElems / 2;
3375   for (int i = 0; i < Half; ++i)
3376     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3377       return false;
3378   for (int i = Half; i < NumElems; ++i)
3379     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3380       return false;
3381   return true;
3382 }
3383
3384 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3385   SmallVector<int, 8> M;
3386   N->getMask(M);
3387   return isCommutedSHUFPMask(M, N->getValueType(0));
3388 }
3389
3390 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3391 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3392 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3393   EVT VT = N->getValueType(0);
3394   unsigned NumElems = VT.getVectorNumElements();
3395
3396   if (VT.getSizeInBits() != 128)
3397     return false;
3398
3399   if (NumElems != 4)
3400     return false;
3401
3402   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3403   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3404          isUndefOrEqual(N->getMaskElt(1), 7) &&
3405          isUndefOrEqual(N->getMaskElt(2), 2) &&
3406          isUndefOrEqual(N->getMaskElt(3), 3);
3407 }
3408
3409 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3410 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3411 /// <2, 3, 2, 3>
3412 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3413   EVT VT = N->getValueType(0);
3414   unsigned NumElems = VT.getVectorNumElements();
3415
3416   if (VT.getSizeInBits() != 128)
3417     return false;
3418
3419   if (NumElems != 4)
3420     return false;
3421
3422   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3423          isUndefOrEqual(N->getMaskElt(1), 3) &&
3424          isUndefOrEqual(N->getMaskElt(2), 2) &&
3425          isUndefOrEqual(N->getMaskElt(3), 3);
3426 }
3427
3428 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3429 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3430 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3431   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3432
3433   if (NumElems != 2 && NumElems != 4)
3434     return false;
3435
3436   for (unsigned i = 0; i < NumElems/2; ++i)
3437     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3438       return false;
3439
3440   for (unsigned i = NumElems/2; i < NumElems; ++i)
3441     if (!isUndefOrEqual(N->getMaskElt(i), i))
3442       return false;
3443
3444   return true;
3445 }
3446
3447 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3448 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3449 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3450   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3451
3452   if ((NumElems != 2 && NumElems != 4)
3453       || N->getValueType(0).getSizeInBits() > 128)
3454     return false;
3455
3456   for (unsigned i = 0; i < NumElems/2; ++i)
3457     if (!isUndefOrEqual(N->getMaskElt(i), i))
3458       return false;
3459
3460   for (unsigned i = 0; i < NumElems/2; ++i)
3461     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3462       return false;
3463
3464   return true;
3465 }
3466
3467 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3468 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3469 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3470                          bool V2IsSplat = false) {
3471   int NumElts = VT.getVectorNumElements();
3472
3473   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3474          "Unsupported vector type for unpckh");
3475
3476   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3477     return false;
3478
3479   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3480   // independently on 128-bit lanes.
3481   unsigned NumLanes = VT.getSizeInBits()/128;
3482   unsigned NumLaneElts = NumElts/NumLanes;
3483
3484   unsigned Start = 0;
3485   unsigned End = NumLaneElts;
3486   for (unsigned s = 0; s < NumLanes; ++s) {
3487     for (unsigned i = Start, j = s * NumLaneElts;
3488          i != End;
3489          i += 2, ++j) {
3490       int BitI  = Mask[i];
3491       int BitI1 = Mask[i+1];
3492       if (!isUndefOrEqual(BitI, j))
3493         return false;
3494       if (V2IsSplat) {
3495         if (!isUndefOrEqual(BitI1, NumElts))
3496           return false;
3497       } else {
3498         if (!isUndefOrEqual(BitI1, j + NumElts))
3499           return false;
3500       }
3501     }
3502     // Process the next 128 bits.
3503     Start += NumLaneElts;
3504     End += NumLaneElts;
3505   }
3506
3507   return true;
3508 }
3509
3510 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3511   SmallVector<int, 8> M;
3512   N->getMask(M);
3513   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3514 }
3515
3516 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3517 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3518 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3519                          bool V2IsSplat = false) {
3520   int NumElts = VT.getVectorNumElements();
3521
3522   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3523          "Unsupported vector type for unpckh");
3524
3525   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3526     return false;
3527
3528   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3529   // independently on 128-bit lanes.
3530   unsigned NumLanes = VT.getSizeInBits()/128;
3531   unsigned NumLaneElts = NumElts/NumLanes;
3532
3533   unsigned Start = 0;
3534   unsigned End = NumLaneElts;
3535   for (unsigned l = 0; l != NumLanes; ++l) {
3536     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3537                              i != End; i += 2, ++j) {
3538       int BitI  = Mask[i];
3539       int BitI1 = Mask[i+1];
3540       if (!isUndefOrEqual(BitI, j))
3541         return false;
3542       if (V2IsSplat) {
3543         if (isUndefOrEqual(BitI1, NumElts))
3544           return false;
3545       } else {
3546         if (!isUndefOrEqual(BitI1, j+NumElts))
3547           return false;
3548       }
3549     }
3550     // Process the next 128 bits.
3551     Start += NumLaneElts;
3552     End += NumLaneElts;
3553   }
3554   return true;
3555 }
3556
3557 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3558   SmallVector<int, 8> M;
3559   N->getMask(M);
3560   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3561 }
3562
3563 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3564 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3565 /// <0, 0, 1, 1>
3566 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3567   int NumElems = VT.getVectorNumElements();
3568   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3569     return false;
3570
3571   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3572   // FIXME: Need a better way to get rid of this, there's no latency difference
3573   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3574   // the former later. We should also remove the "_undef" special mask.
3575   if (NumElems == 4 && VT.getSizeInBits() == 256)
3576     return false;
3577
3578   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3579   // independently on 128-bit lanes.
3580   unsigned NumLanes = VT.getSizeInBits() / 128;
3581   unsigned NumLaneElts = NumElems / NumLanes;
3582
3583   for (unsigned s = 0; s < NumLanes; ++s) {
3584     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3585          i != NumLaneElts * (s + 1);
3586          i += 2, ++j) {
3587       int BitI  = Mask[i];
3588       int BitI1 = Mask[i+1];
3589
3590       if (!isUndefOrEqual(BitI, j))
3591         return false;
3592       if (!isUndefOrEqual(BitI1, j))
3593         return false;
3594     }
3595   }
3596
3597   return true;
3598 }
3599
3600 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3601   SmallVector<int, 8> M;
3602   N->getMask(M);
3603   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3604 }
3605
3606 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3607 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3608 /// <2, 2, 3, 3>
3609 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3610   int NumElems = VT.getVectorNumElements();
3611   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3612     return false;
3613
3614   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3615     int BitI  = Mask[i];
3616     int BitI1 = Mask[i+1];
3617     if (!isUndefOrEqual(BitI, j))
3618       return false;
3619     if (!isUndefOrEqual(BitI1, j))
3620       return false;
3621   }
3622   return true;
3623 }
3624
3625 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3626   SmallVector<int, 8> M;
3627   N->getMask(M);
3628   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3629 }
3630
3631 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3632 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3633 /// MOVSD, and MOVD, i.e. setting the lowest element.
3634 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3635   if (VT.getVectorElementType().getSizeInBits() < 32)
3636     return false;
3637
3638   int NumElts = VT.getVectorNumElements();
3639
3640   if (!isUndefOrEqual(Mask[0], NumElts))
3641     return false;
3642
3643   for (int i = 1; i < NumElts; ++i)
3644     if (!isUndefOrEqual(Mask[i], i))
3645       return false;
3646
3647   return true;
3648 }
3649
3650 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3651   SmallVector<int, 8> M;
3652   N->getMask(M);
3653   return ::isMOVLMask(M, N->getValueType(0));
3654 }
3655
3656 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3657 /// as permutations between 128-bit chunks or halves. As an example: this
3658 /// shuffle bellow:
3659 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3660 /// The first half comes from the second half of V1 and the second half from the
3661 /// the second half of V2.
3662 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3663                              const X86Subtarget *Subtarget) {
3664   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3665     return false;
3666
3667   // The shuffle result is divided into half A and half B. In total the two
3668   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3669   // B must come from C, D, E or F.
3670   int HalfSize = VT.getVectorNumElements()/2;
3671   bool MatchA = false, MatchB = false;
3672
3673   // Check if A comes from one of C, D, E, F.
3674   for (int Half = 0; Half < 4; ++Half) {
3675     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3676       MatchA = true;
3677       break;
3678     }
3679   }
3680
3681   // Check if B comes from one of C, D, E, F.
3682   for (int Half = 0; Half < 4; ++Half) {
3683     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3684       MatchB = true;
3685       break;
3686     }
3687   }
3688
3689   return MatchA && MatchB;
3690 }
3691
3692 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3693 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3694 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3695   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3696   EVT VT = SVOp->getValueType(0);
3697
3698   int HalfSize = VT.getVectorNumElements()/2;
3699
3700   int FstHalf = 0, SndHalf = 0;
3701   for (int i = 0; i < HalfSize; ++i) {
3702     if (SVOp->getMaskElt(i) > 0) {
3703       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3704       break;
3705     }
3706   }
3707   for (int i = HalfSize; i < HalfSize*2; ++i) {
3708     if (SVOp->getMaskElt(i) > 0) {
3709       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3710       break;
3711     }
3712   }
3713
3714   return (FstHalf | (SndHalf << 4));
3715 }
3716
3717 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3718 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3719 /// Note that VPERMIL mask matching is different depending whether theunderlying
3720 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3721 /// to the same elements of the low, but to the higher half of the source.
3722 /// In VPERMILPD the two lanes could be shuffled independently of each other
3723 /// with the same restriction that lanes can't be crossed.
3724 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3725                             const X86Subtarget *Subtarget) {
3726   int NumElts = VT.getVectorNumElements();
3727   int NumLanes = VT.getSizeInBits()/128;
3728
3729   if (!Subtarget->hasAVX())
3730     return false;
3731
3732   // Match any permutation of 128-bit vector with 64-bit types
3733   if (NumLanes == 1 && NumElts != 2)
3734     return false;
3735
3736   // Only match 256-bit with 32 types
3737   if (VT.getSizeInBits() == 256 && NumElts != 4)
3738     return false;
3739
3740   // The mask on the high lane is independent of the low. Both can match
3741   // any element in inside its own lane, but can't cross.
3742   int LaneSize = NumElts/NumLanes;
3743   for (int l = 0; l < NumLanes; ++l)
3744     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3745       int LaneStart = l*LaneSize;
3746       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3747         return false;
3748     }
3749
3750   return true;
3751 }
3752
3753 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3754 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3755 /// Note that VPERMIL mask matching is different depending whether theunderlying
3756 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3757 /// to the same elements of the low, but to the higher half of the source.
3758 /// In VPERMILPD the two lanes could be shuffled independently of each other
3759 /// with the same restriction that lanes can't be crossed.
3760 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3761                             const X86Subtarget *Subtarget) {
3762   unsigned NumElts = VT.getVectorNumElements();
3763   unsigned NumLanes = VT.getSizeInBits()/128;
3764
3765   if (!Subtarget->hasAVX())
3766     return false;
3767
3768   // Match any permutation of 128-bit vector with 32-bit types
3769   if (NumLanes == 1 && NumElts != 4)
3770     return false;
3771
3772   // Only match 256-bit with 32 types
3773   if (VT.getSizeInBits() == 256 && NumElts != 8)
3774     return false;
3775
3776   // The mask on the high lane should be the same as the low. Actually,
3777   // they can differ if any of the corresponding index in a lane is undef
3778   // and the other stays in range.
3779   int LaneSize = NumElts/NumLanes;
3780   for (int i = 0; i < LaneSize; ++i) {
3781     int HighElt = i+LaneSize;
3782     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3783     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3784
3785     if (!HighValid || !LowValid)
3786       return false;
3787     if (Mask[i] < 0 || Mask[HighElt] < 0)
3788       continue;
3789     if (Mask[HighElt]-Mask[i] != LaneSize)
3790       return false;
3791   }
3792
3793   return true;
3794 }
3795
3796 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3797 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3798 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3799   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3800   EVT VT = SVOp->getValueType(0);
3801
3802   int NumElts = VT.getVectorNumElements();
3803   int NumLanes = VT.getSizeInBits()/128;
3804   int LaneSize = NumElts/NumLanes;
3805
3806   // Although the mask is equal for both lanes do it twice to get the cases
3807   // where a mask will match because the same mask element is undef on the
3808   // first half but valid on the second. This would get pathological cases
3809   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3810   unsigned Mask = 0;
3811   for (int l = 0; l < NumLanes; ++l) {
3812     for (int i = 0; i < LaneSize; ++i) {
3813       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3814       if (MaskElt < 0)
3815         continue;
3816       if (MaskElt >= LaneSize)
3817         MaskElt -= LaneSize;
3818       Mask |= MaskElt << (i*2);
3819     }
3820   }
3821
3822   return Mask;
3823 }
3824
3825 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3826 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3827 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3828   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3829   EVT VT = SVOp->getValueType(0);
3830
3831   int NumElts = VT.getVectorNumElements();
3832   int NumLanes = VT.getSizeInBits()/128;
3833
3834   unsigned Mask = 0;
3835   int LaneSize = NumElts/NumLanes;
3836   for (int l = 0; l < NumLanes; ++l)
3837     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3838       int MaskElt = SVOp->getMaskElt(i);
3839       if (MaskElt < 0)
3840         continue;
3841       Mask |= (MaskElt-l*LaneSize) << i;
3842     }
3843
3844   return Mask;
3845 }
3846
3847 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3848 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3849 /// element of vector 2 and the other elements to come from vector 1 in order.
3850 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3851                                bool V2IsSplat = false, bool V2IsUndef = false) {
3852   int NumOps = VT.getVectorNumElements();
3853   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3854     return false;
3855
3856   if (!isUndefOrEqual(Mask[0], 0))
3857     return false;
3858
3859   for (int i = 1; i < NumOps; ++i)
3860     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3861           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3862           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3863       return false;
3864
3865   return true;
3866 }
3867
3868 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3869                            bool V2IsUndef = false) {
3870   SmallVector<int, 8> M;
3871   N->getMask(M);
3872   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3873 }
3874
3875 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3876 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3877 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3878 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3879                          const X86Subtarget *Subtarget) {
3880   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3881     return false;
3882
3883   // The second vector must be undef
3884   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3885     return false;
3886
3887   EVT VT = N->getValueType(0);
3888   unsigned NumElems = VT.getVectorNumElements();
3889
3890   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3891       (VT.getSizeInBits() == 256 && NumElems != 8))
3892     return false;
3893
3894   // "i+1" is the value the indexed mask element must have
3895   for (unsigned i = 0; i < NumElems; i += 2)
3896     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3897         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3898       return false;
3899
3900   return true;
3901 }
3902
3903 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3905 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3906 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3907                          const X86Subtarget *Subtarget) {
3908   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3909     return false;
3910
3911   // The second vector must be undef
3912   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3913     return false;
3914
3915   EVT VT = N->getValueType(0);
3916   unsigned NumElems = VT.getVectorNumElements();
3917
3918   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3919       (VT.getSizeInBits() == 256 && NumElems != 8))
3920     return false;
3921
3922   // "i" is the value the indexed mask element must have
3923   for (unsigned i = 0; i < NumElems; i += 2)
3924     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3925         !isUndefOrEqual(N->getMaskElt(i+1), i))
3926       return false;
3927
3928   return true;
3929 }
3930
3931 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3932 /// specifies a shuffle of elements that is suitable for input to 256-bit
3933 /// version of MOVDDUP.
3934 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3935                            const X86Subtarget *Subtarget) {
3936   EVT VT = N->getValueType(0);
3937   int NumElts = VT.getVectorNumElements();
3938   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3939
3940   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3941       !V2IsUndef || NumElts != 4)
3942     return false;
3943
3944   for (int i = 0; i != NumElts/2; ++i)
3945     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3946       return false;
3947   for (int i = NumElts/2; i != NumElts; ++i)
3948     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3949       return false;
3950   return true;
3951 }
3952
3953 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3954 /// specifies a shuffle of elements that is suitable for input to 128-bit
3955 /// version of MOVDDUP.
3956 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3957   EVT VT = N->getValueType(0);
3958
3959   if (VT.getSizeInBits() != 128)
3960     return false;
3961
3962   int e = VT.getVectorNumElements() / 2;
3963   for (int i = 0; i < e; ++i)
3964     if (!isUndefOrEqual(N->getMaskElt(i), i))
3965       return false;
3966   for (int i = 0; i < e; ++i)
3967     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3968       return false;
3969   return true;
3970 }
3971
3972 /// isVEXTRACTF128Index - Return true if the specified
3973 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3974 /// suitable for input to VEXTRACTF128.
3975 bool X86::isVEXTRACTF128Index(SDNode *N) {
3976   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3977     return false;
3978
3979   // The index should be aligned on a 128-bit boundary.
3980   uint64_t Index =
3981     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3982
3983   unsigned VL = N->getValueType(0).getVectorNumElements();
3984   unsigned VBits = N->getValueType(0).getSizeInBits();
3985   unsigned ElSize = VBits / VL;
3986   bool Result = (Index * ElSize) % 128 == 0;
3987
3988   return Result;
3989 }
3990
3991 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3992 /// operand specifies a subvector insert that is suitable for input to
3993 /// VINSERTF128.
3994 bool X86::isVINSERTF128Index(SDNode *N) {
3995   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3996     return false;
3997
3998   // The index should be aligned on a 128-bit boundary.
3999   uint64_t Index =
4000     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4001
4002   unsigned VL = N->getValueType(0).getVectorNumElements();
4003   unsigned VBits = N->getValueType(0).getSizeInBits();
4004   unsigned ElSize = VBits / VL;
4005   bool Result = (Index * ElSize) % 128 == 0;
4006
4007   return Result;
4008 }
4009
4010 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4011 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4012 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4013   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4014   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4015
4016   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4017   unsigned Mask = 0;
4018   for (int i = 0; i < NumOperands; ++i) {
4019     int Val = SVOp->getMaskElt(NumOperands-i-1);
4020     if (Val < 0) Val = 0;
4021     if (Val >= NumOperands) Val -= NumOperands;
4022     Mask |= Val;
4023     if (i != NumOperands - 1)
4024       Mask <<= Shift;
4025   }
4026   return Mask;
4027 }
4028
4029 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4030 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4031 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4032   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4033   unsigned Mask = 0;
4034   // 8 nodes, but we only care about the last 4.
4035   for (unsigned i = 7; i >= 4; --i) {
4036     int Val = SVOp->getMaskElt(i);
4037     if (Val >= 0)
4038       Mask |= (Val - 4);
4039     if (i != 4)
4040       Mask <<= 2;
4041   }
4042   return Mask;
4043 }
4044
4045 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4046 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4047 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4048   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4049   unsigned Mask = 0;
4050   // 8 nodes, but we only care about the first 4.
4051   for (int i = 3; i >= 0; --i) {
4052     int Val = SVOp->getMaskElt(i);
4053     if (Val >= 0)
4054       Mask |= Val;
4055     if (i != 0)
4056       Mask <<= 2;
4057   }
4058   return Mask;
4059 }
4060
4061 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4062 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4063 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4064   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4065   EVT VVT = N->getValueType(0);
4066   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4067   int Val = 0;
4068
4069   unsigned i, e;
4070   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4071     Val = SVOp->getMaskElt(i);
4072     if (Val >= 0)
4073       break;
4074   }
4075   assert(Val - i > 0 && "PALIGNR imm should be positive");
4076   return (Val - i) * EltSize;
4077 }
4078
4079 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4080 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4081 /// instructions.
4082 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4083   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4084     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4085
4086   uint64_t Index =
4087     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4088
4089   EVT VecVT = N->getOperand(0).getValueType();
4090   EVT ElVT = VecVT.getVectorElementType();
4091
4092   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4093   return Index / NumElemsPerChunk;
4094 }
4095
4096 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4097 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4098 /// instructions.
4099 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4100   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4102
4103   uint64_t Index =
4104     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106   EVT VecVT = N->getValueType(0);
4107   EVT ElVT = VecVT.getVectorElementType();
4108
4109   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4110   return Index / NumElemsPerChunk;
4111 }
4112
4113 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4114 /// constant +0.0.
4115 bool X86::isZeroNode(SDValue Elt) {
4116   return ((isa<ConstantSDNode>(Elt) &&
4117            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4118           (isa<ConstantFPSDNode>(Elt) &&
4119            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4120 }
4121
4122 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4123 /// their permute mask.
4124 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4125                                     SelectionDAG &DAG) {
4126   EVT VT = SVOp->getValueType(0);
4127   unsigned NumElems = VT.getVectorNumElements();
4128   SmallVector<int, 8> MaskVec;
4129
4130   for (unsigned i = 0; i != NumElems; ++i) {
4131     int idx = SVOp->getMaskElt(i);
4132     if (idx < 0)
4133       MaskVec.push_back(idx);
4134     else if (idx < (int)NumElems)
4135       MaskVec.push_back(idx + NumElems);
4136     else
4137       MaskVec.push_back(idx - NumElems);
4138   }
4139   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4140                               SVOp->getOperand(0), &MaskVec[0]);
4141 }
4142
4143 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4144 /// the two vector operands have swapped position.
4145 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4146   unsigned NumElems = VT.getVectorNumElements();
4147   for (unsigned i = 0; i != NumElems; ++i) {
4148     int idx = Mask[i];
4149     if (idx < 0)
4150       continue;
4151     else if (idx < (int)NumElems)
4152       Mask[i] = idx + NumElems;
4153     else
4154       Mask[i] = idx - NumElems;
4155   }
4156 }
4157
4158 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4159 /// match movhlps. The lower half elements should come from upper half of
4160 /// V1 (and in order), and the upper half elements should come from the upper
4161 /// half of V2 (and in order).
4162 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4163   EVT VT = Op->getValueType(0);
4164   if (VT.getSizeInBits() != 128)
4165     return false;
4166   if (VT.getVectorNumElements() != 4)
4167     return false;
4168   for (unsigned i = 0, e = 2; i != e; ++i)
4169     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4170       return false;
4171   for (unsigned i = 2; i != 4; ++i)
4172     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4173       return false;
4174   return true;
4175 }
4176
4177 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4178 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4179 /// required.
4180 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4181   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4182     return false;
4183   N = N->getOperand(0).getNode();
4184   if (!ISD::isNON_EXTLoad(N))
4185     return false;
4186   if (LD)
4187     *LD = cast<LoadSDNode>(N);
4188   return true;
4189 }
4190
4191 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4192 /// match movlp{s|d}. The lower half elements should come from lower half of
4193 /// V1 (and in order), and the upper half elements should come from the upper
4194 /// half of V2 (and in order). And since V1 will become the source of the
4195 /// MOVLP, it must be either a vector load or a scalar load to vector.
4196 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4197                                ShuffleVectorSDNode *Op) {
4198   EVT VT = Op->getValueType(0);
4199   if (VT.getSizeInBits() != 128)
4200     return false;
4201
4202   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4203     return false;
4204   // Is V2 is a vector load, don't do this transformation. We will try to use
4205   // load folding shufps op.
4206   if (ISD::isNON_EXTLoad(V2))
4207     return false;
4208
4209   unsigned NumElems = VT.getVectorNumElements();
4210
4211   if (NumElems != 2 && NumElems != 4)
4212     return false;
4213   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4214     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4215       return false;
4216   for (unsigned i = NumElems/2; i != NumElems; ++i)
4217     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4218       return false;
4219   return true;
4220 }
4221
4222 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4223 /// all the same.
4224 static bool isSplatVector(SDNode *N) {
4225   if (N->getOpcode() != ISD::BUILD_VECTOR)
4226     return false;
4227
4228   SDValue SplatValue = N->getOperand(0);
4229   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4230     if (N->getOperand(i) != SplatValue)
4231       return false;
4232   return true;
4233 }
4234
4235 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4236 /// to an zero vector.
4237 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4238 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4239   SDValue V1 = N->getOperand(0);
4240   SDValue V2 = N->getOperand(1);
4241   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4242   for (unsigned i = 0; i != NumElems; ++i) {
4243     int Idx = N->getMaskElt(i);
4244     if (Idx >= (int)NumElems) {
4245       unsigned Opc = V2.getOpcode();
4246       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4247         continue;
4248       if (Opc != ISD::BUILD_VECTOR ||
4249           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4250         return false;
4251     } else if (Idx >= 0) {
4252       unsigned Opc = V1.getOpcode();
4253       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4254         continue;
4255       if (Opc != ISD::BUILD_VECTOR ||
4256           !X86::isZeroNode(V1.getOperand(Idx)))
4257         return false;
4258     }
4259   }
4260   return true;
4261 }
4262
4263 /// getZeroVector - Returns a vector of specified type with all zero elements.
4264 ///
4265 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4266                              DebugLoc dl) {
4267   assert(VT.isVector() && "Expected a vector type");
4268
4269   // Always build SSE zero vectors as <4 x i32> bitcasted
4270   // to their dest type. This ensures they get CSE'd.
4271   SDValue Vec;
4272   if (VT.getSizeInBits() == 128) {  // SSE
4273     if (HasSSE2) {  // SSE2
4274       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4275       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4276     } else { // SSE1
4277       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4278       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4279     }
4280   } else if (VT.getSizeInBits() == 256) { // AVX
4281     // 256-bit logic and arithmetic instructions in AVX are
4282     // all floating-point, no support for integer ops. Default
4283     // to emitting fp zeroed vectors then.
4284     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4285     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4286     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4287   }
4288   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4289 }
4290
4291 /// getOnesVector - Returns a vector of specified type with all bits set.
4292 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4293 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4294 /// original type, ensuring they get CSE'd.
4295 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4296   assert(VT.isVector() && "Expected a vector type");
4297   assert((VT.is128BitVector() || VT.is256BitVector())
4298          && "Expected a 128-bit or 256-bit vector type");
4299
4300   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4301   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4302                             Cst, Cst, Cst, Cst);
4303
4304   if (VT.is256BitVector()) {
4305     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4306                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4307     Vec = Insert128BitVector(InsV, Vec,
4308                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4309   }
4310
4311   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4312 }
4313
4314 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4315 /// that point to V2 points to its first element.
4316 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4317   EVT VT = SVOp->getValueType(0);
4318   unsigned NumElems = VT.getVectorNumElements();
4319
4320   bool Changed = false;
4321   SmallVector<int, 8> MaskVec;
4322   SVOp->getMask(MaskVec);
4323
4324   for (unsigned i = 0; i != NumElems; ++i) {
4325     if (MaskVec[i] > (int)NumElems) {
4326       MaskVec[i] = NumElems;
4327       Changed = true;
4328     }
4329   }
4330   if (Changed)
4331     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4332                                 SVOp->getOperand(1), &MaskVec[0]);
4333   return SDValue(SVOp, 0);
4334 }
4335
4336 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4337 /// operation of specified width.
4338 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4339                        SDValue V2) {
4340   unsigned NumElems = VT.getVectorNumElements();
4341   SmallVector<int, 8> Mask;
4342   Mask.push_back(NumElems);
4343   for (unsigned i = 1; i != NumElems; ++i)
4344     Mask.push_back(i);
4345   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4346 }
4347
4348 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4349 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4350                           SDValue V2) {
4351   unsigned NumElems = VT.getVectorNumElements();
4352   SmallVector<int, 8> Mask;
4353   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4354     Mask.push_back(i);
4355     Mask.push_back(i + NumElems);
4356   }
4357   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4358 }
4359
4360 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4361 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4362                           SDValue V2) {
4363   unsigned NumElems = VT.getVectorNumElements();
4364   unsigned Half = NumElems/2;
4365   SmallVector<int, 8> Mask;
4366   for (unsigned i = 0; i != Half; ++i) {
4367     Mask.push_back(i + Half);
4368     Mask.push_back(i + NumElems + Half);
4369   }
4370   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4371 }
4372
4373 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4374 // a generic shuffle instruction because the target has no such instructions.
4375 // Generate shuffles which repeat i16 and i8 several times until they can be
4376 // represented by v4f32 and then be manipulated by target suported shuffles.
4377 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4378   EVT VT = V.getValueType();
4379   int NumElems = VT.getVectorNumElements();
4380   DebugLoc dl = V.getDebugLoc();
4381
4382   while (NumElems > 4) {
4383     if (EltNo < NumElems/2) {
4384       V = getUnpackl(DAG, dl, VT, V, V);
4385     } else {
4386       V = getUnpackh(DAG, dl, VT, V, V);
4387       EltNo -= NumElems/2;
4388     }
4389     NumElems >>= 1;
4390   }
4391   return V;
4392 }
4393
4394 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4395 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4396   EVT VT = V.getValueType();
4397   DebugLoc dl = V.getDebugLoc();
4398   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4399          && "Vector size not supported");
4400
4401   if (VT.getSizeInBits() == 128) {
4402     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4403     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4404     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4405                              &SplatMask[0]);
4406   } else {
4407     // To use VPERMILPS to splat scalars, the second half of indicies must
4408     // refer to the higher part, which is a duplication of the lower one,
4409     // because VPERMILPS can only handle in-lane permutations.
4410     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4411                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4412
4413     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4414     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4415                              &SplatMask[0]);
4416   }
4417
4418   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4419 }
4420
4421 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4422 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4423   EVT SrcVT = SV->getValueType(0);
4424   SDValue V1 = SV->getOperand(0);
4425   DebugLoc dl = SV->getDebugLoc();
4426
4427   int EltNo = SV->getSplatIndex();
4428   int NumElems = SrcVT.getVectorNumElements();
4429   unsigned Size = SrcVT.getSizeInBits();
4430
4431   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4432           "Unknown how to promote splat for type");
4433
4434   // Extract the 128-bit part containing the splat element and update
4435   // the splat element index when it refers to the higher register.
4436   if (Size == 256) {
4437     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4438     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4439     if (Idx > 0)
4440       EltNo -= NumElems/2;
4441   }
4442
4443   // All i16 and i8 vector types can't be used directly by a generic shuffle
4444   // instruction because the target has no such instruction. Generate shuffles
4445   // which repeat i16 and i8 several times until they fit in i32, and then can
4446   // be manipulated by target suported shuffles.
4447   EVT EltVT = SrcVT.getVectorElementType();
4448   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4449     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4450
4451   // Recreate the 256-bit vector and place the same 128-bit vector
4452   // into the low and high part. This is necessary because we want
4453   // to use VPERM* to shuffle the vectors
4454   if (Size == 256) {
4455     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4456                          DAG.getConstant(0, MVT::i32), DAG, dl);
4457     V1 = Insert128BitVector(InsV, V1,
4458                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4459   }
4460
4461   return getLegalSplat(DAG, V1, EltNo);
4462 }
4463
4464 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4465 /// vector of zero or undef vector.  This produces a shuffle where the low
4466 /// element of V2 is swizzled into the zero/undef vector, landing at element
4467 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4468 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4469                                              bool isZero, bool HasSSE2,
4470                                              SelectionDAG &DAG) {
4471   EVT VT = V2.getValueType();
4472   SDValue V1 = isZero
4473     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 16> MaskVec;
4476   for (unsigned i = 0; i != NumElems; ++i)
4477     // If this is the insertion idx, put the low elt of V2 here.
4478     MaskVec.push_back(i == Idx ? NumElems : i);
4479   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4480 }
4481
4482 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4483 /// element of the result of the vector shuffle.
4484 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4485                                    unsigned Depth) {
4486   if (Depth == 6)
4487     return SDValue();  // Limit search depth.
4488
4489   SDValue V = SDValue(N, 0);
4490   EVT VT = V.getValueType();
4491   unsigned Opcode = V.getOpcode();
4492
4493   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4494   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4495     Index = SV->getMaskElt(Index);
4496
4497     if (Index < 0)
4498       return DAG.getUNDEF(VT.getVectorElementType());
4499
4500     int NumElems = VT.getVectorNumElements();
4501     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4502     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4503   }
4504
4505   // Recurse into target specific vector shuffles to find scalars.
4506   if (isTargetShuffle(Opcode)) {
4507     int NumElems = VT.getVectorNumElements();
4508     SmallVector<unsigned, 16> ShuffleMask;
4509     SDValue ImmN;
4510
4511     switch(Opcode) {
4512     case X86ISD::SHUFPS:
4513     case X86ISD::SHUFPD:
4514       ImmN = N->getOperand(N->getNumOperands()-1);
4515       DecodeSHUFPSMask(NumElems,
4516                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4517                        ShuffleMask);
4518       break;
4519     case X86ISD::PUNPCKHBW:
4520     case X86ISD::PUNPCKHWD:
4521     case X86ISD::PUNPCKHDQ:
4522     case X86ISD::PUNPCKHQDQ:
4523       DecodePUNPCKHMask(NumElems, ShuffleMask);
4524       break;
4525     case X86ISD::UNPCKHPS:
4526     case X86ISD::UNPCKHPD:
4527     case X86ISD::VUNPCKHPSY:
4528     case X86ISD::VUNPCKHPDY:
4529       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4530       break;
4531     case X86ISD::PUNPCKLBW:
4532     case X86ISD::PUNPCKLWD:
4533     case X86ISD::PUNPCKLDQ:
4534     case X86ISD::PUNPCKLQDQ:
4535       DecodePUNPCKLMask(VT, ShuffleMask);
4536       break;
4537     case X86ISD::UNPCKLPS:
4538     case X86ISD::UNPCKLPD:
4539     case X86ISD::VUNPCKLPSY:
4540     case X86ISD::VUNPCKLPDY:
4541       DecodeUNPCKLPMask(VT, ShuffleMask);
4542       break;
4543     case X86ISD::MOVHLPS:
4544       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4545       break;
4546     case X86ISD::MOVLHPS:
4547       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4548       break;
4549     case X86ISD::PSHUFD:
4550       ImmN = N->getOperand(N->getNumOperands()-1);
4551       DecodePSHUFMask(NumElems,
4552                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4553                       ShuffleMask);
4554       break;
4555     case X86ISD::PSHUFHW:
4556       ImmN = N->getOperand(N->getNumOperands()-1);
4557       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4558                         ShuffleMask);
4559       break;
4560     case X86ISD::PSHUFLW:
4561       ImmN = N->getOperand(N->getNumOperands()-1);
4562       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4563                         ShuffleMask);
4564       break;
4565     case X86ISD::MOVSS:
4566     case X86ISD::MOVSD: {
4567       // The index 0 always comes from the first element of the second source,
4568       // this is why MOVSS and MOVSD are used in the first place. The other
4569       // elements come from the other positions of the first source vector.
4570       unsigned OpNum = (Index == 0) ? 1 : 0;
4571       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4572                                  Depth+1);
4573     }
4574     case X86ISD::VPERMILPS:
4575       ImmN = N->getOperand(N->getNumOperands()-1);
4576       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4577                         ShuffleMask);
4578       break;
4579     case X86ISD::VPERMILPSY:
4580       ImmN = N->getOperand(N->getNumOperands()-1);
4581       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4582                         ShuffleMask);
4583       break;
4584     case X86ISD::VPERMILPD:
4585       ImmN = N->getOperand(N->getNumOperands()-1);
4586       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4587                         ShuffleMask);
4588       break;
4589     case X86ISD::VPERMILPDY:
4590       ImmN = N->getOperand(N->getNumOperands()-1);
4591       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4592                         ShuffleMask);
4593       break;
4594     case X86ISD::VPERM2F128:
4595       ImmN = N->getOperand(N->getNumOperands()-1);
4596       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4597                            ShuffleMask);
4598       break;
4599     default:
4600       assert("not implemented for target shuffle node");
4601       return SDValue();
4602     }
4603
4604     Index = ShuffleMask[Index];
4605     if (Index < 0)
4606       return DAG.getUNDEF(VT.getVectorElementType());
4607
4608     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4609     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4610                                Depth+1);
4611   }
4612
4613   // Actual nodes that may contain scalar elements
4614   if (Opcode == ISD::BITCAST) {
4615     V = V.getOperand(0);
4616     EVT SrcVT = V.getValueType();
4617     unsigned NumElems = VT.getVectorNumElements();
4618
4619     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4620       return SDValue();
4621   }
4622
4623   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4624     return (Index == 0) ? V.getOperand(0)
4625                           : DAG.getUNDEF(VT.getVectorElementType());
4626
4627   if (V.getOpcode() == ISD::BUILD_VECTOR)
4628     return V.getOperand(Index);
4629
4630   return SDValue();
4631 }
4632
4633 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4634 /// shuffle operation which come from a consecutively from a zero. The
4635 /// search can start in two different directions, from left or right.
4636 static
4637 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4638                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4639   int i = 0;
4640
4641   while (i < NumElems) {
4642     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4643     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4644     if (!(Elt.getNode() &&
4645          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4646       break;
4647     ++i;
4648   }
4649
4650   return i;
4651 }
4652
4653 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4654 /// MaskE correspond consecutively to elements from one of the vector operands,
4655 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4656 static
4657 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4658                               int OpIdx, int NumElems, unsigned &OpNum) {
4659   bool SeenV1 = false;
4660   bool SeenV2 = false;
4661
4662   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4663     int Idx = SVOp->getMaskElt(i);
4664     // Ignore undef indicies
4665     if (Idx < 0)
4666       continue;
4667
4668     if (Idx < NumElems)
4669       SeenV1 = true;
4670     else
4671       SeenV2 = true;
4672
4673     // Only accept consecutive elements from the same vector
4674     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4675       return false;
4676   }
4677
4678   OpNum = SeenV1 ? 0 : 1;
4679   return true;
4680 }
4681
4682 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4683 /// logical left shift of a vector.
4684 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4685                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4686   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4687   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4688               false /* check zeros from right */, DAG);
4689   unsigned OpSrc;
4690
4691   if (!NumZeros)
4692     return false;
4693
4694   // Considering the elements in the mask that are not consecutive zeros,
4695   // check if they consecutively come from only one of the source vectors.
4696   //
4697   //               V1 = {X, A, B, C}     0
4698   //                         \  \  \    /
4699   //   vector_shuffle V1, V2 <1, 2, 3, X>
4700   //
4701   if (!isShuffleMaskConsecutive(SVOp,
4702             0,                   // Mask Start Index
4703             NumElems-NumZeros-1, // Mask End Index
4704             NumZeros,            // Where to start looking in the src vector
4705             NumElems,            // Number of elements in vector
4706             OpSrc))              // Which source operand ?
4707     return false;
4708
4709   isLeft = false;
4710   ShAmt = NumZeros;
4711   ShVal = SVOp->getOperand(OpSrc);
4712   return true;
4713 }
4714
4715 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4716 /// logical left shift of a vector.
4717 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4718                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4719   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4720   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4721               true /* check zeros from left */, DAG);
4722   unsigned OpSrc;
4723
4724   if (!NumZeros)
4725     return false;
4726
4727   // Considering the elements in the mask that are not consecutive zeros,
4728   // check if they consecutively come from only one of the source vectors.
4729   //
4730   //                           0    { A, B, X, X } = V2
4731   //                          / \    /  /
4732   //   vector_shuffle V1, V2 <X, X, 4, 5>
4733   //
4734   if (!isShuffleMaskConsecutive(SVOp,
4735             NumZeros,     // Mask Start Index
4736             NumElems-1,   // Mask End Index
4737             0,            // Where to start looking in the src vector
4738             NumElems,     // Number of elements in vector
4739             OpSrc))       // Which source operand ?
4740     return false;
4741
4742   isLeft = true;
4743   ShAmt = NumZeros;
4744   ShVal = SVOp->getOperand(OpSrc);
4745   return true;
4746 }
4747
4748 /// isVectorShift - Returns true if the shuffle can be implemented as a
4749 /// logical left or right shift of a vector.
4750 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4751                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4752   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4753       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4754     return true;
4755
4756   return false;
4757 }
4758
4759 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4760 ///
4761 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4762                                        unsigned NumNonZero, unsigned NumZero,
4763                                        SelectionDAG &DAG,
4764                                        const TargetLowering &TLI) {
4765   if (NumNonZero > 8)
4766     return SDValue();
4767
4768   DebugLoc dl = Op.getDebugLoc();
4769   SDValue V(0, 0);
4770   bool First = true;
4771   for (unsigned i = 0; i < 16; ++i) {
4772     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4773     if (ThisIsNonZero && First) {
4774       if (NumZero)
4775         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4776       else
4777         V = DAG.getUNDEF(MVT::v8i16);
4778       First = false;
4779     }
4780
4781     if ((i & 1) != 0) {
4782       SDValue ThisElt(0, 0), LastElt(0, 0);
4783       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4784       if (LastIsNonZero) {
4785         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4786                               MVT::i16, Op.getOperand(i-1));
4787       }
4788       if (ThisIsNonZero) {
4789         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4790         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4791                               ThisElt, DAG.getConstant(8, MVT::i8));
4792         if (LastIsNonZero)
4793           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4794       } else
4795         ThisElt = LastElt;
4796
4797       if (ThisElt.getNode())
4798         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4799                         DAG.getIntPtrConstant(i/2));
4800     }
4801   }
4802
4803   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4804 }
4805
4806 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4807 ///
4808 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4809                                      unsigned NumNonZero, unsigned NumZero,
4810                                      SelectionDAG &DAG,
4811                                      const TargetLowering &TLI) {
4812   if (NumNonZero > 4)
4813     return SDValue();
4814
4815   DebugLoc dl = Op.getDebugLoc();
4816   SDValue V(0, 0);
4817   bool First = true;
4818   for (unsigned i = 0; i < 8; ++i) {
4819     bool isNonZero = (NonZeros & (1 << i)) != 0;
4820     if (isNonZero) {
4821       if (First) {
4822         if (NumZero)
4823           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4824         else
4825           V = DAG.getUNDEF(MVT::v8i16);
4826         First = false;
4827       }
4828       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4829                       MVT::v8i16, V, Op.getOperand(i),
4830                       DAG.getIntPtrConstant(i));
4831     }
4832   }
4833
4834   return V;
4835 }
4836
4837 /// getVShift - Return a vector logical shift node.
4838 ///
4839 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4840                          unsigned NumBits, SelectionDAG &DAG,
4841                          const TargetLowering &TLI, DebugLoc dl) {
4842   EVT ShVT = MVT::v2i64;
4843   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4844   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4845   return DAG.getNode(ISD::BITCAST, dl, VT,
4846                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4847                              DAG.getConstant(NumBits,
4848                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4849 }
4850
4851 SDValue
4852 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4853                                           SelectionDAG &DAG) const {
4854
4855   // Check if the scalar load can be widened into a vector load. And if
4856   // the address is "base + cst" see if the cst can be "absorbed" into
4857   // the shuffle mask.
4858   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4859     SDValue Ptr = LD->getBasePtr();
4860     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4861       return SDValue();
4862     EVT PVT = LD->getValueType(0);
4863     if (PVT != MVT::i32 && PVT != MVT::f32)
4864       return SDValue();
4865
4866     int FI = -1;
4867     int64_t Offset = 0;
4868     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4869       FI = FINode->getIndex();
4870       Offset = 0;
4871     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4872                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4873       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4874       Offset = Ptr.getConstantOperandVal(1);
4875       Ptr = Ptr.getOperand(0);
4876     } else {
4877       return SDValue();
4878     }
4879
4880     // FIXME: 256-bit vector instructions don't require a strict alignment,
4881     // improve this code to support it better.
4882     unsigned RequiredAlign = VT.getSizeInBits()/8;
4883     SDValue Chain = LD->getChain();
4884     // Make sure the stack object alignment is at least 16 or 32.
4885     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4886     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4887       if (MFI->isFixedObjectIndex(FI)) {
4888         // Can't change the alignment. FIXME: It's possible to compute
4889         // the exact stack offset and reference FI + adjust offset instead.
4890         // If someone *really* cares about this. That's the way to implement it.
4891         return SDValue();
4892       } else {
4893         MFI->setObjectAlignment(FI, RequiredAlign);
4894       }
4895     }
4896
4897     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4898     // Ptr + (Offset & ~15).
4899     if (Offset < 0)
4900       return SDValue();
4901     if ((Offset % RequiredAlign) & 3)
4902       return SDValue();
4903     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4904     if (StartOffset)
4905       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4906                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4907
4908     int EltNo = (Offset - StartOffset) >> 2;
4909     int NumElems = VT.getVectorNumElements();
4910
4911     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4912     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4913     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4914                              LD->getPointerInfo().getWithOffset(StartOffset),
4915                              false, false, 0);
4916
4917     // Canonicalize it to a v4i32 or v8i32 shuffle.
4918     SmallVector<int, 8> Mask;
4919     for (int i = 0; i < NumElems; ++i)
4920       Mask.push_back(EltNo);
4921
4922     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4923     return DAG.getNode(ISD::BITCAST, dl, NVT,
4924                        DAG.getVectorShuffle(CanonVT, dl, V1,
4925                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4926   }
4927
4928   return SDValue();
4929 }
4930
4931 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4932 /// vector of type 'VT', see if the elements can be replaced by a single large
4933 /// load which has the same value as a build_vector whose operands are 'elts'.
4934 ///
4935 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4936 ///
4937 /// FIXME: we'd also like to handle the case where the last elements are zero
4938 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4939 /// There's even a handy isZeroNode for that purpose.
4940 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4941                                         DebugLoc &DL, SelectionDAG &DAG) {
4942   EVT EltVT = VT.getVectorElementType();
4943   unsigned NumElems = Elts.size();
4944
4945   LoadSDNode *LDBase = NULL;
4946   unsigned LastLoadedElt = -1U;
4947
4948   // For each element in the initializer, see if we've found a load or an undef.
4949   // If we don't find an initial load element, or later load elements are
4950   // non-consecutive, bail out.
4951   for (unsigned i = 0; i < NumElems; ++i) {
4952     SDValue Elt = Elts[i];
4953
4954     if (!Elt.getNode() ||
4955         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4956       return SDValue();
4957     if (!LDBase) {
4958       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4959         return SDValue();
4960       LDBase = cast<LoadSDNode>(Elt.getNode());
4961       LastLoadedElt = i;
4962       continue;
4963     }
4964     if (Elt.getOpcode() == ISD::UNDEF)
4965       continue;
4966
4967     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4968     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4969       return SDValue();
4970     LastLoadedElt = i;
4971   }
4972
4973   // If we have found an entire vector of loads and undefs, then return a large
4974   // load of the entire vector width starting at the base pointer.  If we found
4975   // consecutive loads for the low half, generate a vzext_load node.
4976   if (LastLoadedElt == NumElems - 1) {
4977     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4978       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4979                          LDBase->getPointerInfo(),
4980                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4981     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4982                        LDBase->getPointerInfo(),
4983                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4984                        LDBase->getAlignment());
4985   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4986              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4987     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4988     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4989     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4990                                               Ops, 2, MVT::i32,
4991                                               LDBase->getMemOperand());
4992     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4993   }
4994   return SDValue();
4995 }
4996
4997 SDValue
4998 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4999   DebugLoc dl = Op.getDebugLoc();
5000
5001   EVT VT = Op.getValueType();
5002   EVT ExtVT = VT.getVectorElementType();
5003   unsigned NumElems = Op.getNumOperands();
5004
5005   // Vectors containing all zeros can be matched by pxor and xorps later
5006   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5007     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5008     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5009     if (Op.getValueType() == MVT::v4i32 ||
5010         Op.getValueType() == MVT::v8i32)
5011       return Op;
5012
5013     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
5014   }
5015
5016   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5017   // vectors or broken into v4i32 operations on 256-bit vectors.
5018   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5019     if (Op.getValueType() == MVT::v4i32)
5020       return Op;
5021
5022     return getOnesVector(Op.getValueType(), DAG, dl);
5023   }
5024
5025   unsigned EVTBits = ExtVT.getSizeInBits();
5026
5027   unsigned NumZero  = 0;
5028   unsigned NumNonZero = 0;
5029   unsigned NonZeros = 0;
5030   bool IsAllConstants = true;
5031   SmallSet<SDValue, 8> Values;
5032   for (unsigned i = 0; i < NumElems; ++i) {
5033     SDValue Elt = Op.getOperand(i);
5034     if (Elt.getOpcode() == ISD::UNDEF)
5035       continue;
5036     Values.insert(Elt);
5037     if (Elt.getOpcode() != ISD::Constant &&
5038         Elt.getOpcode() != ISD::ConstantFP)
5039       IsAllConstants = false;
5040     if (X86::isZeroNode(Elt))
5041       NumZero++;
5042     else {
5043       NonZeros |= (1 << i);
5044       NumNonZero++;
5045     }
5046   }
5047
5048   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5049   if (NumNonZero == 0)
5050     return DAG.getUNDEF(VT);
5051
5052   // Special case for single non-zero, non-undef, element.
5053   if (NumNonZero == 1) {
5054     unsigned Idx = CountTrailingZeros_32(NonZeros);
5055     SDValue Item = Op.getOperand(Idx);
5056
5057     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5058     // the value are obviously zero, truncate the value to i32 and do the
5059     // insertion that way.  Only do this if the value is non-constant or if the
5060     // value is a constant being inserted into element 0.  It is cheaper to do
5061     // a constant pool load than it is to do a movd + shuffle.
5062     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5063         (!IsAllConstants || Idx == 0)) {
5064       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5065         // Handle SSE only.
5066         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5067         EVT VecVT = MVT::v4i32;
5068         unsigned VecElts = 4;
5069
5070         // Truncate the value (which may itself be a constant) to i32, and
5071         // convert it to a vector with movd (S2V+shuffle to zero extend).
5072         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5073         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5074         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5075                                            Subtarget->hasSSE2(), DAG);
5076
5077         // Now we have our 32-bit value zero extended in the low element of
5078         // a vector.  If Idx != 0, swizzle it into place.
5079         if (Idx != 0) {
5080           SmallVector<int, 4> Mask;
5081           Mask.push_back(Idx);
5082           for (unsigned i = 1; i != VecElts; ++i)
5083             Mask.push_back(i);
5084           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5085                                       DAG.getUNDEF(Item.getValueType()),
5086                                       &Mask[0]);
5087         }
5088         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5089       }
5090     }
5091
5092     // If we have a constant or non-constant insertion into the low element of
5093     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5094     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5095     // depending on what the source datatype is.
5096     if (Idx == 0) {
5097       if (NumZero == 0) {
5098         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5099       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5100           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5101         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5102         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5103         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
5104                                            DAG);
5105       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5106         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5107         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5108         EVT MiddleVT = MVT::v4i32;
5109         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5110         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5111                                            Subtarget->hasSSE2(), DAG);
5112         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5113       }
5114     }
5115
5116     // Is it a vector logical left shift?
5117     if (NumElems == 2 && Idx == 1 &&
5118         X86::isZeroNode(Op.getOperand(0)) &&
5119         !X86::isZeroNode(Op.getOperand(1))) {
5120       unsigned NumBits = VT.getSizeInBits();
5121       return getVShift(true, VT,
5122                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5123                                    VT, Op.getOperand(1)),
5124                        NumBits/2, DAG, *this, dl);
5125     }
5126
5127     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5128       return SDValue();
5129
5130     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5131     // is a non-constant being inserted into an element other than the low one,
5132     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5133     // movd/movss) to move this into the low element, then shuffle it into
5134     // place.
5135     if (EVTBits == 32) {
5136       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5137
5138       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5139       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5140                                          Subtarget->hasSSE2(), DAG);
5141       SmallVector<int, 8> MaskVec;
5142       for (unsigned i = 0; i < NumElems; i++)
5143         MaskVec.push_back(i == Idx ? 0 : 1);
5144       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5145     }
5146   }
5147
5148   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5149   if (Values.size() == 1) {
5150     if (EVTBits == 32) {
5151       // Instead of a shuffle like this:
5152       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5153       // Check if it's possible to issue this instead.
5154       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5155       unsigned Idx = CountTrailingZeros_32(NonZeros);
5156       SDValue Item = Op.getOperand(Idx);
5157       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5158         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5159     }
5160     return SDValue();
5161   }
5162
5163   // A vector full of immediates; various special cases are already
5164   // handled, so this is best done with a single constant-pool load.
5165   if (IsAllConstants)
5166     return SDValue();
5167
5168   // For AVX-length vectors, build the individual 128-bit pieces and use
5169   // shuffles to put them in place.
5170   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5171     SmallVector<SDValue, 32> V;
5172     for (unsigned i = 0; i < NumElems; ++i)
5173       V.push_back(Op.getOperand(i));
5174
5175     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5176
5177     // Build both the lower and upper subvector.
5178     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5179     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5180                                 NumElems/2);
5181
5182     // Recreate the wider vector with the lower and upper part.
5183     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5184                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5185     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5186                               DAG, dl);
5187   }
5188
5189   // Let legalizer expand 2-wide build_vectors.
5190   if (EVTBits == 64) {
5191     if (NumNonZero == 1) {
5192       // One half is zero or undef.
5193       unsigned Idx = CountTrailingZeros_32(NonZeros);
5194       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5195                                  Op.getOperand(Idx));
5196       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5197                                          Subtarget->hasSSE2(), DAG);
5198     }
5199     return SDValue();
5200   }
5201
5202   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5203   if (EVTBits == 8 && NumElems == 16) {
5204     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5205                                         *this);
5206     if (V.getNode()) return V;
5207   }
5208
5209   if (EVTBits == 16 && NumElems == 8) {
5210     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5211                                       *this);
5212     if (V.getNode()) return V;
5213   }
5214
5215   // If element VT is == 32 bits, turn it into a number of shuffles.
5216   SmallVector<SDValue, 8> V;
5217   V.resize(NumElems);
5218   if (NumElems == 4 && NumZero > 0) {
5219     for (unsigned i = 0; i < 4; ++i) {
5220       bool isZero = !(NonZeros & (1 << i));
5221       if (isZero)
5222         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5223       else
5224         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5225     }
5226
5227     for (unsigned i = 0; i < 2; ++i) {
5228       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5229         default: break;
5230         case 0:
5231           V[i] = V[i*2];  // Must be a zero vector.
5232           break;
5233         case 1:
5234           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5235           break;
5236         case 2:
5237           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5238           break;
5239         case 3:
5240           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5241           break;
5242       }
5243     }
5244
5245     SmallVector<int, 8> MaskVec;
5246     bool Reverse = (NonZeros & 0x3) == 2;
5247     for (unsigned i = 0; i < 2; ++i)
5248       MaskVec.push_back(Reverse ? 1-i : i);
5249     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5250     for (unsigned i = 0; i < 2; ++i)
5251       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5252     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5253   }
5254
5255   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5256     // Check for a build vector of consecutive loads.
5257     for (unsigned i = 0; i < NumElems; ++i)
5258       V[i] = Op.getOperand(i);
5259
5260     // Check for elements which are consecutive loads.
5261     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5262     if (LD.getNode())
5263       return LD;
5264
5265     // For SSE 4.1, use insertps to put the high elements into the low element.
5266     if (getSubtarget()->hasSSE41()) {
5267       SDValue Result;
5268       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5269         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5270       else
5271         Result = DAG.getUNDEF(VT);
5272
5273       for (unsigned i = 1; i < NumElems; ++i) {
5274         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5275         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5276                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5277       }
5278       return Result;
5279     }
5280
5281     // Otherwise, expand into a number of unpckl*, start by extending each of
5282     // our (non-undef) elements to the full vector width with the element in the
5283     // bottom slot of the vector (which generates no code for SSE).
5284     for (unsigned i = 0; i < NumElems; ++i) {
5285       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5286         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5287       else
5288         V[i] = DAG.getUNDEF(VT);
5289     }
5290
5291     // Next, we iteratively mix elements, e.g. for v4f32:
5292     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5293     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5294     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5295     unsigned EltStride = NumElems >> 1;
5296     while (EltStride != 0) {
5297       for (unsigned i = 0; i < EltStride; ++i) {
5298         // If V[i+EltStride] is undef and this is the first round of mixing,
5299         // then it is safe to just drop this shuffle: V[i] is already in the
5300         // right place, the one element (since it's the first round) being
5301         // inserted as undef can be dropped.  This isn't safe for successive
5302         // rounds because they will permute elements within both vectors.
5303         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5304             EltStride == NumElems/2)
5305           continue;
5306
5307         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5308       }
5309       EltStride >>= 1;
5310     }
5311     return V[0];
5312   }
5313   return SDValue();
5314 }
5315
5316 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5317 // them in a MMX register.  This is better than doing a stack convert.
5318 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5319   DebugLoc dl = Op.getDebugLoc();
5320   EVT ResVT = Op.getValueType();
5321
5322   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5323          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5324   int Mask[2];
5325   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5326   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5327   InVec = Op.getOperand(1);
5328   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5329     unsigned NumElts = ResVT.getVectorNumElements();
5330     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5331     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5332                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5333   } else {
5334     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5335     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5336     Mask[0] = 0; Mask[1] = 2;
5337     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5338   }
5339   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5340 }
5341
5342 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5343 // to create 256-bit vectors from two other 128-bit ones.
5344 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5345   DebugLoc dl = Op.getDebugLoc();
5346   EVT ResVT = Op.getValueType();
5347
5348   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5349
5350   SDValue V1 = Op.getOperand(0);
5351   SDValue V2 = Op.getOperand(1);
5352   unsigned NumElems = ResVT.getVectorNumElements();
5353
5354   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5355                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5356   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5357                             DAG, dl);
5358 }
5359
5360 SDValue
5361 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5362   EVT ResVT = Op.getValueType();
5363
5364   assert(Op.getNumOperands() == 2);
5365   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5366          "Unsupported CONCAT_VECTORS for value type");
5367
5368   // We support concatenate two MMX registers and place them in a MMX register.
5369   // This is better than doing a stack convert.
5370   if (ResVT.is128BitVector())
5371     return LowerMMXCONCAT_VECTORS(Op, DAG);
5372
5373   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5374   // from two other 128-bit ones.
5375   return LowerAVXCONCAT_VECTORS(Op, DAG);
5376 }
5377
5378 // v8i16 shuffles - Prefer shuffles in the following order:
5379 // 1. [all]   pshuflw, pshufhw, optional move
5380 // 2. [ssse3] 1 x pshufb
5381 // 3. [ssse3] 2 x pshufb + 1 x por
5382 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5383 SDValue
5384 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5385                                             SelectionDAG &DAG) const {
5386   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5387   SDValue V1 = SVOp->getOperand(0);
5388   SDValue V2 = SVOp->getOperand(1);
5389   DebugLoc dl = SVOp->getDebugLoc();
5390   SmallVector<int, 8> MaskVals;
5391
5392   // Determine if more than 1 of the words in each of the low and high quadwords
5393   // of the result come from the same quadword of one of the two inputs.  Undef
5394   // mask values count as coming from any quadword, for better codegen.
5395   SmallVector<unsigned, 4> LoQuad(4);
5396   SmallVector<unsigned, 4> HiQuad(4);
5397   BitVector InputQuads(4);
5398   for (unsigned i = 0; i < 8; ++i) {
5399     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5400     int EltIdx = SVOp->getMaskElt(i);
5401     MaskVals.push_back(EltIdx);
5402     if (EltIdx < 0) {
5403       ++Quad[0];
5404       ++Quad[1];
5405       ++Quad[2];
5406       ++Quad[3];
5407       continue;
5408     }
5409     ++Quad[EltIdx / 4];
5410     InputQuads.set(EltIdx / 4);
5411   }
5412
5413   int BestLoQuad = -1;
5414   unsigned MaxQuad = 1;
5415   for (unsigned i = 0; i < 4; ++i) {
5416     if (LoQuad[i] > MaxQuad) {
5417       BestLoQuad = i;
5418       MaxQuad = LoQuad[i];
5419     }
5420   }
5421
5422   int BestHiQuad = -1;
5423   MaxQuad = 1;
5424   for (unsigned i = 0; i < 4; ++i) {
5425     if (HiQuad[i] > MaxQuad) {
5426       BestHiQuad = i;
5427       MaxQuad = HiQuad[i];
5428     }
5429   }
5430
5431   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5432   // of the two input vectors, shuffle them into one input vector so only a
5433   // single pshufb instruction is necessary. If There are more than 2 input
5434   // quads, disable the next transformation since it does not help SSSE3.
5435   bool V1Used = InputQuads[0] || InputQuads[1];
5436   bool V2Used = InputQuads[2] || InputQuads[3];
5437   if (Subtarget->hasSSSE3()) {
5438     if (InputQuads.count() == 2 && V1Used && V2Used) {
5439       BestLoQuad = InputQuads.find_first();
5440       BestHiQuad = InputQuads.find_next(BestLoQuad);
5441     }
5442     if (InputQuads.count() > 2) {
5443       BestLoQuad = -1;
5444       BestHiQuad = -1;
5445     }
5446   }
5447
5448   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5449   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5450   // words from all 4 input quadwords.
5451   SDValue NewV;
5452   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5453     SmallVector<int, 8> MaskV;
5454     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5455     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5456     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5457                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5458                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5459     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5460
5461     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5462     // source words for the shuffle, to aid later transformations.
5463     bool AllWordsInNewV = true;
5464     bool InOrder[2] = { true, true };
5465     for (unsigned i = 0; i != 8; ++i) {
5466       int idx = MaskVals[i];
5467       if (idx != (int)i)
5468         InOrder[i/4] = false;
5469       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5470         continue;
5471       AllWordsInNewV = false;
5472       break;
5473     }
5474
5475     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5476     if (AllWordsInNewV) {
5477       for (int i = 0; i != 8; ++i) {
5478         int idx = MaskVals[i];
5479         if (idx < 0)
5480           continue;
5481         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5482         if ((idx != i) && idx < 4)
5483           pshufhw = false;
5484         if ((idx != i) && idx > 3)
5485           pshuflw = false;
5486       }
5487       V1 = NewV;
5488       V2Used = false;
5489       BestLoQuad = 0;
5490       BestHiQuad = 1;
5491     }
5492
5493     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5494     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5495     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5496       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5497       unsigned TargetMask = 0;
5498       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5499                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5500       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5501                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5502       V1 = NewV.getOperand(0);
5503       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5504     }
5505   }
5506
5507   // If we have SSSE3, and all words of the result are from 1 input vector,
5508   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5509   // is present, fall back to case 4.
5510   if (Subtarget->hasSSSE3()) {
5511     SmallVector<SDValue,16> pshufbMask;
5512
5513     // If we have elements from both input vectors, set the high bit of the
5514     // shuffle mask element to zero out elements that come from V2 in the V1
5515     // mask, and elements that come from V1 in the V2 mask, so that the two
5516     // results can be OR'd together.
5517     bool TwoInputs = V1Used && V2Used;
5518     for (unsigned i = 0; i != 8; ++i) {
5519       int EltIdx = MaskVals[i] * 2;
5520       if (TwoInputs && (EltIdx >= 16)) {
5521         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5522         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5523         continue;
5524       }
5525       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5526       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5527     }
5528     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5529     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5530                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5531                                  MVT::v16i8, &pshufbMask[0], 16));
5532     if (!TwoInputs)
5533       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5534
5535     // Calculate the shuffle mask for the second input, shuffle it, and
5536     // OR it with the first shuffled input.
5537     pshufbMask.clear();
5538     for (unsigned i = 0; i != 8; ++i) {
5539       int EltIdx = MaskVals[i] * 2;
5540       if (EltIdx < 16) {
5541         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5542         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5543         continue;
5544       }
5545       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5546       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5547     }
5548     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5549     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5550                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5551                                  MVT::v16i8, &pshufbMask[0], 16));
5552     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5553     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5554   }
5555
5556   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5557   // and update MaskVals with new element order.
5558   BitVector InOrder(8);
5559   if (BestLoQuad >= 0) {
5560     SmallVector<int, 8> MaskV;
5561     for (int i = 0; i != 4; ++i) {
5562       int idx = MaskVals[i];
5563       if (idx < 0) {
5564         MaskV.push_back(-1);
5565         InOrder.set(i);
5566       } else if ((idx / 4) == BestLoQuad) {
5567         MaskV.push_back(idx & 3);
5568         InOrder.set(i);
5569       } else {
5570         MaskV.push_back(-1);
5571       }
5572     }
5573     for (unsigned i = 4; i != 8; ++i)
5574       MaskV.push_back(i);
5575     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5576                                 &MaskV[0]);
5577
5578     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5579       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5580                                NewV.getOperand(0),
5581                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5582                                DAG);
5583   }
5584
5585   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5586   // and update MaskVals with the new element order.
5587   if (BestHiQuad >= 0) {
5588     SmallVector<int, 8> MaskV;
5589     for (unsigned i = 0; i != 4; ++i)
5590       MaskV.push_back(i);
5591     for (unsigned i = 4; i != 8; ++i) {
5592       int idx = MaskVals[i];
5593       if (idx < 0) {
5594         MaskV.push_back(-1);
5595         InOrder.set(i);
5596       } else if ((idx / 4) == BestHiQuad) {
5597         MaskV.push_back((idx & 3) + 4);
5598         InOrder.set(i);
5599       } else {
5600         MaskV.push_back(-1);
5601       }
5602     }
5603     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5604                                 &MaskV[0]);
5605
5606     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5607       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5608                               NewV.getOperand(0),
5609                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5610                               DAG);
5611   }
5612
5613   // In case BestHi & BestLo were both -1, which means each quadword has a word
5614   // from each of the four input quadwords, calculate the InOrder bitvector now
5615   // before falling through to the insert/extract cleanup.
5616   if (BestLoQuad == -1 && BestHiQuad == -1) {
5617     NewV = V1;
5618     for (int i = 0; i != 8; ++i)
5619       if (MaskVals[i] < 0 || MaskVals[i] == i)
5620         InOrder.set(i);
5621   }
5622
5623   // The other elements are put in the right place using pextrw and pinsrw.
5624   for (unsigned i = 0; i != 8; ++i) {
5625     if (InOrder[i])
5626       continue;
5627     int EltIdx = MaskVals[i];
5628     if (EltIdx < 0)
5629       continue;
5630     SDValue ExtOp = (EltIdx < 8)
5631     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5632                   DAG.getIntPtrConstant(EltIdx))
5633     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5634                   DAG.getIntPtrConstant(EltIdx - 8));
5635     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5636                        DAG.getIntPtrConstant(i));
5637   }
5638   return NewV;
5639 }
5640
5641 // v16i8 shuffles - Prefer shuffles in the following order:
5642 // 1. [ssse3] 1 x pshufb
5643 // 2. [ssse3] 2 x pshufb + 1 x por
5644 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5645 static
5646 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5647                                  SelectionDAG &DAG,
5648                                  const X86TargetLowering &TLI) {
5649   SDValue V1 = SVOp->getOperand(0);
5650   SDValue V2 = SVOp->getOperand(1);
5651   DebugLoc dl = SVOp->getDebugLoc();
5652   SmallVector<int, 16> MaskVals;
5653   SVOp->getMask(MaskVals);
5654
5655   // If we have SSSE3, case 1 is generated when all result bytes come from
5656   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5657   // present, fall back to case 3.
5658   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5659   bool V1Only = true;
5660   bool V2Only = true;
5661   for (unsigned i = 0; i < 16; ++i) {
5662     int EltIdx = MaskVals[i];
5663     if (EltIdx < 0)
5664       continue;
5665     if (EltIdx < 16)
5666       V2Only = false;
5667     else
5668       V1Only = false;
5669   }
5670
5671   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5672   if (TLI.getSubtarget()->hasSSSE3()) {
5673     SmallVector<SDValue,16> pshufbMask;
5674
5675     // If all result elements are from one input vector, then only translate
5676     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5677     //
5678     // Otherwise, we have elements from both input vectors, and must zero out
5679     // elements that come from V2 in the first mask, and V1 in the second mask
5680     // so that we can OR them together.
5681     bool TwoInputs = !(V1Only || V2Only);
5682     for (unsigned i = 0; i != 16; ++i) {
5683       int EltIdx = MaskVals[i];
5684       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5685         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5686         continue;
5687       }
5688       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5689     }
5690     // If all the elements are from V2, assign it to V1 and return after
5691     // building the first pshufb.
5692     if (V2Only)
5693       V1 = V2;
5694     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5695                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5696                                  MVT::v16i8, &pshufbMask[0], 16));
5697     if (!TwoInputs)
5698       return V1;
5699
5700     // Calculate the shuffle mask for the second input, shuffle it, and
5701     // OR it with the first shuffled input.
5702     pshufbMask.clear();
5703     for (unsigned i = 0; i != 16; ++i) {
5704       int EltIdx = MaskVals[i];
5705       if (EltIdx < 16) {
5706         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5707         continue;
5708       }
5709       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5710     }
5711     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5712                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5713                                  MVT::v16i8, &pshufbMask[0], 16));
5714     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5715   }
5716
5717   // No SSSE3 - Calculate in place words and then fix all out of place words
5718   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5719   // the 16 different words that comprise the two doublequadword input vectors.
5720   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5721   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5722   SDValue NewV = V2Only ? V2 : V1;
5723   for (int i = 0; i != 8; ++i) {
5724     int Elt0 = MaskVals[i*2];
5725     int Elt1 = MaskVals[i*2+1];
5726
5727     // This word of the result is all undef, skip it.
5728     if (Elt0 < 0 && Elt1 < 0)
5729       continue;
5730
5731     // This word of the result is already in the correct place, skip it.
5732     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5733       continue;
5734     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5735       continue;
5736
5737     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5738     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5739     SDValue InsElt;
5740
5741     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5742     // using a single extract together, load it and store it.
5743     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5744       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5745                            DAG.getIntPtrConstant(Elt1 / 2));
5746       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5747                         DAG.getIntPtrConstant(i));
5748       continue;
5749     }
5750
5751     // If Elt1 is defined, extract it from the appropriate source.  If the
5752     // source byte is not also odd, shift the extracted word left 8 bits
5753     // otherwise clear the bottom 8 bits if we need to do an or.
5754     if (Elt1 >= 0) {
5755       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5756                            DAG.getIntPtrConstant(Elt1 / 2));
5757       if ((Elt1 & 1) == 0)
5758         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5759                              DAG.getConstant(8,
5760                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5761       else if (Elt0 >= 0)
5762         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5763                              DAG.getConstant(0xFF00, MVT::i16));
5764     }
5765     // If Elt0 is defined, extract it from the appropriate source.  If the
5766     // source byte is not also even, shift the extracted word right 8 bits. If
5767     // Elt1 was also defined, OR the extracted values together before
5768     // inserting them in the result.
5769     if (Elt0 >= 0) {
5770       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5771                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5772       if ((Elt0 & 1) != 0)
5773         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5774                               DAG.getConstant(8,
5775                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5776       else if (Elt1 >= 0)
5777         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5778                              DAG.getConstant(0x00FF, MVT::i16));
5779       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5780                          : InsElt0;
5781     }
5782     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5783                        DAG.getIntPtrConstant(i));
5784   }
5785   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5786 }
5787
5788 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5789 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5790 /// done when every pair / quad of shuffle mask elements point to elements in
5791 /// the right sequence. e.g.
5792 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5793 static
5794 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5795                                  SelectionDAG &DAG, DebugLoc dl) {
5796   EVT VT = SVOp->getValueType(0);
5797   SDValue V1 = SVOp->getOperand(0);
5798   SDValue V2 = SVOp->getOperand(1);
5799   unsigned NumElems = VT.getVectorNumElements();
5800   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5801   EVT NewVT;
5802   switch (VT.getSimpleVT().SimpleTy) {
5803   default: assert(false && "Unexpected!");
5804   case MVT::v4f32: NewVT = MVT::v2f64; break;
5805   case MVT::v4i32: NewVT = MVT::v2i64; break;
5806   case MVT::v8i16: NewVT = MVT::v4i32; break;
5807   case MVT::v16i8: NewVT = MVT::v4i32; break;
5808   }
5809
5810   int Scale = NumElems / NewWidth;
5811   SmallVector<int, 8> MaskVec;
5812   for (unsigned i = 0; i < NumElems; i += Scale) {
5813     int StartIdx = -1;
5814     for (int j = 0; j < Scale; ++j) {
5815       int EltIdx = SVOp->getMaskElt(i+j);
5816       if (EltIdx < 0)
5817         continue;
5818       if (StartIdx == -1)
5819         StartIdx = EltIdx - (EltIdx % Scale);
5820       if (EltIdx != StartIdx + j)
5821         return SDValue();
5822     }
5823     if (StartIdx == -1)
5824       MaskVec.push_back(-1);
5825     else
5826       MaskVec.push_back(StartIdx / Scale);
5827   }
5828
5829   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5830   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5831   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5832 }
5833
5834 /// getVZextMovL - Return a zero-extending vector move low node.
5835 ///
5836 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5837                             SDValue SrcOp, SelectionDAG &DAG,
5838                             const X86Subtarget *Subtarget, DebugLoc dl) {
5839   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5840     LoadSDNode *LD = NULL;
5841     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5842       LD = dyn_cast<LoadSDNode>(SrcOp);
5843     if (!LD) {
5844       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5845       // instead.
5846       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5847       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5848           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5849           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5850           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5851         // PR2108
5852         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5853         return DAG.getNode(ISD::BITCAST, dl, VT,
5854                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5855                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5856                                                    OpVT,
5857                                                    SrcOp.getOperand(0)
5858                                                           .getOperand(0))));
5859       }
5860     }
5861   }
5862
5863   return DAG.getNode(ISD::BITCAST, dl, VT,
5864                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5865                                  DAG.getNode(ISD::BITCAST, dl,
5866                                              OpVT, SrcOp)));
5867 }
5868
5869 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5870 /// shuffle node referes to only one lane in the sources.
5871 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5872   EVT VT = SVOp->getValueType(0);
5873   int NumElems = VT.getVectorNumElements();
5874   int HalfSize = NumElems/2;
5875   SmallVector<int, 16> M;
5876   SVOp->getMask(M);
5877   bool MatchA = false, MatchB = false;
5878
5879   for (int l = 0; l < NumElems*2; l += HalfSize) {
5880     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5881       MatchA = true;
5882       break;
5883     }
5884   }
5885
5886   for (int l = 0; l < NumElems*2; l += HalfSize) {
5887     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5888       MatchB = true;
5889       break;
5890     }
5891   }
5892
5893   return MatchA && MatchB;
5894 }
5895
5896 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5897 /// which could not be matched by any known target speficic shuffle
5898 static SDValue
5899 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5900   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5901     // If each half of a vector shuffle node referes to only one lane in the
5902     // source vectors, extract each used 128-bit lane and shuffle them using
5903     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5904     // the work to the legalizer.
5905     DebugLoc dl = SVOp->getDebugLoc();
5906     EVT VT = SVOp->getValueType(0);
5907     int NumElems = VT.getVectorNumElements();
5908     int HalfSize = NumElems/2;
5909
5910     // Extract the reference for each half
5911     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5912     int FstVecOpNum = 0, SndVecOpNum = 0;
5913     for (int i = 0; i < HalfSize; ++i) {
5914       int Elt = SVOp->getMaskElt(i);
5915       if (SVOp->getMaskElt(i) < 0)
5916         continue;
5917       FstVecOpNum = Elt/NumElems;
5918       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5919       break;
5920     }
5921     for (int i = HalfSize; i < NumElems; ++i) {
5922       int Elt = SVOp->getMaskElt(i);
5923       if (SVOp->getMaskElt(i) < 0)
5924         continue;
5925       SndVecOpNum = Elt/NumElems;
5926       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5927       break;
5928     }
5929
5930     // Extract the subvectors
5931     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5932                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5933     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5934                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5935
5936     // Generate 128-bit shuffles
5937     SmallVector<int, 16> MaskV1, MaskV2;
5938     for (int i = 0; i < HalfSize; ++i) {
5939       int Elt = SVOp->getMaskElt(i);
5940       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5941     }
5942     for (int i = HalfSize; i < NumElems; ++i) {
5943       int Elt = SVOp->getMaskElt(i);
5944       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5945     }
5946
5947     EVT NVT = V1.getValueType();
5948     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5949     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5950
5951     // Concatenate the result back
5952     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5953                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5954     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5955                               DAG, dl);
5956   }
5957
5958   return SDValue();
5959 }
5960
5961 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5962 /// 4 elements, and match them with several different shuffle types.
5963 static SDValue
5964 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5965   SDValue V1 = SVOp->getOperand(0);
5966   SDValue V2 = SVOp->getOperand(1);
5967   DebugLoc dl = SVOp->getDebugLoc();
5968   EVT VT = SVOp->getValueType(0);
5969
5970   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5971
5972   SmallVector<std::pair<int, int>, 8> Locs;
5973   Locs.resize(4);
5974   SmallVector<int, 8> Mask1(4U, -1);
5975   SmallVector<int, 8> PermMask;
5976   SVOp->getMask(PermMask);
5977
5978   unsigned NumHi = 0;
5979   unsigned NumLo = 0;
5980   for (unsigned i = 0; i != 4; ++i) {
5981     int Idx = PermMask[i];
5982     if (Idx < 0) {
5983       Locs[i] = std::make_pair(-1, -1);
5984     } else {
5985       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5986       if (Idx < 4) {
5987         Locs[i] = std::make_pair(0, NumLo);
5988         Mask1[NumLo] = Idx;
5989         NumLo++;
5990       } else {
5991         Locs[i] = std::make_pair(1, NumHi);
5992         if (2+NumHi < 4)
5993           Mask1[2+NumHi] = Idx;
5994         NumHi++;
5995       }
5996     }
5997   }
5998
5999   if (NumLo <= 2 && NumHi <= 2) {
6000     // If no more than two elements come from either vector. This can be
6001     // implemented with two shuffles. First shuffle gather the elements.
6002     // The second shuffle, which takes the first shuffle as both of its
6003     // vector operands, put the elements into the right order.
6004     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6005
6006     SmallVector<int, 8> Mask2(4U, -1);
6007
6008     for (unsigned i = 0; i != 4; ++i) {
6009       if (Locs[i].first == -1)
6010         continue;
6011       else {
6012         unsigned Idx = (i < 2) ? 0 : 4;
6013         Idx += Locs[i].first * 2 + Locs[i].second;
6014         Mask2[i] = Idx;
6015       }
6016     }
6017
6018     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6019   } else if (NumLo == 3 || NumHi == 3) {
6020     // Otherwise, we must have three elements from one vector, call it X, and
6021     // one element from the other, call it Y.  First, use a shufps to build an
6022     // intermediate vector with the one element from Y and the element from X
6023     // that will be in the same half in the final destination (the indexes don't
6024     // matter). Then, use a shufps to build the final vector, taking the half
6025     // containing the element from Y from the intermediate, and the other half
6026     // from X.
6027     if (NumHi == 3) {
6028       // Normalize it so the 3 elements come from V1.
6029       CommuteVectorShuffleMask(PermMask, VT);
6030       std::swap(V1, V2);
6031     }
6032
6033     // Find the element from V2.
6034     unsigned HiIndex;
6035     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6036       int Val = PermMask[HiIndex];
6037       if (Val < 0)
6038         continue;
6039       if (Val >= 4)
6040         break;
6041     }
6042
6043     Mask1[0] = PermMask[HiIndex];
6044     Mask1[1] = -1;
6045     Mask1[2] = PermMask[HiIndex^1];
6046     Mask1[3] = -1;
6047     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6048
6049     if (HiIndex >= 2) {
6050       Mask1[0] = PermMask[0];
6051       Mask1[1] = PermMask[1];
6052       Mask1[2] = HiIndex & 1 ? 6 : 4;
6053       Mask1[3] = HiIndex & 1 ? 4 : 6;
6054       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6055     } else {
6056       Mask1[0] = HiIndex & 1 ? 2 : 0;
6057       Mask1[1] = HiIndex & 1 ? 0 : 2;
6058       Mask1[2] = PermMask[2];
6059       Mask1[3] = PermMask[3];
6060       if (Mask1[2] >= 0)
6061         Mask1[2] += 4;
6062       if (Mask1[3] >= 0)
6063         Mask1[3] += 4;
6064       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6065     }
6066   }
6067
6068   // Break it into (shuffle shuffle_hi, shuffle_lo).
6069   Locs.clear();
6070   Locs.resize(4);
6071   SmallVector<int,8> LoMask(4U, -1);
6072   SmallVector<int,8> HiMask(4U, -1);
6073
6074   SmallVector<int,8> *MaskPtr = &LoMask;
6075   unsigned MaskIdx = 0;
6076   unsigned LoIdx = 0;
6077   unsigned HiIdx = 2;
6078   for (unsigned i = 0; i != 4; ++i) {
6079     if (i == 2) {
6080       MaskPtr = &HiMask;
6081       MaskIdx = 1;
6082       LoIdx = 0;
6083       HiIdx = 2;
6084     }
6085     int Idx = PermMask[i];
6086     if (Idx < 0) {
6087       Locs[i] = std::make_pair(-1, -1);
6088     } else if (Idx < 4) {
6089       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6090       (*MaskPtr)[LoIdx] = Idx;
6091       LoIdx++;
6092     } else {
6093       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6094       (*MaskPtr)[HiIdx] = Idx;
6095       HiIdx++;
6096     }
6097   }
6098
6099   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6100   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6101   SmallVector<int, 8> MaskOps;
6102   for (unsigned i = 0; i != 4; ++i) {
6103     if (Locs[i].first == -1) {
6104       MaskOps.push_back(-1);
6105     } else {
6106       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6107       MaskOps.push_back(Idx);
6108     }
6109   }
6110   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6111 }
6112
6113 static bool MayFoldVectorLoad(SDValue V) {
6114   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6115     V = V.getOperand(0);
6116   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6117     V = V.getOperand(0);
6118   if (MayFoldLoad(V))
6119     return true;
6120   return false;
6121 }
6122
6123 // FIXME: the version above should always be used. Since there's
6124 // a bug where several vector shuffles can't be folded because the
6125 // DAG is not updated during lowering and a node claims to have two
6126 // uses while it only has one, use this version, and let isel match
6127 // another instruction if the load really happens to have more than
6128 // one use. Remove this version after this bug get fixed.
6129 // rdar://8434668, PR8156
6130 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6131   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6132     V = V.getOperand(0);
6133   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6134     V = V.getOperand(0);
6135   if (ISD::isNormalLoad(V.getNode()))
6136     return true;
6137   return false;
6138 }
6139
6140 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6141 /// a vector extract, and if both can be later optimized into a single load.
6142 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6143 /// here because otherwise a target specific shuffle node is going to be
6144 /// emitted for this shuffle, and the optimization not done.
6145 /// FIXME: This is probably not the best approach, but fix the problem
6146 /// until the right path is decided.
6147 static
6148 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6149                                          const TargetLowering &TLI) {
6150   EVT VT = V.getValueType();
6151   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6152
6153   // Be sure that the vector shuffle is present in a pattern like this:
6154   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6155   if (!V.hasOneUse())
6156     return false;
6157
6158   SDNode *N = *V.getNode()->use_begin();
6159   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6160     return false;
6161
6162   SDValue EltNo = N->getOperand(1);
6163   if (!isa<ConstantSDNode>(EltNo))
6164     return false;
6165
6166   // If the bit convert changed the number of elements, it is unsafe
6167   // to examine the mask.
6168   bool HasShuffleIntoBitcast = false;
6169   if (V.getOpcode() == ISD::BITCAST) {
6170     EVT SrcVT = V.getOperand(0).getValueType();
6171     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6172       return false;
6173     V = V.getOperand(0);
6174     HasShuffleIntoBitcast = true;
6175   }
6176
6177   // Select the input vector, guarding against out of range extract vector.
6178   unsigned NumElems = VT.getVectorNumElements();
6179   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6180   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6181   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6182
6183   // Skip one more bit_convert if necessary
6184   if (V.getOpcode() == ISD::BITCAST)
6185     V = V.getOperand(0);
6186
6187   if (ISD::isNormalLoad(V.getNode())) {
6188     // Is the original load suitable?
6189     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6190
6191     // FIXME: avoid the multi-use bug that is preventing lots of
6192     // of foldings to be detected, this is still wrong of course, but
6193     // give the temporary desired behavior, and if it happens that
6194     // the load has real more uses, during isel it will not fold, and
6195     // will generate poor code.
6196     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6197       return false;
6198
6199     if (!HasShuffleIntoBitcast)
6200       return true;
6201
6202     // If there's a bitcast before the shuffle, check if the load type and
6203     // alignment is valid.
6204     unsigned Align = LN0->getAlignment();
6205     unsigned NewAlign =
6206       TLI.getTargetData()->getABITypeAlignment(
6207                                     VT.getTypeForEVT(*DAG.getContext()));
6208
6209     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6210       return false;
6211   }
6212
6213   return true;
6214 }
6215
6216 static
6217 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6218   EVT VT = Op.getValueType();
6219
6220   // Canonizalize to v2f64.
6221   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6222   return DAG.getNode(ISD::BITCAST, dl, VT,
6223                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6224                                           V1, DAG));
6225 }
6226
6227 static
6228 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6229                         bool HasSSE2) {
6230   SDValue V1 = Op.getOperand(0);
6231   SDValue V2 = Op.getOperand(1);
6232   EVT VT = Op.getValueType();
6233
6234   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6235
6236   if (HasSSE2 && VT == MVT::v2f64)
6237     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6238
6239   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6240   return DAG.getNode(ISD::BITCAST, dl, VT,
6241                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6242                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6243                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6244 }
6245
6246 static
6247 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6248   SDValue V1 = Op.getOperand(0);
6249   SDValue V2 = Op.getOperand(1);
6250   EVT VT = Op.getValueType();
6251
6252   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6253          "unsupported shuffle type");
6254
6255   if (V2.getOpcode() == ISD::UNDEF)
6256     V2 = V1;
6257
6258   // v4i32 or v4f32
6259   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6260 }
6261
6262 static inline unsigned getSHUFPOpcode(EVT VT) {
6263   switch(VT.getSimpleVT().SimpleTy) {
6264   case MVT::v8i32: // Use fp unit for int unpack.
6265   case MVT::v8f32:
6266   case MVT::v4i32: // Use fp unit for int unpack.
6267   case MVT::v4f32: return X86ISD::SHUFPS;
6268   case MVT::v4i64: // Use fp unit for int unpack.
6269   case MVT::v4f64:
6270   case MVT::v2i64: // Use fp unit for int unpack.
6271   case MVT::v2f64: return X86ISD::SHUFPD;
6272   default:
6273     llvm_unreachable("Unknown type for shufp*");
6274   }
6275   return 0;
6276 }
6277
6278 static
6279 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6280   SDValue V1 = Op.getOperand(0);
6281   SDValue V2 = Op.getOperand(1);
6282   EVT VT = Op.getValueType();
6283   unsigned NumElems = VT.getVectorNumElements();
6284
6285   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6286   // operand of these instructions is only memory, so check if there's a
6287   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6288   // same masks.
6289   bool CanFoldLoad = false;
6290
6291   // Trivial case, when V2 comes from a load.
6292   if (MayFoldVectorLoad(V2))
6293     CanFoldLoad = true;
6294
6295   // When V1 is a load, it can be folded later into a store in isel, example:
6296   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6297   //    turns into:
6298   //  (MOVLPSmr addr:$src1, VR128:$src2)
6299   // So, recognize this potential and also use MOVLPS or MOVLPD
6300   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6301     CanFoldLoad = true;
6302
6303   // Both of them can't be memory operations though.
6304   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6305     CanFoldLoad = false;
6306
6307   if (CanFoldLoad) {
6308     if (HasSSE2 && NumElems == 2)
6309       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6310
6311     if (NumElems == 4)
6312       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6313   }
6314
6315   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6316   // movl and movlp will both match v2i64, but v2i64 is never matched by
6317   // movl earlier because we make it strict to avoid messing with the movlp load
6318   // folding logic (see the code above getMOVLP call). Match it here then,
6319   // this is horrible, but will stay like this until we move all shuffle
6320   // matching to x86 specific nodes. Note that for the 1st condition all
6321   // types are matched with movsd.
6322   if (HasSSE2) {
6323     if (NumElems == 2)
6324       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6325     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6326   }
6327
6328   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6329
6330   // Invert the operand order and use SHUFPS to match it.
6331   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6332                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6333 }
6334
6335 static inline unsigned getUNPCKLOpcode(EVT VT) {
6336   switch(VT.getSimpleVT().SimpleTy) {
6337   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6338   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6339   case MVT::v4f32: return X86ISD::UNPCKLPS;
6340   case MVT::v2f64: return X86ISD::UNPCKLPD;
6341   case MVT::v8i32: // Use fp unit for int unpack.
6342   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6343   case MVT::v4i64: // Use fp unit for int unpack.
6344   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6345   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6346   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6347   default:
6348     llvm_unreachable("Unknown type for unpckl");
6349   }
6350   return 0;
6351 }
6352
6353 static inline unsigned getUNPCKHOpcode(EVT VT) {
6354   switch(VT.getSimpleVT().SimpleTy) {
6355   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6356   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6357   case MVT::v4f32: return X86ISD::UNPCKHPS;
6358   case MVT::v2f64: return X86ISD::UNPCKHPD;
6359   case MVT::v8i32: // Use fp unit for int unpack.
6360   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6361   case MVT::v4i64: // Use fp unit for int unpack.
6362   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6363   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6364   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6365   default:
6366     llvm_unreachable("Unknown type for unpckh");
6367   }
6368   return 0;
6369 }
6370
6371 static inline unsigned getVPERMILOpcode(EVT VT) {
6372   switch(VT.getSimpleVT().SimpleTy) {
6373   case MVT::v4i32:
6374   case MVT::v4f32: return X86ISD::VPERMILPS;
6375   case MVT::v2i64:
6376   case MVT::v2f64: return X86ISD::VPERMILPD;
6377   case MVT::v8i32:
6378   case MVT::v8f32: return X86ISD::VPERMILPSY;
6379   case MVT::v4i64:
6380   case MVT::v4f64: return X86ISD::VPERMILPDY;
6381   default:
6382     llvm_unreachable("Unknown type for vpermil");
6383   }
6384   return 0;
6385 }
6386
6387 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6388 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6389 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6390 static bool isVectorBroadcast(SDValue &Op) {
6391   EVT VT = Op.getValueType();
6392   bool Is256 = VT.getSizeInBits() == 256;
6393
6394   assert((VT.getSizeInBits() == 128 || Is256) &&
6395          "Unsupported type for vbroadcast node");
6396
6397   SDValue V = Op;
6398   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6399     V = V.getOperand(0);
6400
6401   if (Is256 && !(V.hasOneUse() &&
6402                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6403                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6404     return false;
6405
6406   if (Is256)
6407     V = V.getOperand(1);
6408   if (V.hasOneUse() && V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6409     return false;
6410
6411   // Check the source scalar_to_vector type. 256-bit broadcasts are
6412   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6413   // for 32-bit scalars.
6414   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6415   if (ScalarSize != 32 && ScalarSize != 64)
6416     return false;
6417   if (!Is256 && ScalarSize == 64)
6418     return false;
6419
6420   V = V.getOperand(0);
6421   if (!MayFoldLoad(V))
6422     return false;
6423
6424   // Return the load node
6425   Op = V;
6426   return true;
6427 }
6428
6429 static
6430 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6431                                const TargetLowering &TLI,
6432                                const X86Subtarget *Subtarget) {
6433   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6434   EVT VT = Op.getValueType();
6435   DebugLoc dl = Op.getDebugLoc();
6436   SDValue V1 = Op.getOperand(0);
6437   SDValue V2 = Op.getOperand(1);
6438
6439   if (isZeroShuffle(SVOp))
6440     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6441
6442   // Handle splat operations
6443   if (SVOp->isSplat()) {
6444     unsigned NumElem = VT.getVectorNumElements();
6445     int Size = VT.getSizeInBits();
6446     // Special case, this is the only place now where it's allowed to return
6447     // a vector_shuffle operation without using a target specific node, because
6448     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6449     // this be moved to DAGCombine instead?
6450     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6451       return Op;
6452
6453     // Use vbroadcast whenever the splat comes from a foldable load
6454     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6455       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6456
6457     // Handle splats by matching through known shuffle masks
6458     if ((Size == 128 && NumElem <= 4) ||
6459         (Size == 256 && NumElem < 8))
6460       return SDValue();
6461
6462     // All remaning splats are promoted to target supported vector shuffles.
6463     return PromoteSplat(SVOp, DAG);
6464   }
6465
6466   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6467   // do it!
6468   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6469     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6470     if (NewOp.getNode())
6471       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6472   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6473     // FIXME: Figure out a cleaner way to do this.
6474     // Try to make use of movq to zero out the top part.
6475     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6476       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6477       if (NewOp.getNode()) {
6478         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6479           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6480                               DAG, Subtarget, dl);
6481       }
6482     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6483       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6484       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6485         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6486                             DAG, Subtarget, dl);
6487     }
6488   }
6489   return SDValue();
6490 }
6491
6492 SDValue
6493 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6494   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6495   SDValue V1 = Op.getOperand(0);
6496   SDValue V2 = Op.getOperand(1);
6497   EVT VT = Op.getValueType();
6498   DebugLoc dl = Op.getDebugLoc();
6499   unsigned NumElems = VT.getVectorNumElements();
6500   bool isMMX = VT.getSizeInBits() == 64;
6501   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6502   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6503   bool V1IsSplat = false;
6504   bool V2IsSplat = false;
6505   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6506   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6507   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6508   MachineFunction &MF = DAG.getMachineFunction();
6509   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6510
6511   // Shuffle operations on MMX not supported.
6512   if (isMMX)
6513     return Op;
6514
6515   // Vector shuffle lowering takes 3 steps:
6516   //
6517   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6518   //    narrowing and commutation of operands should be handled.
6519   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6520   //    shuffle nodes.
6521   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6522   //    so the shuffle can be broken into other shuffles and the legalizer can
6523   //    try the lowering again.
6524   //
6525   // The general ideia is that no vector_shuffle operation should be left to
6526   // be matched during isel, all of them must be converted to a target specific
6527   // node here.
6528
6529   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6530   // narrowing and commutation of operands should be handled. The actual code
6531   // doesn't include all of those, work in progress...
6532   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6533   if (NewOp.getNode())
6534     return NewOp;
6535
6536   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6537   // unpckh_undef). Only use pshufd if speed is more important than size.
6538   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6539     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6540   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6541     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6542
6543   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6544       RelaxedMayFoldVectorLoad(V1))
6545     return getMOVDDup(Op, dl, V1, DAG);
6546
6547   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6548     return getMOVHighToLow(Op, dl, DAG);
6549
6550   // Use to match splats
6551   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6552       (VT == MVT::v2f64 || VT == MVT::v2i64))
6553     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6554
6555   if (X86::isPSHUFDMask(SVOp)) {
6556     // The actual implementation will match the mask in the if above and then
6557     // during isel it can match several different instructions, not only pshufd
6558     // as its name says, sad but true, emulate the behavior for now...
6559     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6560         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6561
6562     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6563
6564     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6565       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6566
6567     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6568                                 TargetMask, DAG);
6569   }
6570
6571   // Check if this can be converted into a logical shift.
6572   bool isLeft = false;
6573   unsigned ShAmt = 0;
6574   SDValue ShVal;
6575   bool isShift = getSubtarget()->hasSSE2() &&
6576     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6577   if (isShift && ShVal.hasOneUse()) {
6578     // If the shifted value has multiple uses, it may be cheaper to use
6579     // v_set0 + movlhps or movhlps, etc.
6580     EVT EltVT = VT.getVectorElementType();
6581     ShAmt *= EltVT.getSizeInBits();
6582     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6583   }
6584
6585   if (X86::isMOVLMask(SVOp)) {
6586     if (V1IsUndef)
6587       return V2;
6588     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6589       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6590     if (!X86::isMOVLPMask(SVOp)) {
6591       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6592         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6593
6594       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6595         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6596     }
6597   }
6598
6599   // FIXME: fold these into legal mask.
6600   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6601     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6602
6603   if (X86::isMOVHLPSMask(SVOp))
6604     return getMOVHighToLow(Op, dl, DAG);
6605
6606   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6607     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6608
6609   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6610     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6611
6612   if (X86::isMOVLPMask(SVOp))
6613     return getMOVLP(Op, dl, DAG, HasSSE2);
6614
6615   if (ShouldXformToMOVHLPS(SVOp) ||
6616       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6617     return CommuteVectorShuffle(SVOp, DAG);
6618
6619   if (isShift) {
6620     // No better options. Use a vshl / vsrl.
6621     EVT EltVT = VT.getVectorElementType();
6622     ShAmt *= EltVT.getSizeInBits();
6623     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6624   }
6625
6626   bool Commuted = false;
6627   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6628   // 1,1,1,1 -> v8i16 though.
6629   V1IsSplat = isSplatVector(V1.getNode());
6630   V2IsSplat = isSplatVector(V2.getNode());
6631
6632   // Canonicalize the splat or undef, if present, to be on the RHS.
6633   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6634     Op = CommuteVectorShuffle(SVOp, DAG);
6635     SVOp = cast<ShuffleVectorSDNode>(Op);
6636     V1 = SVOp->getOperand(0);
6637     V2 = SVOp->getOperand(1);
6638     std::swap(V1IsSplat, V2IsSplat);
6639     std::swap(V1IsUndef, V2IsUndef);
6640     Commuted = true;
6641   }
6642
6643   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6644     // Shuffling low element of v1 into undef, just return v1.
6645     if (V2IsUndef)
6646       return V1;
6647     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6648     // the instruction selector will not match, so get a canonical MOVL with
6649     // swapped operands to undo the commute.
6650     return getMOVL(DAG, dl, VT, V2, V1);
6651   }
6652
6653   if (X86::isUNPCKLMask(SVOp))
6654     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6655
6656   if (X86::isUNPCKHMask(SVOp))
6657     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6658
6659   if (V2IsSplat) {
6660     // Normalize mask so all entries that point to V2 points to its first
6661     // element then try to match unpck{h|l} again. If match, return a
6662     // new vector_shuffle with the corrected mask.
6663     SDValue NewMask = NormalizeMask(SVOp, DAG);
6664     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6665     if (NSVOp != SVOp) {
6666       if (X86::isUNPCKLMask(NSVOp, true)) {
6667         return NewMask;
6668       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6669         return NewMask;
6670       }
6671     }
6672   }
6673
6674   if (Commuted) {
6675     // Commute is back and try unpck* again.
6676     // FIXME: this seems wrong.
6677     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6678     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6679
6680     if (X86::isUNPCKLMask(NewSVOp))
6681       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6682
6683     if (X86::isUNPCKHMask(NewSVOp))
6684       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6685   }
6686
6687   // Normalize the node to match x86 shuffle ops if needed
6688   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6689     return CommuteVectorShuffle(SVOp, DAG);
6690
6691   // The checks below are all present in isShuffleMaskLegal, but they are
6692   // inlined here right now to enable us to directly emit target specific
6693   // nodes, and remove one by one until they don't return Op anymore.
6694   SmallVector<int, 16> M;
6695   SVOp->getMask(M);
6696
6697   if (isPALIGNRMask(M, VT, HasSSSE3))
6698     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6699                                 X86::getShufflePALIGNRImmediate(SVOp),
6700                                 DAG);
6701
6702   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6703       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6704     if (VT == MVT::v2f64)
6705       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6706     if (VT == MVT::v2i64)
6707       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6708   }
6709
6710   if (isPSHUFHWMask(M, VT))
6711     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6712                                 X86::getShufflePSHUFHWImmediate(SVOp),
6713                                 DAG);
6714
6715   if (isPSHUFLWMask(M, VT))
6716     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6717                                 X86::getShufflePSHUFLWImmediate(SVOp),
6718                                 DAG);
6719
6720   if (isSHUFPMask(M, VT))
6721     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6722                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6723
6724   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6725     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6726   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6727     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6728
6729   //===--------------------------------------------------------------------===//
6730   // Generate target specific nodes for 128 or 256-bit shuffles only
6731   // supported in the AVX instruction set.
6732   //
6733
6734   // Handle VMOVDDUPY permutations
6735   if (isMOVDDUPYMask(SVOp, Subtarget))
6736     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6737
6738   // Handle VPERMILPS* permutations
6739   if (isVPERMILPSMask(M, VT, Subtarget))
6740     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6741                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6742
6743   // Handle VPERMILPD* permutations
6744   if (isVPERMILPDMask(M, VT, Subtarget))
6745     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6746                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6747
6748   // Handle VPERM2F128 permutations
6749   if (isVPERM2F128Mask(M, VT, Subtarget))
6750     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6751                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6752
6753   // Handle VSHUFPSY permutations
6754   if (isVSHUFPSYMask(M, VT, Subtarget))
6755     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6756                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6757
6758   // Handle VSHUFPDY permutations
6759   if (isVSHUFPDYMask(M, VT, Subtarget))
6760     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6761                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6762
6763   //===--------------------------------------------------------------------===//
6764   // Since no target specific shuffle was selected for this generic one,
6765   // lower it into other known shuffles. FIXME: this isn't true yet, but
6766   // this is the plan.
6767   //
6768
6769   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6770   if (VT == MVT::v8i16) {
6771     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6772     if (NewOp.getNode())
6773       return NewOp;
6774   }
6775
6776   if (VT == MVT::v16i8) {
6777     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6778     if (NewOp.getNode())
6779       return NewOp;
6780   }
6781
6782   // Handle all 128-bit wide vectors with 4 elements, and match them with
6783   // several different shuffle types.
6784   if (NumElems == 4 && VT.getSizeInBits() == 128)
6785     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6786
6787   // Handle general 256-bit shuffles
6788   if (VT.is256BitVector())
6789     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6790
6791   return SDValue();
6792 }
6793
6794 SDValue
6795 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6796                                                 SelectionDAG &DAG) const {
6797   EVT VT = Op.getValueType();
6798   DebugLoc dl = Op.getDebugLoc();
6799
6800   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6801     return SDValue();
6802
6803   if (VT.getSizeInBits() == 8) {
6804     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6805                                     Op.getOperand(0), Op.getOperand(1));
6806     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6807                                     DAG.getValueType(VT));
6808     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6809   } else if (VT.getSizeInBits() == 16) {
6810     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6811     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6812     if (Idx == 0)
6813       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6814                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6815                                      DAG.getNode(ISD::BITCAST, dl,
6816                                                  MVT::v4i32,
6817                                                  Op.getOperand(0)),
6818                                      Op.getOperand(1)));
6819     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6820                                     Op.getOperand(0), Op.getOperand(1));
6821     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6822                                     DAG.getValueType(VT));
6823     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6824   } else if (VT == MVT::f32) {
6825     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6826     // the result back to FR32 register. It's only worth matching if the
6827     // result has a single use which is a store or a bitcast to i32.  And in
6828     // the case of a store, it's not worth it if the index is a constant 0,
6829     // because a MOVSSmr can be used instead, which is smaller and faster.
6830     if (!Op.hasOneUse())
6831       return SDValue();
6832     SDNode *User = *Op.getNode()->use_begin();
6833     if ((User->getOpcode() != ISD::STORE ||
6834          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6835           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6836         (User->getOpcode() != ISD::BITCAST ||
6837          User->getValueType(0) != MVT::i32))
6838       return SDValue();
6839     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6840                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6841                                               Op.getOperand(0)),
6842                                               Op.getOperand(1));
6843     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6844   } else if (VT == MVT::i32) {
6845     // ExtractPS works with constant index.
6846     if (isa<ConstantSDNode>(Op.getOperand(1)))
6847       return Op;
6848   }
6849   return SDValue();
6850 }
6851
6852
6853 SDValue
6854 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6855                                            SelectionDAG &DAG) const {
6856   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6857     return SDValue();
6858
6859   SDValue Vec = Op.getOperand(0);
6860   EVT VecVT = Vec.getValueType();
6861
6862   // If this is a 256-bit vector result, first extract the 128-bit vector and
6863   // then extract the element from the 128-bit vector.
6864   if (VecVT.getSizeInBits() == 256) {
6865     DebugLoc dl = Op.getNode()->getDebugLoc();
6866     unsigned NumElems = VecVT.getVectorNumElements();
6867     SDValue Idx = Op.getOperand(1);
6868     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6869
6870     // Get the 128-bit vector.
6871     bool Upper = IdxVal >= NumElems/2;
6872     Vec = Extract128BitVector(Vec,
6873                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6874
6875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6876                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6877   }
6878
6879   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6880
6881   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6882     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6883     if (Res.getNode())
6884       return Res;
6885   }
6886
6887   EVT VT = Op.getValueType();
6888   DebugLoc dl = Op.getDebugLoc();
6889   // TODO: handle v16i8.
6890   if (VT.getSizeInBits() == 16) {
6891     SDValue Vec = Op.getOperand(0);
6892     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6893     if (Idx == 0)
6894       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6895                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6896                                      DAG.getNode(ISD::BITCAST, dl,
6897                                                  MVT::v4i32, Vec),
6898                                      Op.getOperand(1)));
6899     // Transform it so it match pextrw which produces a 32-bit result.
6900     EVT EltVT = MVT::i32;
6901     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6902                                     Op.getOperand(0), Op.getOperand(1));
6903     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6904                                     DAG.getValueType(VT));
6905     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6906   } else if (VT.getSizeInBits() == 32) {
6907     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6908     if (Idx == 0)
6909       return Op;
6910
6911     // SHUFPS the element to the lowest double word, then movss.
6912     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6913     EVT VVT = Op.getOperand(0).getValueType();
6914     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6915                                        DAG.getUNDEF(VVT), Mask);
6916     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6917                        DAG.getIntPtrConstant(0));
6918   } else if (VT.getSizeInBits() == 64) {
6919     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6920     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6921     //        to match extract_elt for f64.
6922     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6923     if (Idx == 0)
6924       return Op;
6925
6926     // UNPCKHPD the element to the lowest double word, then movsd.
6927     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6928     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6929     int Mask[2] = { 1, -1 };
6930     EVT VVT = Op.getOperand(0).getValueType();
6931     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6932                                        DAG.getUNDEF(VVT), Mask);
6933     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6934                        DAG.getIntPtrConstant(0));
6935   }
6936
6937   return SDValue();
6938 }
6939
6940 SDValue
6941 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6942                                                SelectionDAG &DAG) const {
6943   EVT VT = Op.getValueType();
6944   EVT EltVT = VT.getVectorElementType();
6945   DebugLoc dl = Op.getDebugLoc();
6946
6947   SDValue N0 = Op.getOperand(0);
6948   SDValue N1 = Op.getOperand(1);
6949   SDValue N2 = Op.getOperand(2);
6950
6951   if (VT.getSizeInBits() == 256)
6952     return SDValue();
6953
6954   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6955       isa<ConstantSDNode>(N2)) {
6956     unsigned Opc;
6957     if (VT == MVT::v8i16)
6958       Opc = X86ISD::PINSRW;
6959     else if (VT == MVT::v16i8)
6960       Opc = X86ISD::PINSRB;
6961     else
6962       Opc = X86ISD::PINSRB;
6963
6964     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6965     // argument.
6966     if (N1.getValueType() != MVT::i32)
6967       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6968     if (N2.getValueType() != MVT::i32)
6969       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6970     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6971   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6972     // Bits [7:6] of the constant are the source select.  This will always be
6973     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6974     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6975     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6976     // Bits [5:4] of the constant are the destination select.  This is the
6977     //  value of the incoming immediate.
6978     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6979     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6980     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6981     // Create this as a scalar to vector..
6982     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6983     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6984   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6985     // PINSR* works with constant index.
6986     return Op;
6987   }
6988   return SDValue();
6989 }
6990
6991 SDValue
6992 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6993   EVT VT = Op.getValueType();
6994   EVT EltVT = VT.getVectorElementType();
6995
6996   DebugLoc dl = Op.getDebugLoc();
6997   SDValue N0 = Op.getOperand(0);
6998   SDValue N1 = Op.getOperand(1);
6999   SDValue N2 = Op.getOperand(2);
7000
7001   // If this is a 256-bit vector result, first extract the 128-bit vector,
7002   // insert the element into the extracted half and then place it back.
7003   if (VT.getSizeInBits() == 256) {
7004     if (!isa<ConstantSDNode>(N2))
7005       return SDValue();
7006
7007     // Get the desired 128-bit vector half.
7008     unsigned NumElems = VT.getVectorNumElements();
7009     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7010     bool Upper = IdxVal >= NumElems/2;
7011     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7012     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7013
7014     // Insert the element into the desired half.
7015     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7016                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7017
7018     // Insert the changed part back to the 256-bit vector
7019     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7020   }
7021
7022   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7023     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7024
7025   if (EltVT == MVT::i8)
7026     return SDValue();
7027
7028   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7029     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7030     // as its second argument.
7031     if (N1.getValueType() != MVT::i32)
7032       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7033     if (N2.getValueType() != MVT::i32)
7034       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7035     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7036   }
7037   return SDValue();
7038 }
7039
7040 SDValue
7041 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7042   LLVMContext *Context = DAG.getContext();
7043   DebugLoc dl = Op.getDebugLoc();
7044   EVT OpVT = Op.getValueType();
7045
7046   // If this is a 256-bit vector result, first insert into a 128-bit
7047   // vector and then insert into the 256-bit vector.
7048   if (OpVT.getSizeInBits() > 128) {
7049     // Insert into a 128-bit vector.
7050     EVT VT128 = EVT::getVectorVT(*Context,
7051                                  OpVT.getVectorElementType(),
7052                                  OpVT.getVectorNumElements() / 2);
7053
7054     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7055
7056     // Insert the 128-bit vector.
7057     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7058                               DAG.getConstant(0, MVT::i32),
7059                               DAG, dl);
7060   }
7061
7062   if (Op.getValueType() == MVT::v1i64 &&
7063       Op.getOperand(0).getValueType() == MVT::i64)
7064     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7065
7066   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7067   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7068          "Expected an SSE type!");
7069   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7070                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7071 }
7072
7073 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7074 // a simple subregister reference or explicit instructions to grab
7075 // upper bits of a vector.
7076 SDValue
7077 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7078   if (Subtarget->hasAVX()) {
7079     DebugLoc dl = Op.getNode()->getDebugLoc();
7080     SDValue Vec = Op.getNode()->getOperand(0);
7081     SDValue Idx = Op.getNode()->getOperand(1);
7082
7083     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7084         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7085         return Extract128BitVector(Vec, Idx, DAG, dl);
7086     }
7087   }
7088   return SDValue();
7089 }
7090
7091 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7092 // simple superregister reference or explicit instructions to insert
7093 // the upper bits of a vector.
7094 SDValue
7095 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7096   if (Subtarget->hasAVX()) {
7097     DebugLoc dl = Op.getNode()->getDebugLoc();
7098     SDValue Vec = Op.getNode()->getOperand(0);
7099     SDValue SubVec = Op.getNode()->getOperand(1);
7100     SDValue Idx = Op.getNode()->getOperand(2);
7101
7102     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7103         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7104       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7105     }
7106   }
7107   return SDValue();
7108 }
7109
7110 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7111 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7112 // one of the above mentioned nodes. It has to be wrapped because otherwise
7113 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7114 // be used to form addressing mode. These wrapped nodes will be selected
7115 // into MOV32ri.
7116 SDValue
7117 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7118   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7119
7120   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7121   // global base reg.
7122   unsigned char OpFlag = 0;
7123   unsigned WrapperKind = X86ISD::Wrapper;
7124   CodeModel::Model M = getTargetMachine().getCodeModel();
7125
7126   if (Subtarget->isPICStyleRIPRel() &&
7127       (M == CodeModel::Small || M == CodeModel::Kernel))
7128     WrapperKind = X86ISD::WrapperRIP;
7129   else if (Subtarget->isPICStyleGOT())
7130     OpFlag = X86II::MO_GOTOFF;
7131   else if (Subtarget->isPICStyleStubPIC())
7132     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7133
7134   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7135                                              CP->getAlignment(),
7136                                              CP->getOffset(), OpFlag);
7137   DebugLoc DL = CP->getDebugLoc();
7138   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7139   // With PIC, the address is actually $g + Offset.
7140   if (OpFlag) {
7141     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7142                          DAG.getNode(X86ISD::GlobalBaseReg,
7143                                      DebugLoc(), getPointerTy()),
7144                          Result);
7145   }
7146
7147   return Result;
7148 }
7149
7150 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7151   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7152
7153   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7154   // global base reg.
7155   unsigned char OpFlag = 0;
7156   unsigned WrapperKind = X86ISD::Wrapper;
7157   CodeModel::Model M = getTargetMachine().getCodeModel();
7158
7159   if (Subtarget->isPICStyleRIPRel() &&
7160       (M == CodeModel::Small || M == CodeModel::Kernel))
7161     WrapperKind = X86ISD::WrapperRIP;
7162   else if (Subtarget->isPICStyleGOT())
7163     OpFlag = X86II::MO_GOTOFF;
7164   else if (Subtarget->isPICStyleStubPIC())
7165     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7166
7167   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7168                                           OpFlag);
7169   DebugLoc DL = JT->getDebugLoc();
7170   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7171
7172   // With PIC, the address is actually $g + Offset.
7173   if (OpFlag)
7174     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7175                          DAG.getNode(X86ISD::GlobalBaseReg,
7176                                      DebugLoc(), getPointerTy()),
7177                          Result);
7178
7179   return Result;
7180 }
7181
7182 SDValue
7183 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7184   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7185
7186   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7187   // global base reg.
7188   unsigned char OpFlag = 0;
7189   unsigned WrapperKind = X86ISD::Wrapper;
7190   CodeModel::Model M = getTargetMachine().getCodeModel();
7191
7192   if (Subtarget->isPICStyleRIPRel() &&
7193       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7194     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7195       OpFlag = X86II::MO_GOTPCREL;
7196     WrapperKind = X86ISD::WrapperRIP;
7197   } else if (Subtarget->isPICStyleGOT()) {
7198     OpFlag = X86II::MO_GOT;
7199   } else if (Subtarget->isPICStyleStubPIC()) {
7200     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7201   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7202     OpFlag = X86II::MO_DARWIN_NONLAZY;
7203   }
7204
7205   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7206
7207   DebugLoc DL = Op.getDebugLoc();
7208   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7209
7210
7211   // With PIC, the address is actually $g + Offset.
7212   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7213       !Subtarget->is64Bit()) {
7214     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7215                          DAG.getNode(X86ISD::GlobalBaseReg,
7216                                      DebugLoc(), getPointerTy()),
7217                          Result);
7218   }
7219
7220   // For symbols that require a load from a stub to get the address, emit the
7221   // load.
7222   if (isGlobalStubReference(OpFlag))
7223     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7224                          MachinePointerInfo::getGOT(), false, false, 0);
7225
7226   return Result;
7227 }
7228
7229 SDValue
7230 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7231   // Create the TargetBlockAddressAddress node.
7232   unsigned char OpFlags =
7233     Subtarget->ClassifyBlockAddressReference();
7234   CodeModel::Model M = getTargetMachine().getCodeModel();
7235   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7236   DebugLoc dl = Op.getDebugLoc();
7237   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7238                                        /*isTarget=*/true, OpFlags);
7239
7240   if (Subtarget->isPICStyleRIPRel() &&
7241       (M == CodeModel::Small || M == CodeModel::Kernel))
7242     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7243   else
7244     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7245
7246   // With PIC, the address is actually $g + Offset.
7247   if (isGlobalRelativeToPICBase(OpFlags)) {
7248     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7249                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7250                          Result);
7251   }
7252
7253   return Result;
7254 }
7255
7256 SDValue
7257 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7258                                       int64_t Offset,
7259                                       SelectionDAG &DAG) const {
7260   // Create the TargetGlobalAddress node, folding in the constant
7261   // offset if it is legal.
7262   unsigned char OpFlags =
7263     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7264   CodeModel::Model M = getTargetMachine().getCodeModel();
7265   SDValue Result;
7266   if (OpFlags == X86II::MO_NO_FLAG &&
7267       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7268     // A direct static reference to a global.
7269     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7270     Offset = 0;
7271   } else {
7272     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7273   }
7274
7275   if (Subtarget->isPICStyleRIPRel() &&
7276       (M == CodeModel::Small || M == CodeModel::Kernel))
7277     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7278   else
7279     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7280
7281   // With PIC, the address is actually $g + Offset.
7282   if (isGlobalRelativeToPICBase(OpFlags)) {
7283     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7284                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7285                          Result);
7286   }
7287
7288   // For globals that require a load from a stub to get the address, emit the
7289   // load.
7290   if (isGlobalStubReference(OpFlags))
7291     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7292                          MachinePointerInfo::getGOT(), false, false, 0);
7293
7294   // If there was a non-zero offset that we didn't fold, create an explicit
7295   // addition for it.
7296   if (Offset != 0)
7297     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7298                          DAG.getConstant(Offset, getPointerTy()));
7299
7300   return Result;
7301 }
7302
7303 SDValue
7304 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7305   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7306   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7307   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7308 }
7309
7310 static SDValue
7311 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7312            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7313            unsigned char OperandFlags) {
7314   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7315   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7316   DebugLoc dl = GA->getDebugLoc();
7317   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7318                                            GA->getValueType(0),
7319                                            GA->getOffset(),
7320                                            OperandFlags);
7321   if (InFlag) {
7322     SDValue Ops[] = { Chain,  TGA, *InFlag };
7323     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7324   } else {
7325     SDValue Ops[]  = { Chain, TGA };
7326     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7327   }
7328
7329   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7330   MFI->setAdjustsStack(true);
7331
7332   SDValue Flag = Chain.getValue(1);
7333   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7334 }
7335
7336 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7337 static SDValue
7338 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7339                                 const EVT PtrVT) {
7340   SDValue InFlag;
7341   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7342   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7343                                      DAG.getNode(X86ISD::GlobalBaseReg,
7344                                                  DebugLoc(), PtrVT), InFlag);
7345   InFlag = Chain.getValue(1);
7346
7347   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7348 }
7349
7350 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7351 static SDValue
7352 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7353                                 const EVT PtrVT) {
7354   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7355                     X86::RAX, X86II::MO_TLSGD);
7356 }
7357
7358 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7359 // "local exec" model.
7360 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7361                                    const EVT PtrVT, TLSModel::Model model,
7362                                    bool is64Bit) {
7363   DebugLoc dl = GA->getDebugLoc();
7364
7365   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7366   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7367                                                          is64Bit ? 257 : 256));
7368
7369   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7370                                       DAG.getIntPtrConstant(0),
7371                                       MachinePointerInfo(Ptr), false, false, 0);
7372
7373   unsigned char OperandFlags = 0;
7374   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7375   // initialexec.
7376   unsigned WrapperKind = X86ISD::Wrapper;
7377   if (model == TLSModel::LocalExec) {
7378     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7379   } else if (is64Bit) {
7380     assert(model == TLSModel::InitialExec);
7381     OperandFlags = X86II::MO_GOTTPOFF;
7382     WrapperKind = X86ISD::WrapperRIP;
7383   } else {
7384     assert(model == TLSModel::InitialExec);
7385     OperandFlags = X86II::MO_INDNTPOFF;
7386   }
7387
7388   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7389   // exec)
7390   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7391                                            GA->getValueType(0),
7392                                            GA->getOffset(), OperandFlags);
7393   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7394
7395   if (model == TLSModel::InitialExec)
7396     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7397                          MachinePointerInfo::getGOT(), false, false, 0);
7398
7399   // The address of the thread local variable is the add of the thread
7400   // pointer with the offset of the variable.
7401   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7402 }
7403
7404 SDValue
7405 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7406
7407   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7408   const GlobalValue *GV = GA->getGlobal();
7409
7410   if (Subtarget->isTargetELF()) {
7411     // TODO: implement the "local dynamic" model
7412     // TODO: implement the "initial exec"model for pic executables
7413
7414     // If GV is an alias then use the aliasee for determining
7415     // thread-localness.
7416     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7417       GV = GA->resolveAliasedGlobal(false);
7418
7419     TLSModel::Model model
7420       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7421
7422     switch (model) {
7423       case TLSModel::GeneralDynamic:
7424       case TLSModel::LocalDynamic: // not implemented
7425         if (Subtarget->is64Bit())
7426           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7427         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7428
7429       case TLSModel::InitialExec:
7430       case TLSModel::LocalExec:
7431         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7432                                    Subtarget->is64Bit());
7433     }
7434   } else if (Subtarget->isTargetDarwin()) {
7435     // Darwin only has one model of TLS.  Lower to that.
7436     unsigned char OpFlag = 0;
7437     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7438                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7439
7440     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7441     // global base reg.
7442     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7443                   !Subtarget->is64Bit();
7444     if (PIC32)
7445       OpFlag = X86II::MO_TLVP_PIC_BASE;
7446     else
7447       OpFlag = X86II::MO_TLVP;
7448     DebugLoc DL = Op.getDebugLoc();
7449     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7450                                                 GA->getValueType(0),
7451                                                 GA->getOffset(), OpFlag);
7452     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7453
7454     // With PIC32, the address is actually $g + Offset.
7455     if (PIC32)
7456       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7457                            DAG.getNode(X86ISD::GlobalBaseReg,
7458                                        DebugLoc(), getPointerTy()),
7459                            Offset);
7460
7461     // Lowering the machine isd will make sure everything is in the right
7462     // location.
7463     SDValue Chain = DAG.getEntryNode();
7464     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7465     SDValue Args[] = { Chain, Offset };
7466     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7467
7468     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7469     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7470     MFI->setAdjustsStack(true);
7471
7472     // And our return value (tls address) is in the standard call return value
7473     // location.
7474     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7475     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7476   }
7477
7478   assert(false &&
7479          "TLS not implemented for this target.");
7480
7481   llvm_unreachable("Unreachable");
7482   return SDValue();
7483 }
7484
7485
7486 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7487 /// take a 2 x i32 value to shift plus a shift amount.
7488 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7489   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7490   EVT VT = Op.getValueType();
7491   unsigned VTBits = VT.getSizeInBits();
7492   DebugLoc dl = Op.getDebugLoc();
7493   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7494   SDValue ShOpLo = Op.getOperand(0);
7495   SDValue ShOpHi = Op.getOperand(1);
7496   SDValue ShAmt  = Op.getOperand(2);
7497   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7498                                      DAG.getConstant(VTBits - 1, MVT::i8))
7499                        : DAG.getConstant(0, VT);
7500
7501   SDValue Tmp2, Tmp3;
7502   if (Op.getOpcode() == ISD::SHL_PARTS) {
7503     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7504     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7505   } else {
7506     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7507     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7508   }
7509
7510   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7511                                 DAG.getConstant(VTBits, MVT::i8));
7512   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7513                              AndNode, DAG.getConstant(0, MVT::i8));
7514
7515   SDValue Hi, Lo;
7516   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7517   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7518   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7519
7520   if (Op.getOpcode() == ISD::SHL_PARTS) {
7521     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7522     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7523   } else {
7524     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7525     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7526   }
7527
7528   SDValue Ops[2] = { Lo, Hi };
7529   return DAG.getMergeValues(Ops, 2, dl);
7530 }
7531
7532 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7533                                            SelectionDAG &DAG) const {
7534   EVT SrcVT = Op.getOperand(0).getValueType();
7535
7536   if (SrcVT.isVector())
7537     return SDValue();
7538
7539   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7540          "Unknown SINT_TO_FP to lower!");
7541
7542   // These are really Legal; return the operand so the caller accepts it as
7543   // Legal.
7544   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7545     return Op;
7546   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7547       Subtarget->is64Bit()) {
7548     return Op;
7549   }
7550
7551   DebugLoc dl = Op.getDebugLoc();
7552   unsigned Size = SrcVT.getSizeInBits()/8;
7553   MachineFunction &MF = DAG.getMachineFunction();
7554   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7555   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7556   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7557                                StackSlot,
7558                                MachinePointerInfo::getFixedStack(SSFI),
7559                                false, false, 0);
7560   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7561 }
7562
7563 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7564                                      SDValue StackSlot,
7565                                      SelectionDAG &DAG) const {
7566   // Build the FILD
7567   DebugLoc DL = Op.getDebugLoc();
7568   SDVTList Tys;
7569   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7570   if (useSSE)
7571     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7572   else
7573     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7574
7575   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7576
7577   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7578   MachineMemOperand *MMO;
7579   if (FI) {
7580     int SSFI = FI->getIndex();
7581     MMO =
7582       DAG.getMachineFunction()
7583       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7584                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7585   } else {
7586     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7587     StackSlot = StackSlot.getOperand(1);
7588   }
7589   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7590   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7591                                            X86ISD::FILD, DL,
7592                                            Tys, Ops, array_lengthof(Ops),
7593                                            SrcVT, MMO);
7594
7595   if (useSSE) {
7596     Chain = Result.getValue(1);
7597     SDValue InFlag = Result.getValue(2);
7598
7599     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7600     // shouldn't be necessary except that RFP cannot be live across
7601     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7602     MachineFunction &MF = DAG.getMachineFunction();
7603     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7604     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7605     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7606     Tys = DAG.getVTList(MVT::Other);
7607     SDValue Ops[] = {
7608       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7609     };
7610     MachineMemOperand *MMO =
7611       DAG.getMachineFunction()
7612       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7613                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7614
7615     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7616                                     Ops, array_lengthof(Ops),
7617                                     Op.getValueType(), MMO);
7618     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7619                          MachinePointerInfo::getFixedStack(SSFI),
7620                          false, false, 0);
7621   }
7622
7623   return Result;
7624 }
7625
7626 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7627 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7628                                                SelectionDAG &DAG) const {
7629   // This algorithm is not obvious. Here it is in C code, more or less:
7630   /*
7631     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7632       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7633       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7634
7635       // Copy ints to xmm registers.
7636       __m128i xh = _mm_cvtsi32_si128( hi );
7637       __m128i xl = _mm_cvtsi32_si128( lo );
7638
7639       // Combine into low half of a single xmm register.
7640       __m128i x = _mm_unpacklo_epi32( xh, xl );
7641       __m128d d;
7642       double sd;
7643
7644       // Merge in appropriate exponents to give the integer bits the right
7645       // magnitude.
7646       x = _mm_unpacklo_epi32( x, exp );
7647
7648       // Subtract away the biases to deal with the IEEE-754 double precision
7649       // implicit 1.
7650       d = _mm_sub_pd( (__m128d) x, bias );
7651
7652       // All conversions up to here are exact. The correctly rounded result is
7653       // calculated using the current rounding mode using the following
7654       // horizontal add.
7655       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7656       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7657                                 // store doesn't really need to be here (except
7658                                 // maybe to zero the other double)
7659       return sd;
7660     }
7661   */
7662
7663   DebugLoc dl = Op.getDebugLoc();
7664   LLVMContext *Context = DAG.getContext();
7665
7666   // Build some magic constants.
7667   std::vector<Constant*> CV0;
7668   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7669   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7670   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7671   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7672   Constant *C0 = ConstantVector::get(CV0);
7673   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7674
7675   std::vector<Constant*> CV1;
7676   CV1.push_back(
7677     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7678   CV1.push_back(
7679     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7680   Constant *C1 = ConstantVector::get(CV1);
7681   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7682
7683   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7684                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7685                                         Op.getOperand(0),
7686                                         DAG.getIntPtrConstant(1)));
7687   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7688                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7689                                         Op.getOperand(0),
7690                                         DAG.getIntPtrConstant(0)));
7691   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7692   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7693                               MachinePointerInfo::getConstantPool(),
7694                               false, false, 16);
7695   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7696   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7697   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7698                               MachinePointerInfo::getConstantPool(),
7699                               false, false, 16);
7700   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7701
7702   // Add the halves; easiest way is to swap them into another reg first.
7703   int ShufMask[2] = { 1, -1 };
7704   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7705                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7706   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7707   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7708                      DAG.getIntPtrConstant(0));
7709 }
7710
7711 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7712 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7713                                                SelectionDAG &DAG) const {
7714   DebugLoc dl = Op.getDebugLoc();
7715   // FP constant to bias correct the final result.
7716   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7717                                    MVT::f64);
7718
7719   // Load the 32-bit value into an XMM register.
7720   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7721                              Op.getOperand(0));
7722
7723   // Zero out the upper parts of the register.
7724   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasSSE2(), DAG);
7725
7726   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7727                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7728                      DAG.getIntPtrConstant(0));
7729
7730   // Or the load with the bias.
7731   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7732                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7733                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7734                                                    MVT::v2f64, Load)),
7735                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7736                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7737                                                    MVT::v2f64, Bias)));
7738   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7739                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7740                    DAG.getIntPtrConstant(0));
7741
7742   // Subtract the bias.
7743   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7744
7745   // Handle final rounding.
7746   EVT DestVT = Op.getValueType();
7747
7748   if (DestVT.bitsLT(MVT::f64)) {
7749     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7750                        DAG.getIntPtrConstant(0));
7751   } else if (DestVT.bitsGT(MVT::f64)) {
7752     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7753   }
7754
7755   // Handle final rounding.
7756   return Sub;
7757 }
7758
7759 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7760                                            SelectionDAG &DAG) const {
7761   SDValue N0 = Op.getOperand(0);
7762   DebugLoc dl = Op.getDebugLoc();
7763
7764   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7765   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7766   // the optimization here.
7767   if (DAG.SignBitIsZero(N0))
7768     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7769
7770   EVT SrcVT = N0.getValueType();
7771   EVT DstVT = Op.getValueType();
7772   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7773     return LowerUINT_TO_FP_i64(Op, DAG);
7774   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7775     return LowerUINT_TO_FP_i32(Op, DAG);
7776
7777   // Make a 64-bit buffer, and use it to build an FILD.
7778   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7779   if (SrcVT == MVT::i32) {
7780     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7781     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7782                                      getPointerTy(), StackSlot, WordOff);
7783     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7784                                   StackSlot, MachinePointerInfo(),
7785                                   false, false, 0);
7786     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7787                                   OffsetSlot, MachinePointerInfo(),
7788                                   false, false, 0);
7789     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7790     return Fild;
7791   }
7792
7793   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7794   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7795                                 StackSlot, MachinePointerInfo(),
7796                                false, false, 0);
7797   // For i64 source, we need to add the appropriate power of 2 if the input
7798   // was negative.  This is the same as the optimization in
7799   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7800   // we must be careful to do the computation in x87 extended precision, not
7801   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7802   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7803   MachineMemOperand *MMO =
7804     DAG.getMachineFunction()
7805     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7806                           MachineMemOperand::MOLoad, 8, 8);
7807
7808   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7809   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7810   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7811                                          MVT::i64, MMO);
7812
7813   APInt FF(32, 0x5F800000ULL);
7814
7815   // Check whether the sign bit is set.
7816   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7817                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7818                                  ISD::SETLT);
7819
7820   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7821   SDValue FudgePtr = DAG.getConstantPool(
7822                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7823                                          getPointerTy());
7824
7825   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7826   SDValue Zero = DAG.getIntPtrConstant(0);
7827   SDValue Four = DAG.getIntPtrConstant(4);
7828   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7829                                Zero, Four);
7830   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7831
7832   // Load the value out, extending it from f32 to f80.
7833   // FIXME: Avoid the extend by constructing the right constant pool?
7834   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7835                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7836                                  MVT::f32, false, false, 4);
7837   // Extend everything to 80 bits to force it to be done on x87.
7838   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7839   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7840 }
7841
7842 std::pair<SDValue,SDValue> X86TargetLowering::
7843 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7844   DebugLoc DL = Op.getDebugLoc();
7845
7846   EVT DstTy = Op.getValueType();
7847
7848   if (!IsSigned) {
7849     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7850     DstTy = MVT::i64;
7851   }
7852
7853   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7854          DstTy.getSimpleVT() >= MVT::i16 &&
7855          "Unknown FP_TO_SINT to lower!");
7856
7857   // These are really Legal.
7858   if (DstTy == MVT::i32 &&
7859       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7860     return std::make_pair(SDValue(), SDValue());
7861   if (Subtarget->is64Bit() &&
7862       DstTy == MVT::i64 &&
7863       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7864     return std::make_pair(SDValue(), SDValue());
7865
7866   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7867   // stack slot.
7868   MachineFunction &MF = DAG.getMachineFunction();
7869   unsigned MemSize = DstTy.getSizeInBits()/8;
7870   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7871   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7872
7873
7874
7875   unsigned Opc;
7876   switch (DstTy.getSimpleVT().SimpleTy) {
7877   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7878   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7879   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7880   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7881   }
7882
7883   SDValue Chain = DAG.getEntryNode();
7884   SDValue Value = Op.getOperand(0);
7885   EVT TheVT = Op.getOperand(0).getValueType();
7886   if (isScalarFPTypeInSSEReg(TheVT)) {
7887     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7888     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7889                          MachinePointerInfo::getFixedStack(SSFI),
7890                          false, false, 0);
7891     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7892     SDValue Ops[] = {
7893       Chain, StackSlot, DAG.getValueType(TheVT)
7894     };
7895
7896     MachineMemOperand *MMO =
7897       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7898                               MachineMemOperand::MOLoad, MemSize, MemSize);
7899     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7900                                     DstTy, MMO);
7901     Chain = Value.getValue(1);
7902     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7903     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7904   }
7905
7906   MachineMemOperand *MMO =
7907     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7908                             MachineMemOperand::MOStore, MemSize, MemSize);
7909
7910   // Build the FP_TO_INT*_IN_MEM
7911   SDValue Ops[] = { Chain, Value, StackSlot };
7912   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7913                                          Ops, 3, DstTy, MMO);
7914
7915   return std::make_pair(FIST, StackSlot);
7916 }
7917
7918 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7919                                            SelectionDAG &DAG) const {
7920   if (Op.getValueType().isVector())
7921     return SDValue();
7922
7923   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7924   SDValue FIST = Vals.first, StackSlot = Vals.second;
7925   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7926   if (FIST.getNode() == 0) return Op;
7927
7928   // Load the result.
7929   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7930                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7931 }
7932
7933 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7934                                            SelectionDAG &DAG) const {
7935   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7936   SDValue FIST = Vals.first, StackSlot = Vals.second;
7937   assert(FIST.getNode() && "Unexpected failure");
7938
7939   // Load the result.
7940   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7941                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7942 }
7943
7944 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7945                                      SelectionDAG &DAG) const {
7946   LLVMContext *Context = DAG.getContext();
7947   DebugLoc dl = Op.getDebugLoc();
7948   EVT VT = Op.getValueType();
7949   EVT EltVT = VT;
7950   if (VT.isVector())
7951     EltVT = VT.getVectorElementType();
7952   std::vector<Constant*> CV;
7953   if (EltVT == MVT::f64) {
7954     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7955     CV.push_back(C);
7956     CV.push_back(C);
7957   } else {
7958     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7959     CV.push_back(C);
7960     CV.push_back(C);
7961     CV.push_back(C);
7962     CV.push_back(C);
7963   }
7964   Constant *C = ConstantVector::get(CV);
7965   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7966   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7967                              MachinePointerInfo::getConstantPool(),
7968                              false, false, 16);
7969   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7970 }
7971
7972 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7973   LLVMContext *Context = DAG.getContext();
7974   DebugLoc dl = Op.getDebugLoc();
7975   EVT VT = Op.getValueType();
7976   EVT EltVT = VT;
7977   if (VT.isVector())
7978     EltVT = VT.getVectorElementType();
7979   std::vector<Constant*> CV;
7980   if (EltVT == MVT::f64) {
7981     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7982     CV.push_back(C);
7983     CV.push_back(C);
7984   } else {
7985     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7986     CV.push_back(C);
7987     CV.push_back(C);
7988     CV.push_back(C);
7989     CV.push_back(C);
7990   }
7991   Constant *C = ConstantVector::get(CV);
7992   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7993   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7994                              MachinePointerInfo::getConstantPool(),
7995                              false, false, 16);
7996   if (VT.isVector()) {
7997     return DAG.getNode(ISD::BITCAST, dl, VT,
7998                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7999                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8000                                 Op.getOperand(0)),
8001                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8002   } else {
8003     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8004   }
8005 }
8006
8007 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8008   LLVMContext *Context = DAG.getContext();
8009   SDValue Op0 = Op.getOperand(0);
8010   SDValue Op1 = Op.getOperand(1);
8011   DebugLoc dl = Op.getDebugLoc();
8012   EVT VT = Op.getValueType();
8013   EVT SrcVT = Op1.getValueType();
8014
8015   // If second operand is smaller, extend it first.
8016   if (SrcVT.bitsLT(VT)) {
8017     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8018     SrcVT = VT;
8019   }
8020   // And if it is bigger, shrink it first.
8021   if (SrcVT.bitsGT(VT)) {
8022     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8023     SrcVT = VT;
8024   }
8025
8026   // At this point the operands and the result should have the same
8027   // type, and that won't be f80 since that is not custom lowered.
8028
8029   // First get the sign bit of second operand.
8030   std::vector<Constant*> CV;
8031   if (SrcVT == MVT::f64) {
8032     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8033     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8034   } else {
8035     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8036     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8037     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8038     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8039   }
8040   Constant *C = ConstantVector::get(CV);
8041   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8042   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8043                               MachinePointerInfo::getConstantPool(),
8044                               false, false, 16);
8045   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8046
8047   // Shift sign bit right or left if the two operands have different types.
8048   if (SrcVT.bitsGT(VT)) {
8049     // Op0 is MVT::f32, Op1 is MVT::f64.
8050     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8051     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8052                           DAG.getConstant(32, MVT::i32));
8053     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8054     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8055                           DAG.getIntPtrConstant(0));
8056   }
8057
8058   // Clear first operand sign bit.
8059   CV.clear();
8060   if (VT == MVT::f64) {
8061     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8062     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8063   } else {
8064     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8065     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8066     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8067     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8068   }
8069   C = ConstantVector::get(CV);
8070   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8071   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8072                               MachinePointerInfo::getConstantPool(),
8073                               false, false, 16);
8074   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8075
8076   // Or the value with the sign bit.
8077   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8078 }
8079
8080 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8081   SDValue N0 = Op.getOperand(0);
8082   DebugLoc dl = Op.getDebugLoc();
8083   EVT VT = Op.getValueType();
8084
8085   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8086   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8087                                   DAG.getConstant(1, VT));
8088   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8089 }
8090
8091 /// Emit nodes that will be selected as "test Op0,Op0", or something
8092 /// equivalent.
8093 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8094                                     SelectionDAG &DAG) const {
8095   DebugLoc dl = Op.getDebugLoc();
8096
8097   // CF and OF aren't always set the way we want. Determine which
8098   // of these we need.
8099   bool NeedCF = false;
8100   bool NeedOF = false;
8101   switch (X86CC) {
8102   default: break;
8103   case X86::COND_A: case X86::COND_AE:
8104   case X86::COND_B: case X86::COND_BE:
8105     NeedCF = true;
8106     break;
8107   case X86::COND_G: case X86::COND_GE:
8108   case X86::COND_L: case X86::COND_LE:
8109   case X86::COND_O: case X86::COND_NO:
8110     NeedOF = true;
8111     break;
8112   }
8113
8114   // See if we can use the EFLAGS value from the operand instead of
8115   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8116   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8117   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8118     // Emit a CMP with 0, which is the TEST pattern.
8119     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8120                        DAG.getConstant(0, Op.getValueType()));
8121
8122   unsigned Opcode = 0;
8123   unsigned NumOperands = 0;
8124   switch (Op.getNode()->getOpcode()) {
8125   case ISD::ADD:
8126     // Due to an isel shortcoming, be conservative if this add is likely to be
8127     // selected as part of a load-modify-store instruction. When the root node
8128     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8129     // uses of other nodes in the match, such as the ADD in this case. This
8130     // leads to the ADD being left around and reselected, with the result being
8131     // two adds in the output.  Alas, even if none our users are stores, that
8132     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8133     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8134     // climbing the DAG back to the root, and it doesn't seem to be worth the
8135     // effort.
8136     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8137            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8138       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8139         goto default_case;
8140
8141     if (ConstantSDNode *C =
8142         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8143       // An add of one will be selected as an INC.
8144       if (C->getAPIntValue() == 1) {
8145         Opcode = X86ISD::INC;
8146         NumOperands = 1;
8147         break;
8148       }
8149
8150       // An add of negative one (subtract of one) will be selected as a DEC.
8151       if (C->getAPIntValue().isAllOnesValue()) {
8152         Opcode = X86ISD::DEC;
8153         NumOperands = 1;
8154         break;
8155       }
8156     }
8157
8158     // Otherwise use a regular EFLAGS-setting add.
8159     Opcode = X86ISD::ADD;
8160     NumOperands = 2;
8161     break;
8162   case ISD::AND: {
8163     // If the primary and result isn't used, don't bother using X86ISD::AND,
8164     // because a TEST instruction will be better.
8165     bool NonFlagUse = false;
8166     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8167            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8168       SDNode *User = *UI;
8169       unsigned UOpNo = UI.getOperandNo();
8170       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8171         // Look pass truncate.
8172         UOpNo = User->use_begin().getOperandNo();
8173         User = *User->use_begin();
8174       }
8175
8176       if (User->getOpcode() != ISD::BRCOND &&
8177           User->getOpcode() != ISD::SETCC &&
8178           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8179         NonFlagUse = true;
8180         break;
8181       }
8182     }
8183
8184     if (!NonFlagUse)
8185       break;
8186   }
8187     // FALL THROUGH
8188   case ISD::SUB:
8189   case ISD::OR:
8190   case ISD::XOR:
8191     // Due to the ISEL shortcoming noted above, be conservative if this op is
8192     // likely to be selected as part of a load-modify-store instruction.
8193     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8194            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8195       if (UI->getOpcode() == ISD::STORE)
8196         goto default_case;
8197
8198     // Otherwise use a regular EFLAGS-setting instruction.
8199     switch (Op.getNode()->getOpcode()) {
8200     default: llvm_unreachable("unexpected operator!");
8201     case ISD::SUB: Opcode = X86ISD::SUB; break;
8202     case ISD::OR:  Opcode = X86ISD::OR;  break;
8203     case ISD::XOR: Opcode = X86ISD::XOR; break;
8204     case ISD::AND: Opcode = X86ISD::AND; break;
8205     }
8206
8207     NumOperands = 2;
8208     break;
8209   case X86ISD::ADD:
8210   case X86ISD::SUB:
8211   case X86ISD::INC:
8212   case X86ISD::DEC:
8213   case X86ISD::OR:
8214   case X86ISD::XOR:
8215   case X86ISD::AND:
8216     return SDValue(Op.getNode(), 1);
8217   default:
8218   default_case:
8219     break;
8220   }
8221
8222   if (Opcode == 0)
8223     // Emit a CMP with 0, which is the TEST pattern.
8224     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8225                        DAG.getConstant(0, Op.getValueType()));
8226
8227   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8228   SmallVector<SDValue, 4> Ops;
8229   for (unsigned i = 0; i != NumOperands; ++i)
8230     Ops.push_back(Op.getOperand(i));
8231
8232   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8233   DAG.ReplaceAllUsesWith(Op, New);
8234   return SDValue(New.getNode(), 1);
8235 }
8236
8237 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8238 /// equivalent.
8239 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8240                                    SelectionDAG &DAG) const {
8241   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8242     if (C->getAPIntValue() == 0)
8243       return EmitTest(Op0, X86CC, DAG);
8244
8245   DebugLoc dl = Op0.getDebugLoc();
8246   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8247 }
8248
8249 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8250 /// if it's possible.
8251 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8252                                      DebugLoc dl, SelectionDAG &DAG) const {
8253   SDValue Op0 = And.getOperand(0);
8254   SDValue Op1 = And.getOperand(1);
8255   if (Op0.getOpcode() == ISD::TRUNCATE)
8256     Op0 = Op0.getOperand(0);
8257   if (Op1.getOpcode() == ISD::TRUNCATE)
8258     Op1 = Op1.getOperand(0);
8259
8260   SDValue LHS, RHS;
8261   if (Op1.getOpcode() == ISD::SHL)
8262     std::swap(Op0, Op1);
8263   if (Op0.getOpcode() == ISD::SHL) {
8264     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8265       if (And00C->getZExtValue() == 1) {
8266         // If we looked past a truncate, check that it's only truncating away
8267         // known zeros.
8268         unsigned BitWidth = Op0.getValueSizeInBits();
8269         unsigned AndBitWidth = And.getValueSizeInBits();
8270         if (BitWidth > AndBitWidth) {
8271           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8272           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8273           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8274             return SDValue();
8275         }
8276         LHS = Op1;
8277         RHS = Op0.getOperand(1);
8278       }
8279   } else if (Op1.getOpcode() == ISD::Constant) {
8280     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8281     SDValue AndLHS = Op0;
8282     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8283       LHS = AndLHS.getOperand(0);
8284       RHS = AndLHS.getOperand(1);
8285     }
8286   }
8287
8288   if (LHS.getNode()) {
8289     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8290     // instruction.  Since the shift amount is in-range-or-undefined, we know
8291     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8292     // the encoding for the i16 version is larger than the i32 version.
8293     // Also promote i16 to i32 for performance / code size reason.
8294     if (LHS.getValueType() == MVT::i8 ||
8295         LHS.getValueType() == MVT::i16)
8296       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8297
8298     // If the operand types disagree, extend the shift amount to match.  Since
8299     // BT ignores high bits (like shifts) we can use anyextend.
8300     if (LHS.getValueType() != RHS.getValueType())
8301       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8302
8303     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8304     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8305     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8306                        DAG.getConstant(Cond, MVT::i8), BT);
8307   }
8308
8309   return SDValue();
8310 }
8311
8312 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8313   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8314   SDValue Op0 = Op.getOperand(0);
8315   SDValue Op1 = Op.getOperand(1);
8316   DebugLoc dl = Op.getDebugLoc();
8317   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8318
8319   // Optimize to BT if possible.
8320   // Lower (X & (1 << N)) == 0 to BT(X, N).
8321   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8322   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8323   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8324       Op1.getOpcode() == ISD::Constant &&
8325       cast<ConstantSDNode>(Op1)->isNullValue() &&
8326       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8327     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8328     if (NewSetCC.getNode())
8329       return NewSetCC;
8330   }
8331
8332   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8333   // these.
8334   if (Op1.getOpcode() == ISD::Constant &&
8335       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8336        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8337       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8338
8339     // If the input is a setcc, then reuse the input setcc or use a new one with
8340     // the inverted condition.
8341     if (Op0.getOpcode() == X86ISD::SETCC) {
8342       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8343       bool Invert = (CC == ISD::SETNE) ^
8344         cast<ConstantSDNode>(Op1)->isNullValue();
8345       if (!Invert) return Op0;
8346
8347       CCode = X86::GetOppositeBranchCondition(CCode);
8348       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8349                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8350     }
8351   }
8352
8353   bool isFP = Op1.getValueType().isFloatingPoint();
8354   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8355   if (X86CC == X86::COND_INVALID)
8356     return SDValue();
8357
8358   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8359   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8360                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8361 }
8362
8363 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8364 // ones, and then concatenate the result back.
8365 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8366   EVT VT = Op.getValueType();
8367
8368   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::VSETCC &&
8369          "Unsupported value type for operation");
8370
8371   int NumElems = VT.getVectorNumElements();
8372   DebugLoc dl = Op.getDebugLoc();
8373   SDValue CC = Op.getOperand(2);
8374   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8375   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8376
8377   // Extract the LHS vectors
8378   SDValue LHS = Op.getOperand(0);
8379   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8380   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8381
8382   // Extract the RHS vectors
8383   SDValue RHS = Op.getOperand(1);
8384   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8385   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8386
8387   // Issue the operation on the smaller types and concatenate the result back
8388   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8389   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8390   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8391                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8392                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8393 }
8394
8395
8396 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8397   SDValue Cond;
8398   SDValue Op0 = Op.getOperand(0);
8399   SDValue Op1 = Op.getOperand(1);
8400   SDValue CC = Op.getOperand(2);
8401   EVT VT = Op.getValueType();
8402   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8403   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8404   DebugLoc dl = Op.getDebugLoc();
8405
8406   if (isFP) {
8407     unsigned SSECC = 8;
8408     EVT EltVT = Op0.getValueType().getVectorElementType();
8409     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8410
8411     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8412     bool Swap = false;
8413
8414     switch (SetCCOpcode) {
8415     default: break;
8416     case ISD::SETOEQ:
8417     case ISD::SETEQ:  SSECC = 0; break;
8418     case ISD::SETOGT:
8419     case ISD::SETGT: Swap = true; // Fallthrough
8420     case ISD::SETLT:
8421     case ISD::SETOLT: SSECC = 1; break;
8422     case ISD::SETOGE:
8423     case ISD::SETGE: Swap = true; // Fallthrough
8424     case ISD::SETLE:
8425     case ISD::SETOLE: SSECC = 2; break;
8426     case ISD::SETUO:  SSECC = 3; break;
8427     case ISD::SETUNE:
8428     case ISD::SETNE:  SSECC = 4; break;
8429     case ISD::SETULE: Swap = true;
8430     case ISD::SETUGE: SSECC = 5; break;
8431     case ISD::SETULT: Swap = true;
8432     case ISD::SETUGT: SSECC = 6; break;
8433     case ISD::SETO:   SSECC = 7; break;
8434     }
8435     if (Swap)
8436       std::swap(Op0, Op1);
8437
8438     // In the two special cases we can't handle, emit two comparisons.
8439     if (SSECC == 8) {
8440       if (SetCCOpcode == ISD::SETUEQ) {
8441         SDValue UNORD, EQ;
8442         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8443         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8444         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8445       }
8446       else if (SetCCOpcode == ISD::SETONE) {
8447         SDValue ORD, NEQ;
8448         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8449         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8450         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8451       }
8452       llvm_unreachable("Illegal FP comparison");
8453     }
8454     // Handle all other FP comparisons here.
8455     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8456   }
8457
8458   // Break 256-bit integer vector compare into smaller ones.
8459   if (!isFP && VT.getSizeInBits() == 256)
8460     return Lower256IntVETCC(Op, DAG);
8461
8462   // We are handling one of the integer comparisons here.  Since SSE only has
8463   // GT and EQ comparisons for integer, swapping operands and multiple
8464   // operations may be required for some comparisons.
8465   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8466   bool Swap = false, Invert = false, FlipSigns = false;
8467
8468   switch (VT.getSimpleVT().SimpleTy) {
8469   default: break;
8470   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8471   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8472   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8473   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8474   }
8475
8476   switch (SetCCOpcode) {
8477   default: break;
8478   case ISD::SETNE:  Invert = true;
8479   case ISD::SETEQ:  Opc = EQOpc; break;
8480   case ISD::SETLT:  Swap = true;
8481   case ISD::SETGT:  Opc = GTOpc; break;
8482   case ISD::SETGE:  Swap = true;
8483   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8484   case ISD::SETULT: Swap = true;
8485   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8486   case ISD::SETUGE: Swap = true;
8487   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8488   }
8489   if (Swap)
8490     std::swap(Op0, Op1);
8491
8492   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8493   // bits of the inputs before performing those operations.
8494   if (FlipSigns) {
8495     EVT EltVT = VT.getVectorElementType();
8496     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8497                                       EltVT);
8498     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8499     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8500                                     SignBits.size());
8501     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8502     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8503   }
8504
8505   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8506
8507   // If the logical-not of the result is required, perform that now.
8508   if (Invert)
8509     Result = DAG.getNOT(dl, Result, VT);
8510
8511   return Result;
8512 }
8513
8514 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8515 static bool isX86LogicalCmp(SDValue Op) {
8516   unsigned Opc = Op.getNode()->getOpcode();
8517   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8518     return true;
8519   if (Op.getResNo() == 1 &&
8520       (Opc == X86ISD::ADD ||
8521        Opc == X86ISD::SUB ||
8522        Opc == X86ISD::ADC ||
8523        Opc == X86ISD::SBB ||
8524        Opc == X86ISD::SMUL ||
8525        Opc == X86ISD::UMUL ||
8526        Opc == X86ISD::INC ||
8527        Opc == X86ISD::DEC ||
8528        Opc == X86ISD::OR ||
8529        Opc == X86ISD::XOR ||
8530        Opc == X86ISD::AND))
8531     return true;
8532
8533   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8534     return true;
8535
8536   return false;
8537 }
8538
8539 static bool isZero(SDValue V) {
8540   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8541   return C && C->isNullValue();
8542 }
8543
8544 static bool isAllOnes(SDValue V) {
8545   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8546   return C && C->isAllOnesValue();
8547 }
8548
8549 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8550   bool addTest = true;
8551   SDValue Cond  = Op.getOperand(0);
8552   SDValue Op1 = Op.getOperand(1);
8553   SDValue Op2 = Op.getOperand(2);
8554   DebugLoc DL = Op.getDebugLoc();
8555   SDValue CC;
8556
8557   if (Cond.getOpcode() == ISD::SETCC) {
8558     SDValue NewCond = LowerSETCC(Cond, DAG);
8559     if (NewCond.getNode())
8560       Cond = NewCond;
8561   }
8562
8563   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8564   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8565   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8566   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8567   if (Cond.getOpcode() == X86ISD::SETCC &&
8568       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8569       isZero(Cond.getOperand(1).getOperand(1))) {
8570     SDValue Cmp = Cond.getOperand(1);
8571
8572     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8573
8574     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8575         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8576       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8577
8578       SDValue CmpOp0 = Cmp.getOperand(0);
8579       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8580                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8581
8582       SDValue Res =   // Res = 0 or -1.
8583         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8584                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8585
8586       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8587         Res = DAG.getNOT(DL, Res, Res.getValueType());
8588
8589       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8590       if (N2C == 0 || !N2C->isNullValue())
8591         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8592       return Res;
8593     }
8594   }
8595
8596   // Look past (and (setcc_carry (cmp ...)), 1).
8597   if (Cond.getOpcode() == ISD::AND &&
8598       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8599     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8600     if (C && C->getAPIntValue() == 1)
8601       Cond = Cond.getOperand(0);
8602   }
8603
8604   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8605   // setting operand in place of the X86ISD::SETCC.
8606   if (Cond.getOpcode() == X86ISD::SETCC ||
8607       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8608     CC = Cond.getOperand(0);
8609
8610     SDValue Cmp = Cond.getOperand(1);
8611     unsigned Opc = Cmp.getOpcode();
8612     EVT VT = Op.getValueType();
8613
8614     bool IllegalFPCMov = false;
8615     if (VT.isFloatingPoint() && !VT.isVector() &&
8616         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8617       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8618
8619     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8620         Opc == X86ISD::BT) { // FIXME
8621       Cond = Cmp;
8622       addTest = false;
8623     }
8624   }
8625
8626   if (addTest) {
8627     // Look pass the truncate.
8628     if (Cond.getOpcode() == ISD::TRUNCATE)
8629       Cond = Cond.getOperand(0);
8630
8631     // We know the result of AND is compared against zero. Try to match
8632     // it to BT.
8633     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8634       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8635       if (NewSetCC.getNode()) {
8636         CC = NewSetCC.getOperand(0);
8637         Cond = NewSetCC.getOperand(1);
8638         addTest = false;
8639       }
8640     }
8641   }
8642
8643   if (addTest) {
8644     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8645     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8646   }
8647
8648   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8649   // a <  b ?  0 : -1 -> RES = setcc_carry
8650   // a >= b ? -1 :  0 -> RES = setcc_carry
8651   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8652   if (Cond.getOpcode() == X86ISD::CMP) {
8653     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8654
8655     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8656         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8657       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8658                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8659       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8660         return DAG.getNOT(DL, Res, Res.getValueType());
8661       return Res;
8662     }
8663   }
8664
8665   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8666   // condition is true.
8667   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8668   SDValue Ops[] = { Op2, Op1, CC, Cond };
8669   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8670 }
8671
8672 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8673 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8674 // from the AND / OR.
8675 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8676   Opc = Op.getOpcode();
8677   if (Opc != ISD::OR && Opc != ISD::AND)
8678     return false;
8679   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8680           Op.getOperand(0).hasOneUse() &&
8681           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8682           Op.getOperand(1).hasOneUse());
8683 }
8684
8685 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8686 // 1 and that the SETCC node has a single use.
8687 static bool isXor1OfSetCC(SDValue Op) {
8688   if (Op.getOpcode() != ISD::XOR)
8689     return false;
8690   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8691   if (N1C && N1C->getAPIntValue() == 1) {
8692     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8693       Op.getOperand(0).hasOneUse();
8694   }
8695   return false;
8696 }
8697
8698 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8699   bool addTest = true;
8700   SDValue Chain = Op.getOperand(0);
8701   SDValue Cond  = Op.getOperand(1);
8702   SDValue Dest  = Op.getOperand(2);
8703   DebugLoc dl = Op.getDebugLoc();
8704   SDValue CC;
8705
8706   if (Cond.getOpcode() == ISD::SETCC) {
8707     SDValue NewCond = LowerSETCC(Cond, DAG);
8708     if (NewCond.getNode())
8709       Cond = NewCond;
8710   }
8711 #if 0
8712   // FIXME: LowerXALUO doesn't handle these!!
8713   else if (Cond.getOpcode() == X86ISD::ADD  ||
8714            Cond.getOpcode() == X86ISD::SUB  ||
8715            Cond.getOpcode() == X86ISD::SMUL ||
8716            Cond.getOpcode() == X86ISD::UMUL)
8717     Cond = LowerXALUO(Cond, DAG);
8718 #endif
8719
8720   // Look pass (and (setcc_carry (cmp ...)), 1).
8721   if (Cond.getOpcode() == ISD::AND &&
8722       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8723     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8724     if (C && C->getAPIntValue() == 1)
8725       Cond = Cond.getOperand(0);
8726   }
8727
8728   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8729   // setting operand in place of the X86ISD::SETCC.
8730   if (Cond.getOpcode() == X86ISD::SETCC ||
8731       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8732     CC = Cond.getOperand(0);
8733
8734     SDValue Cmp = Cond.getOperand(1);
8735     unsigned Opc = Cmp.getOpcode();
8736     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8737     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8738       Cond = Cmp;
8739       addTest = false;
8740     } else {
8741       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8742       default: break;
8743       case X86::COND_O:
8744       case X86::COND_B:
8745         // These can only come from an arithmetic instruction with overflow,
8746         // e.g. SADDO, UADDO.
8747         Cond = Cond.getNode()->getOperand(1);
8748         addTest = false;
8749         break;
8750       }
8751     }
8752   } else {
8753     unsigned CondOpc;
8754     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8755       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8756       if (CondOpc == ISD::OR) {
8757         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8758         // two branches instead of an explicit OR instruction with a
8759         // separate test.
8760         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8761             isX86LogicalCmp(Cmp)) {
8762           CC = Cond.getOperand(0).getOperand(0);
8763           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8764                               Chain, Dest, CC, Cmp);
8765           CC = Cond.getOperand(1).getOperand(0);
8766           Cond = Cmp;
8767           addTest = false;
8768         }
8769       } else { // ISD::AND
8770         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8771         // two branches instead of an explicit AND instruction with a
8772         // separate test. However, we only do this if this block doesn't
8773         // have a fall-through edge, because this requires an explicit
8774         // jmp when the condition is false.
8775         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8776             isX86LogicalCmp(Cmp) &&
8777             Op.getNode()->hasOneUse()) {
8778           X86::CondCode CCode =
8779             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8780           CCode = X86::GetOppositeBranchCondition(CCode);
8781           CC = DAG.getConstant(CCode, MVT::i8);
8782           SDNode *User = *Op.getNode()->use_begin();
8783           // Look for an unconditional branch following this conditional branch.
8784           // We need this because we need to reverse the successors in order
8785           // to implement FCMP_OEQ.
8786           if (User->getOpcode() == ISD::BR) {
8787             SDValue FalseBB = User->getOperand(1);
8788             SDNode *NewBR =
8789               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8790             assert(NewBR == User);
8791             (void)NewBR;
8792             Dest = FalseBB;
8793
8794             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8795                                 Chain, Dest, CC, Cmp);
8796             X86::CondCode CCode =
8797               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8798             CCode = X86::GetOppositeBranchCondition(CCode);
8799             CC = DAG.getConstant(CCode, MVT::i8);
8800             Cond = Cmp;
8801             addTest = false;
8802           }
8803         }
8804       }
8805     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8806       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8807       // It should be transformed during dag combiner except when the condition
8808       // is set by a arithmetics with overflow node.
8809       X86::CondCode CCode =
8810         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8811       CCode = X86::GetOppositeBranchCondition(CCode);
8812       CC = DAG.getConstant(CCode, MVT::i8);
8813       Cond = Cond.getOperand(0).getOperand(1);
8814       addTest = false;
8815     }
8816   }
8817
8818   if (addTest) {
8819     // Look pass the truncate.
8820     if (Cond.getOpcode() == ISD::TRUNCATE)
8821       Cond = Cond.getOperand(0);
8822
8823     // We know the result of AND is compared against zero. Try to match
8824     // it to BT.
8825     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8826       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8827       if (NewSetCC.getNode()) {
8828         CC = NewSetCC.getOperand(0);
8829         Cond = NewSetCC.getOperand(1);
8830         addTest = false;
8831       }
8832     }
8833   }
8834
8835   if (addTest) {
8836     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8837     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8838   }
8839   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8840                      Chain, Dest, CC, Cond);
8841 }
8842
8843
8844 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8845 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8846 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8847 // that the guard pages used by the OS virtual memory manager are allocated in
8848 // correct sequence.
8849 SDValue
8850 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8851                                            SelectionDAG &DAG) const {
8852   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8853           EnableSegmentedStacks) &&
8854          "This should be used only on Windows targets or when segmented stacks "
8855          "are being used.");
8856   assert(!Subtarget->isTargetEnvMacho());
8857   DebugLoc dl = Op.getDebugLoc();
8858
8859   // Get the inputs.
8860   SDValue Chain = Op.getOperand(0);
8861   SDValue Size  = Op.getOperand(1);
8862   // FIXME: Ensure alignment here
8863
8864   bool Is64Bit = Subtarget->is64Bit();
8865   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8866
8867   if (EnableSegmentedStacks) {
8868     MachineFunction &MF = DAG.getMachineFunction();
8869     MachineRegisterInfo &MRI = MF.getRegInfo();
8870
8871     if (Is64Bit) {
8872       // The 64 bit implementation of segmented stacks needs to clobber both r10
8873       // r11. This makes it impossible to use it along with nested paramenters.
8874       const Function *F = MF.getFunction();
8875
8876       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8877            I != E; I++)
8878         if (I->hasNestAttr())
8879           report_fatal_error("Cannot use segmented stacks with functions that "
8880                              "have nested arguments.");
8881     }
8882
8883     const TargetRegisterClass *AddrRegClass =
8884       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8885     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8886     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8887     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8888                                 DAG.getRegister(Vreg, SPTy));
8889     SDValue Ops1[2] = { Value, Chain };
8890     return DAG.getMergeValues(Ops1, 2, dl);
8891   } else {
8892     SDValue Flag;
8893     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8894
8895     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8896     Flag = Chain.getValue(1);
8897     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8898
8899     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8900     Flag = Chain.getValue(1);
8901
8902     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8903
8904     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8905     return DAG.getMergeValues(Ops1, 2, dl);
8906   }
8907 }
8908
8909 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8910   MachineFunction &MF = DAG.getMachineFunction();
8911   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8912
8913   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8914   DebugLoc DL = Op.getDebugLoc();
8915
8916   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8917     // vastart just stores the address of the VarArgsFrameIndex slot into the
8918     // memory location argument.
8919     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8920                                    getPointerTy());
8921     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8922                         MachinePointerInfo(SV), false, false, 0);
8923   }
8924
8925   // __va_list_tag:
8926   //   gp_offset         (0 - 6 * 8)
8927   //   fp_offset         (48 - 48 + 8 * 16)
8928   //   overflow_arg_area (point to parameters coming in memory).
8929   //   reg_save_area
8930   SmallVector<SDValue, 8> MemOps;
8931   SDValue FIN = Op.getOperand(1);
8932   // Store gp_offset
8933   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8934                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8935                                                MVT::i32),
8936                                FIN, MachinePointerInfo(SV), false, false, 0);
8937   MemOps.push_back(Store);
8938
8939   // Store fp_offset
8940   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8941                     FIN, DAG.getIntPtrConstant(4));
8942   Store = DAG.getStore(Op.getOperand(0), DL,
8943                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8944                                        MVT::i32),
8945                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8946   MemOps.push_back(Store);
8947
8948   // Store ptr to overflow_arg_area
8949   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8950                     FIN, DAG.getIntPtrConstant(4));
8951   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8952                                     getPointerTy());
8953   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8954                        MachinePointerInfo(SV, 8),
8955                        false, false, 0);
8956   MemOps.push_back(Store);
8957
8958   // Store ptr to reg_save_area.
8959   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8960                     FIN, DAG.getIntPtrConstant(8));
8961   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8962                                     getPointerTy());
8963   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8964                        MachinePointerInfo(SV, 16), false, false, 0);
8965   MemOps.push_back(Store);
8966   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8967                      &MemOps[0], MemOps.size());
8968 }
8969
8970 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8971   assert(Subtarget->is64Bit() &&
8972          "LowerVAARG only handles 64-bit va_arg!");
8973   assert((Subtarget->isTargetLinux() ||
8974           Subtarget->isTargetDarwin()) &&
8975           "Unhandled target in LowerVAARG");
8976   assert(Op.getNode()->getNumOperands() == 4);
8977   SDValue Chain = Op.getOperand(0);
8978   SDValue SrcPtr = Op.getOperand(1);
8979   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8980   unsigned Align = Op.getConstantOperandVal(3);
8981   DebugLoc dl = Op.getDebugLoc();
8982
8983   EVT ArgVT = Op.getNode()->getValueType(0);
8984   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8985   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8986   uint8_t ArgMode;
8987
8988   // Decide which area this value should be read from.
8989   // TODO: Implement the AMD64 ABI in its entirety. This simple
8990   // selection mechanism works only for the basic types.
8991   if (ArgVT == MVT::f80) {
8992     llvm_unreachable("va_arg for f80 not yet implemented");
8993   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8994     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8995   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8996     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8997   } else {
8998     llvm_unreachable("Unhandled argument type in LowerVAARG");
8999   }
9000
9001   if (ArgMode == 2) {
9002     // Sanity Check: Make sure using fp_offset makes sense.
9003     assert(!UseSoftFloat &&
9004            !(DAG.getMachineFunction()
9005                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9006            Subtarget->hasXMM());
9007   }
9008
9009   // Insert VAARG_64 node into the DAG
9010   // VAARG_64 returns two values: Variable Argument Address, Chain
9011   SmallVector<SDValue, 11> InstOps;
9012   InstOps.push_back(Chain);
9013   InstOps.push_back(SrcPtr);
9014   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9015   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9016   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9017   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9018   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9019                                           VTs, &InstOps[0], InstOps.size(),
9020                                           MVT::i64,
9021                                           MachinePointerInfo(SV),
9022                                           /*Align=*/0,
9023                                           /*Volatile=*/false,
9024                                           /*ReadMem=*/true,
9025                                           /*WriteMem=*/true);
9026   Chain = VAARG.getValue(1);
9027
9028   // Load the next argument and return it
9029   return DAG.getLoad(ArgVT, dl,
9030                      Chain,
9031                      VAARG,
9032                      MachinePointerInfo(),
9033                      false, false, 0);
9034 }
9035
9036 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9037   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9038   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9039   SDValue Chain = Op.getOperand(0);
9040   SDValue DstPtr = Op.getOperand(1);
9041   SDValue SrcPtr = Op.getOperand(2);
9042   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9043   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9044   DebugLoc DL = Op.getDebugLoc();
9045
9046   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9047                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9048                        false,
9049                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9050 }
9051
9052 SDValue
9053 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9054   DebugLoc dl = Op.getDebugLoc();
9055   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9056   switch (IntNo) {
9057   default: return SDValue();    // Don't custom lower most intrinsics.
9058   // Comparison intrinsics.
9059   case Intrinsic::x86_sse_comieq_ss:
9060   case Intrinsic::x86_sse_comilt_ss:
9061   case Intrinsic::x86_sse_comile_ss:
9062   case Intrinsic::x86_sse_comigt_ss:
9063   case Intrinsic::x86_sse_comige_ss:
9064   case Intrinsic::x86_sse_comineq_ss:
9065   case Intrinsic::x86_sse_ucomieq_ss:
9066   case Intrinsic::x86_sse_ucomilt_ss:
9067   case Intrinsic::x86_sse_ucomile_ss:
9068   case Intrinsic::x86_sse_ucomigt_ss:
9069   case Intrinsic::x86_sse_ucomige_ss:
9070   case Intrinsic::x86_sse_ucomineq_ss:
9071   case Intrinsic::x86_sse2_comieq_sd:
9072   case Intrinsic::x86_sse2_comilt_sd:
9073   case Intrinsic::x86_sse2_comile_sd:
9074   case Intrinsic::x86_sse2_comigt_sd:
9075   case Intrinsic::x86_sse2_comige_sd:
9076   case Intrinsic::x86_sse2_comineq_sd:
9077   case Intrinsic::x86_sse2_ucomieq_sd:
9078   case Intrinsic::x86_sse2_ucomilt_sd:
9079   case Intrinsic::x86_sse2_ucomile_sd:
9080   case Intrinsic::x86_sse2_ucomigt_sd:
9081   case Intrinsic::x86_sse2_ucomige_sd:
9082   case Intrinsic::x86_sse2_ucomineq_sd: {
9083     unsigned Opc = 0;
9084     ISD::CondCode CC = ISD::SETCC_INVALID;
9085     switch (IntNo) {
9086     default: break;
9087     case Intrinsic::x86_sse_comieq_ss:
9088     case Intrinsic::x86_sse2_comieq_sd:
9089       Opc = X86ISD::COMI;
9090       CC = ISD::SETEQ;
9091       break;
9092     case Intrinsic::x86_sse_comilt_ss:
9093     case Intrinsic::x86_sse2_comilt_sd:
9094       Opc = X86ISD::COMI;
9095       CC = ISD::SETLT;
9096       break;
9097     case Intrinsic::x86_sse_comile_ss:
9098     case Intrinsic::x86_sse2_comile_sd:
9099       Opc = X86ISD::COMI;
9100       CC = ISD::SETLE;
9101       break;
9102     case Intrinsic::x86_sse_comigt_ss:
9103     case Intrinsic::x86_sse2_comigt_sd:
9104       Opc = X86ISD::COMI;
9105       CC = ISD::SETGT;
9106       break;
9107     case Intrinsic::x86_sse_comige_ss:
9108     case Intrinsic::x86_sse2_comige_sd:
9109       Opc = X86ISD::COMI;
9110       CC = ISD::SETGE;
9111       break;
9112     case Intrinsic::x86_sse_comineq_ss:
9113     case Intrinsic::x86_sse2_comineq_sd:
9114       Opc = X86ISD::COMI;
9115       CC = ISD::SETNE;
9116       break;
9117     case Intrinsic::x86_sse_ucomieq_ss:
9118     case Intrinsic::x86_sse2_ucomieq_sd:
9119       Opc = X86ISD::UCOMI;
9120       CC = ISD::SETEQ;
9121       break;
9122     case Intrinsic::x86_sse_ucomilt_ss:
9123     case Intrinsic::x86_sse2_ucomilt_sd:
9124       Opc = X86ISD::UCOMI;
9125       CC = ISD::SETLT;
9126       break;
9127     case Intrinsic::x86_sse_ucomile_ss:
9128     case Intrinsic::x86_sse2_ucomile_sd:
9129       Opc = X86ISD::UCOMI;
9130       CC = ISD::SETLE;
9131       break;
9132     case Intrinsic::x86_sse_ucomigt_ss:
9133     case Intrinsic::x86_sse2_ucomigt_sd:
9134       Opc = X86ISD::UCOMI;
9135       CC = ISD::SETGT;
9136       break;
9137     case Intrinsic::x86_sse_ucomige_ss:
9138     case Intrinsic::x86_sse2_ucomige_sd:
9139       Opc = X86ISD::UCOMI;
9140       CC = ISD::SETGE;
9141       break;
9142     case Intrinsic::x86_sse_ucomineq_ss:
9143     case Intrinsic::x86_sse2_ucomineq_sd:
9144       Opc = X86ISD::UCOMI;
9145       CC = ISD::SETNE;
9146       break;
9147     }
9148
9149     SDValue LHS = Op.getOperand(1);
9150     SDValue RHS = Op.getOperand(2);
9151     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9152     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9153     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9154     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9155                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9156     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9157   }
9158   // ptest and testp intrinsics. The intrinsic these come from are designed to
9159   // return an integer value, not just an instruction so lower it to the ptest
9160   // or testp pattern and a setcc for the result.
9161   case Intrinsic::x86_sse41_ptestz:
9162   case Intrinsic::x86_sse41_ptestc:
9163   case Intrinsic::x86_sse41_ptestnzc:
9164   case Intrinsic::x86_avx_ptestz_256:
9165   case Intrinsic::x86_avx_ptestc_256:
9166   case Intrinsic::x86_avx_ptestnzc_256:
9167   case Intrinsic::x86_avx_vtestz_ps:
9168   case Intrinsic::x86_avx_vtestc_ps:
9169   case Intrinsic::x86_avx_vtestnzc_ps:
9170   case Intrinsic::x86_avx_vtestz_pd:
9171   case Intrinsic::x86_avx_vtestc_pd:
9172   case Intrinsic::x86_avx_vtestnzc_pd:
9173   case Intrinsic::x86_avx_vtestz_ps_256:
9174   case Intrinsic::x86_avx_vtestc_ps_256:
9175   case Intrinsic::x86_avx_vtestnzc_ps_256:
9176   case Intrinsic::x86_avx_vtestz_pd_256:
9177   case Intrinsic::x86_avx_vtestc_pd_256:
9178   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9179     bool IsTestPacked = false;
9180     unsigned X86CC = 0;
9181     switch (IntNo) {
9182     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9183     case Intrinsic::x86_avx_vtestz_ps:
9184     case Intrinsic::x86_avx_vtestz_pd:
9185     case Intrinsic::x86_avx_vtestz_ps_256:
9186     case Intrinsic::x86_avx_vtestz_pd_256:
9187       IsTestPacked = true; // Fallthrough
9188     case Intrinsic::x86_sse41_ptestz:
9189     case Intrinsic::x86_avx_ptestz_256:
9190       // ZF = 1
9191       X86CC = X86::COND_E;
9192       break;
9193     case Intrinsic::x86_avx_vtestc_ps:
9194     case Intrinsic::x86_avx_vtestc_pd:
9195     case Intrinsic::x86_avx_vtestc_ps_256:
9196     case Intrinsic::x86_avx_vtestc_pd_256:
9197       IsTestPacked = true; // Fallthrough
9198     case Intrinsic::x86_sse41_ptestc:
9199     case Intrinsic::x86_avx_ptestc_256:
9200       // CF = 1
9201       X86CC = X86::COND_B;
9202       break;
9203     case Intrinsic::x86_avx_vtestnzc_ps:
9204     case Intrinsic::x86_avx_vtestnzc_pd:
9205     case Intrinsic::x86_avx_vtestnzc_ps_256:
9206     case Intrinsic::x86_avx_vtestnzc_pd_256:
9207       IsTestPacked = true; // Fallthrough
9208     case Intrinsic::x86_sse41_ptestnzc:
9209     case Intrinsic::x86_avx_ptestnzc_256:
9210       // ZF and CF = 0
9211       X86CC = X86::COND_A;
9212       break;
9213     }
9214
9215     SDValue LHS = Op.getOperand(1);
9216     SDValue RHS = Op.getOperand(2);
9217     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9218     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9219     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9220     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9221     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9222   }
9223
9224   // Fix vector shift instructions where the last operand is a non-immediate
9225   // i32 value.
9226   case Intrinsic::x86_sse2_pslli_w:
9227   case Intrinsic::x86_sse2_pslli_d:
9228   case Intrinsic::x86_sse2_pslli_q:
9229   case Intrinsic::x86_sse2_psrli_w:
9230   case Intrinsic::x86_sse2_psrli_d:
9231   case Intrinsic::x86_sse2_psrli_q:
9232   case Intrinsic::x86_sse2_psrai_w:
9233   case Intrinsic::x86_sse2_psrai_d:
9234   case Intrinsic::x86_mmx_pslli_w:
9235   case Intrinsic::x86_mmx_pslli_d:
9236   case Intrinsic::x86_mmx_pslli_q:
9237   case Intrinsic::x86_mmx_psrli_w:
9238   case Intrinsic::x86_mmx_psrli_d:
9239   case Intrinsic::x86_mmx_psrli_q:
9240   case Intrinsic::x86_mmx_psrai_w:
9241   case Intrinsic::x86_mmx_psrai_d: {
9242     SDValue ShAmt = Op.getOperand(2);
9243     if (isa<ConstantSDNode>(ShAmt))
9244       return SDValue();
9245
9246     unsigned NewIntNo = 0;
9247     EVT ShAmtVT = MVT::v4i32;
9248     switch (IntNo) {
9249     case Intrinsic::x86_sse2_pslli_w:
9250       NewIntNo = Intrinsic::x86_sse2_psll_w;
9251       break;
9252     case Intrinsic::x86_sse2_pslli_d:
9253       NewIntNo = Intrinsic::x86_sse2_psll_d;
9254       break;
9255     case Intrinsic::x86_sse2_pslli_q:
9256       NewIntNo = Intrinsic::x86_sse2_psll_q;
9257       break;
9258     case Intrinsic::x86_sse2_psrli_w:
9259       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9260       break;
9261     case Intrinsic::x86_sse2_psrli_d:
9262       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9263       break;
9264     case Intrinsic::x86_sse2_psrli_q:
9265       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9266       break;
9267     case Intrinsic::x86_sse2_psrai_w:
9268       NewIntNo = Intrinsic::x86_sse2_psra_w;
9269       break;
9270     case Intrinsic::x86_sse2_psrai_d:
9271       NewIntNo = Intrinsic::x86_sse2_psra_d;
9272       break;
9273     default: {
9274       ShAmtVT = MVT::v2i32;
9275       switch (IntNo) {
9276       case Intrinsic::x86_mmx_pslli_w:
9277         NewIntNo = Intrinsic::x86_mmx_psll_w;
9278         break;
9279       case Intrinsic::x86_mmx_pslli_d:
9280         NewIntNo = Intrinsic::x86_mmx_psll_d;
9281         break;
9282       case Intrinsic::x86_mmx_pslli_q:
9283         NewIntNo = Intrinsic::x86_mmx_psll_q;
9284         break;
9285       case Intrinsic::x86_mmx_psrli_w:
9286         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9287         break;
9288       case Intrinsic::x86_mmx_psrli_d:
9289         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9290         break;
9291       case Intrinsic::x86_mmx_psrli_q:
9292         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9293         break;
9294       case Intrinsic::x86_mmx_psrai_w:
9295         NewIntNo = Intrinsic::x86_mmx_psra_w;
9296         break;
9297       case Intrinsic::x86_mmx_psrai_d:
9298         NewIntNo = Intrinsic::x86_mmx_psra_d;
9299         break;
9300       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9301       }
9302       break;
9303     }
9304     }
9305
9306     // The vector shift intrinsics with scalars uses 32b shift amounts but
9307     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9308     // to be zero.
9309     SDValue ShOps[4];
9310     ShOps[0] = ShAmt;
9311     ShOps[1] = DAG.getConstant(0, MVT::i32);
9312     if (ShAmtVT == MVT::v4i32) {
9313       ShOps[2] = DAG.getUNDEF(MVT::i32);
9314       ShOps[3] = DAG.getUNDEF(MVT::i32);
9315       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9316     } else {
9317       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9318 // FIXME this must be lowered to get rid of the invalid type.
9319     }
9320
9321     EVT VT = Op.getValueType();
9322     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9323     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9324                        DAG.getConstant(NewIntNo, MVT::i32),
9325                        Op.getOperand(1), ShAmt);
9326   }
9327   }
9328 }
9329
9330 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9331                                            SelectionDAG &DAG) const {
9332   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9333   MFI->setReturnAddressIsTaken(true);
9334
9335   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9336   DebugLoc dl = Op.getDebugLoc();
9337
9338   if (Depth > 0) {
9339     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9340     SDValue Offset =
9341       DAG.getConstant(TD->getPointerSize(),
9342                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9343     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9344                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9345                                    FrameAddr, Offset),
9346                        MachinePointerInfo(), false, false, 0);
9347   }
9348
9349   // Just load the return address.
9350   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9351   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9352                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9353 }
9354
9355 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9356   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9357   MFI->setFrameAddressIsTaken(true);
9358
9359   EVT VT = Op.getValueType();
9360   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9361   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9362   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9363   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9364   while (Depth--)
9365     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9366                             MachinePointerInfo(),
9367                             false, false, 0);
9368   return FrameAddr;
9369 }
9370
9371 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9372                                                      SelectionDAG &DAG) const {
9373   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9374 }
9375
9376 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9377   MachineFunction &MF = DAG.getMachineFunction();
9378   SDValue Chain     = Op.getOperand(0);
9379   SDValue Offset    = Op.getOperand(1);
9380   SDValue Handler   = Op.getOperand(2);
9381   DebugLoc dl       = Op.getDebugLoc();
9382
9383   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9384                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9385                                      getPointerTy());
9386   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9387
9388   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9389                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9390   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9391   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9392                        false, false, 0);
9393   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9394   MF.getRegInfo().addLiveOut(StoreAddrReg);
9395
9396   return DAG.getNode(X86ISD::EH_RETURN, dl,
9397                      MVT::Other,
9398                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9399 }
9400
9401 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
9402                                              SelectionDAG &DAG) const {
9403   SDValue Root = Op.getOperand(0);
9404   SDValue Trmp = Op.getOperand(1); // trampoline
9405   SDValue FPtr = Op.getOperand(2); // nested function
9406   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9407   DebugLoc dl  = Op.getDebugLoc();
9408
9409   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9410
9411   if (Subtarget->is64Bit()) {
9412     SDValue OutChains[6];
9413
9414     // Large code-model.
9415     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9416     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9417
9418     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9419     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9420
9421     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9422
9423     // Load the pointer to the nested function into R11.
9424     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9425     SDValue Addr = Trmp;
9426     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9427                                 Addr, MachinePointerInfo(TrmpAddr),
9428                                 false, false, 0);
9429
9430     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9431                        DAG.getConstant(2, MVT::i64));
9432     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9433                                 MachinePointerInfo(TrmpAddr, 2),
9434                                 false, false, 2);
9435
9436     // Load the 'nest' parameter value into R10.
9437     // R10 is specified in X86CallingConv.td
9438     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9439     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9440                        DAG.getConstant(10, MVT::i64));
9441     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9442                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9443                                 false, false, 0);
9444
9445     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9446                        DAG.getConstant(12, MVT::i64));
9447     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9448                                 MachinePointerInfo(TrmpAddr, 12),
9449                                 false, false, 2);
9450
9451     // Jump to the nested function.
9452     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9454                        DAG.getConstant(20, MVT::i64));
9455     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9456                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9457                                 false, false, 0);
9458
9459     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9460     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9461                        DAG.getConstant(22, MVT::i64));
9462     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9463                                 MachinePointerInfo(TrmpAddr, 22),
9464                                 false, false, 0);
9465
9466     SDValue Ops[] =
9467       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
9468     return DAG.getMergeValues(Ops, 2, dl);
9469   } else {
9470     const Function *Func =
9471       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9472     CallingConv::ID CC = Func->getCallingConv();
9473     unsigned NestReg;
9474
9475     switch (CC) {
9476     default:
9477       llvm_unreachable("Unsupported calling convention");
9478     case CallingConv::C:
9479     case CallingConv::X86_StdCall: {
9480       // Pass 'nest' parameter in ECX.
9481       // Must be kept in sync with X86CallingConv.td
9482       NestReg = X86::ECX;
9483
9484       // Check that ECX wasn't needed by an 'inreg' parameter.
9485       FunctionType *FTy = Func->getFunctionType();
9486       const AttrListPtr &Attrs = Func->getAttributes();
9487
9488       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9489         unsigned InRegCount = 0;
9490         unsigned Idx = 1;
9491
9492         for (FunctionType::param_iterator I = FTy->param_begin(),
9493              E = FTy->param_end(); I != E; ++I, ++Idx)
9494           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9495             // FIXME: should only count parameters that are lowered to integers.
9496             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9497
9498         if (InRegCount > 2) {
9499           report_fatal_error("Nest register in use - reduce number of inreg"
9500                              " parameters!");
9501         }
9502       }
9503       break;
9504     }
9505     case CallingConv::X86_FastCall:
9506     case CallingConv::X86_ThisCall:
9507     case CallingConv::Fast:
9508       // Pass 'nest' parameter in EAX.
9509       // Must be kept in sync with X86CallingConv.td
9510       NestReg = X86::EAX;
9511       break;
9512     }
9513
9514     SDValue OutChains[4];
9515     SDValue Addr, Disp;
9516
9517     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9518                        DAG.getConstant(10, MVT::i32));
9519     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9520
9521     // This is storing the opcode for MOV32ri.
9522     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9523     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9524     OutChains[0] = DAG.getStore(Root, dl,
9525                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9526                                 Trmp, MachinePointerInfo(TrmpAddr),
9527                                 false, false, 0);
9528
9529     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9530                        DAG.getConstant(1, MVT::i32));
9531     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9532                                 MachinePointerInfo(TrmpAddr, 1),
9533                                 false, false, 1);
9534
9535     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9536     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9537                        DAG.getConstant(5, MVT::i32));
9538     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9539                                 MachinePointerInfo(TrmpAddr, 5),
9540                                 false, false, 1);
9541
9542     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9543                        DAG.getConstant(6, MVT::i32));
9544     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9545                                 MachinePointerInfo(TrmpAddr, 6),
9546                                 false, false, 1);
9547
9548     SDValue Ops[] =
9549       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
9550     return DAG.getMergeValues(Ops, 2, dl);
9551   }
9552 }
9553
9554 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9555                                             SelectionDAG &DAG) const {
9556   /*
9557    The rounding mode is in bits 11:10 of FPSR, and has the following
9558    settings:
9559      00 Round to nearest
9560      01 Round to -inf
9561      10 Round to +inf
9562      11 Round to 0
9563
9564   FLT_ROUNDS, on the other hand, expects the following:
9565     -1 Undefined
9566      0 Round to 0
9567      1 Round to nearest
9568      2 Round to +inf
9569      3 Round to -inf
9570
9571   To perform the conversion, we do:
9572     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9573   */
9574
9575   MachineFunction &MF = DAG.getMachineFunction();
9576   const TargetMachine &TM = MF.getTarget();
9577   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9578   unsigned StackAlignment = TFI.getStackAlignment();
9579   EVT VT = Op.getValueType();
9580   DebugLoc DL = Op.getDebugLoc();
9581
9582   // Save FP Control Word to stack slot
9583   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9584   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9585
9586
9587   MachineMemOperand *MMO =
9588    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9589                            MachineMemOperand::MOStore, 2, 2);
9590
9591   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9592   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9593                                           DAG.getVTList(MVT::Other),
9594                                           Ops, 2, MVT::i16, MMO);
9595
9596   // Load FP Control Word from stack slot
9597   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9598                             MachinePointerInfo(), false, false, 0);
9599
9600   // Transform as necessary
9601   SDValue CWD1 =
9602     DAG.getNode(ISD::SRL, DL, MVT::i16,
9603                 DAG.getNode(ISD::AND, DL, MVT::i16,
9604                             CWD, DAG.getConstant(0x800, MVT::i16)),
9605                 DAG.getConstant(11, MVT::i8));
9606   SDValue CWD2 =
9607     DAG.getNode(ISD::SRL, DL, MVT::i16,
9608                 DAG.getNode(ISD::AND, DL, MVT::i16,
9609                             CWD, DAG.getConstant(0x400, MVT::i16)),
9610                 DAG.getConstant(9, MVT::i8));
9611
9612   SDValue RetVal =
9613     DAG.getNode(ISD::AND, DL, MVT::i16,
9614                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9615                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9616                             DAG.getConstant(1, MVT::i16)),
9617                 DAG.getConstant(3, MVT::i16));
9618
9619
9620   return DAG.getNode((VT.getSizeInBits() < 16 ?
9621                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9622 }
9623
9624 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9625   EVT VT = Op.getValueType();
9626   EVT OpVT = VT;
9627   unsigned NumBits = VT.getSizeInBits();
9628   DebugLoc dl = Op.getDebugLoc();
9629
9630   Op = Op.getOperand(0);
9631   if (VT == MVT::i8) {
9632     // Zero extend to i32 since there is not an i8 bsr.
9633     OpVT = MVT::i32;
9634     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9635   }
9636
9637   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9638   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9639   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9640
9641   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9642   SDValue Ops[] = {
9643     Op,
9644     DAG.getConstant(NumBits+NumBits-1, OpVT),
9645     DAG.getConstant(X86::COND_E, MVT::i8),
9646     Op.getValue(1)
9647   };
9648   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9649
9650   // Finally xor with NumBits-1.
9651   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9652
9653   if (VT == MVT::i8)
9654     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9655   return Op;
9656 }
9657
9658 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9659   EVT VT = Op.getValueType();
9660   EVT OpVT = VT;
9661   unsigned NumBits = VT.getSizeInBits();
9662   DebugLoc dl = Op.getDebugLoc();
9663
9664   Op = Op.getOperand(0);
9665   if (VT == MVT::i8) {
9666     OpVT = MVT::i32;
9667     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9668   }
9669
9670   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9671   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9672   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9673
9674   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9675   SDValue Ops[] = {
9676     Op,
9677     DAG.getConstant(NumBits, OpVT),
9678     DAG.getConstant(X86::COND_E, MVT::i8),
9679     Op.getValue(1)
9680   };
9681   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9682
9683   if (VT == MVT::i8)
9684     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9685   return Op;
9686 }
9687
9688 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9689 // ones, and then concatenate the result back.
9690 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9691   EVT VT = Op.getValueType();
9692
9693   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9694          "Unsupported value type for operation");
9695
9696   int NumElems = VT.getVectorNumElements();
9697   DebugLoc dl = Op.getDebugLoc();
9698   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9699   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9700
9701   // Extract the LHS vectors
9702   SDValue LHS = Op.getOperand(0);
9703   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9704   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9705
9706   // Extract the RHS vectors
9707   SDValue RHS = Op.getOperand(1);
9708   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9709   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9710
9711   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9712   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9713
9714   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9715                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9716                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9717 }
9718
9719 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9720   assert(Op.getValueType().getSizeInBits() == 256 &&
9721          Op.getValueType().isInteger() &&
9722          "Only handle AVX 256-bit vector integer operation");
9723   return Lower256IntArith(Op, DAG);
9724 }
9725
9726 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9727   assert(Op.getValueType().getSizeInBits() == 256 &&
9728          Op.getValueType().isInteger() &&
9729          "Only handle AVX 256-bit vector integer operation");
9730   return Lower256IntArith(Op, DAG);
9731 }
9732
9733 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9734   EVT VT = Op.getValueType();
9735
9736   // Decompose 256-bit ops into smaller 128-bit ops.
9737   if (VT.getSizeInBits() == 256)
9738     return Lower256IntArith(Op, DAG);
9739
9740   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9741   DebugLoc dl = Op.getDebugLoc();
9742
9743   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9744   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9745   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9746   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9747   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9748   //
9749   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9750   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9751   //  return AloBlo + AloBhi + AhiBlo;
9752
9753   SDValue A = Op.getOperand(0);
9754   SDValue B = Op.getOperand(1);
9755
9756   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9757                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9758                        A, DAG.getConstant(32, MVT::i32));
9759   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9760                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9761                        B, DAG.getConstant(32, MVT::i32));
9762   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9763                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9764                        A, B);
9765   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9766                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9767                        A, Bhi);
9768   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9769                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9770                        Ahi, B);
9771   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9772                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9773                        AloBhi, DAG.getConstant(32, MVT::i32));
9774   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9775                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9776                        AhiBlo, DAG.getConstant(32, MVT::i32));
9777   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9778   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9779   return Res;
9780 }
9781
9782 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9783
9784   EVT VT = Op.getValueType();
9785   DebugLoc dl = Op.getDebugLoc();
9786   SDValue R = Op.getOperand(0);
9787   SDValue Amt = Op.getOperand(1);
9788   LLVMContext *Context = DAG.getContext();
9789
9790   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9791     return SDValue();
9792
9793   // Decompose 256-bit shifts into smaller 128-bit shifts.
9794   if (VT.getSizeInBits() == 256) {
9795     int NumElems = VT.getVectorNumElements();
9796     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9797     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9798
9799     // Extract the two vectors
9800     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9801     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9802                                      DAG, dl);
9803
9804     // Recreate the shift amount vectors
9805     SDValue Amt1, Amt2;
9806     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9807       // Constant shift amount
9808       SmallVector<SDValue, 4> Amt1Csts;
9809       SmallVector<SDValue, 4> Amt2Csts;
9810       for (int i = 0; i < NumElems/2; ++i)
9811         Amt1Csts.push_back(Amt->getOperand(i));
9812       for (int i = NumElems/2; i < NumElems; ++i)
9813         Amt2Csts.push_back(Amt->getOperand(i));
9814
9815       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9816                                  &Amt1Csts[0], NumElems/2);
9817       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9818                                  &Amt2Csts[0], NumElems/2);
9819     } else {
9820       // Variable shift amount
9821       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9822       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9823                                  DAG, dl);
9824     }
9825
9826     // Issue new vector shifts for the smaller types
9827     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9828     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9829
9830     // Concatenate the result back
9831     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9832   }
9833
9834   // Optimize shl/srl/sra with constant shift amount.
9835   if (isSplatVector(Amt.getNode())) {
9836     SDValue SclrAmt = Amt->getOperand(0);
9837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9838       uint64_t ShiftAmt = C->getZExtValue();
9839
9840       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9841        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9842                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9843                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9844
9845       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9846        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9847                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9848                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9849
9850       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9851        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9852                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9853                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9854
9855       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9856        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9857                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9858                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9859
9860       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9861        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9862                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9863                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9864
9865       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9866        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9867                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9868                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9869
9870       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9871        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9872                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9873                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9874
9875       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9876        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9877                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9878                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9879     }
9880   }
9881
9882   // Lower SHL with variable shift amount.
9883   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9884     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9885                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9886                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9887
9888     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9889
9890     std::vector<Constant*> CV(4, CI);
9891     Constant *C = ConstantVector::get(CV);
9892     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9893     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9894                                  MachinePointerInfo::getConstantPool(),
9895                                  false, false, 16);
9896
9897     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9898     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9899     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9900     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9901   }
9902   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9903     // a = a << 5;
9904     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9905                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9906                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9907
9908     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9909     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9910
9911     std::vector<Constant*> CVM1(16, CM1);
9912     std::vector<Constant*> CVM2(16, CM2);
9913     Constant *C = ConstantVector::get(CVM1);
9914     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9915     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9916                             MachinePointerInfo::getConstantPool(),
9917                             false, false, 16);
9918
9919     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9920     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9921     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9922                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9923                     DAG.getConstant(4, MVT::i32));
9924     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9925     // a += a
9926     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9927
9928     C = ConstantVector::get(CVM2);
9929     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9930     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9931                     MachinePointerInfo::getConstantPool(),
9932                     false, false, 16);
9933
9934     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9935     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9936     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9937                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9938                     DAG.getConstant(2, MVT::i32));
9939     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9940     // a += a
9941     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9942
9943     // return pblendv(r, r+r, a);
9944     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9945                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9946     return R;
9947   }
9948   return SDValue();
9949 }
9950
9951 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9952   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9953   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9954   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9955   // has only one use.
9956   SDNode *N = Op.getNode();
9957   SDValue LHS = N->getOperand(0);
9958   SDValue RHS = N->getOperand(1);
9959   unsigned BaseOp = 0;
9960   unsigned Cond = 0;
9961   DebugLoc DL = Op.getDebugLoc();
9962   switch (Op.getOpcode()) {
9963   default: llvm_unreachable("Unknown ovf instruction!");
9964   case ISD::SADDO:
9965     // A subtract of one will be selected as a INC. Note that INC doesn't
9966     // set CF, so we can't do this for UADDO.
9967     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9968       if (C->isOne()) {
9969         BaseOp = X86ISD::INC;
9970         Cond = X86::COND_O;
9971         break;
9972       }
9973     BaseOp = X86ISD::ADD;
9974     Cond = X86::COND_O;
9975     break;
9976   case ISD::UADDO:
9977     BaseOp = X86ISD::ADD;
9978     Cond = X86::COND_B;
9979     break;
9980   case ISD::SSUBO:
9981     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9982     // set CF, so we can't do this for USUBO.
9983     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9984       if (C->isOne()) {
9985         BaseOp = X86ISD::DEC;
9986         Cond = X86::COND_O;
9987         break;
9988       }
9989     BaseOp = X86ISD::SUB;
9990     Cond = X86::COND_O;
9991     break;
9992   case ISD::USUBO:
9993     BaseOp = X86ISD::SUB;
9994     Cond = X86::COND_B;
9995     break;
9996   case ISD::SMULO:
9997     BaseOp = X86ISD::SMUL;
9998     Cond = X86::COND_O;
9999     break;
10000   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10001     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10002                                  MVT::i32);
10003     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10004
10005     SDValue SetCC =
10006       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10007                   DAG.getConstant(X86::COND_O, MVT::i32),
10008                   SDValue(Sum.getNode(), 2));
10009
10010     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10011   }
10012   }
10013
10014   // Also sets EFLAGS.
10015   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10016   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10017
10018   SDValue SetCC =
10019     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10020                 DAG.getConstant(Cond, MVT::i32),
10021                 SDValue(Sum.getNode(), 1));
10022
10023   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10024 }
10025
10026 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10027   DebugLoc dl = Op.getDebugLoc();
10028   SDNode* Node = Op.getNode();
10029   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10030   EVT VT = Node->getValueType(0);
10031
10032   if (Subtarget->hasSSE2() && VT.isVector()) {
10033     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10034                         ExtraVT.getScalarType().getSizeInBits();
10035     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10036
10037     unsigned SHLIntrinsicsID = 0;
10038     unsigned SRAIntrinsicsID = 0;
10039     switch (VT.getSimpleVT().SimpleTy) {
10040       default:
10041         return SDValue();
10042       case MVT::v2i64: {
10043         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10044         SRAIntrinsicsID = 0;
10045         break;
10046       }
10047       case MVT::v4i32: {
10048         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10049         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10050         break;
10051       }
10052       case MVT::v8i16: {
10053         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10054         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10055         break;
10056       }
10057     }
10058
10059     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10060                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10061                          Node->getOperand(0), ShAmt);
10062
10063     // In case of 1 bit sext, no need to shr
10064     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10065
10066     if (SRAIntrinsicsID) {
10067       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10068                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10069                          Tmp1, ShAmt);
10070     }
10071     return Tmp1;
10072   }
10073
10074   return SDValue();
10075 }
10076
10077
10078 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10079   DebugLoc dl = Op.getDebugLoc();
10080
10081   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10082   // There isn't any reason to disable it if the target processor supports it.
10083   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10084     SDValue Chain = Op.getOperand(0);
10085     SDValue Zero = DAG.getConstant(0, MVT::i32);
10086     SDValue Ops[] = {
10087       DAG.getRegister(X86::ESP, MVT::i32), // Base
10088       DAG.getTargetConstant(1, MVT::i8),   // Scale
10089       DAG.getRegister(0, MVT::i32),        // Index
10090       DAG.getTargetConstant(0, MVT::i32),  // Disp
10091       DAG.getRegister(0, MVT::i32),        // Segment.
10092       Zero,
10093       Chain
10094     };
10095     SDNode *Res =
10096       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10097                           array_lengthof(Ops));
10098     return SDValue(Res, 0);
10099   }
10100
10101   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10102   if (!isDev)
10103     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10104
10105   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10106   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10107   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10108   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10109
10110   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10111   if (!Op1 && !Op2 && !Op3 && Op4)
10112     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10113
10114   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10115   if (Op1 && !Op2 && !Op3 && !Op4)
10116     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10117
10118   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10119   //           (MFENCE)>;
10120   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10121 }
10122
10123 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10124                                              SelectionDAG &DAG) const {
10125   DebugLoc dl = Op.getDebugLoc();
10126   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10127     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10128   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10129     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10130
10131   // The only fence that needs an instruction is a sequentially-consistent
10132   // cross-thread fence.
10133   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10134     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10135     // no-sse2). There isn't any reason to disable it if the target processor
10136     // supports it.
10137     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10138       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10139
10140     SDValue Chain = Op.getOperand(0);
10141     SDValue Zero = DAG.getConstant(0, MVT::i32);
10142     SDValue Ops[] = {
10143       DAG.getRegister(X86::ESP, MVT::i32), // Base
10144       DAG.getTargetConstant(1, MVT::i8),   // Scale
10145       DAG.getRegister(0, MVT::i32),        // Index
10146       DAG.getTargetConstant(0, MVT::i32),  // Disp
10147       DAG.getRegister(0, MVT::i32),        // Segment.
10148       Zero,
10149       Chain
10150     };
10151     SDNode *Res =
10152       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10153                          array_lengthof(Ops));
10154     return SDValue(Res, 0);
10155   }
10156
10157   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10158   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10159 }
10160
10161
10162 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10163   EVT T = Op.getValueType();
10164   DebugLoc DL = Op.getDebugLoc();
10165   unsigned Reg = 0;
10166   unsigned size = 0;
10167   switch(T.getSimpleVT().SimpleTy) {
10168   default:
10169     assert(false && "Invalid value type!");
10170   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10171   case MVT::i16: Reg = X86::AX;  size = 2; break;
10172   case MVT::i32: Reg = X86::EAX; size = 4; break;
10173   case MVT::i64:
10174     assert(Subtarget->is64Bit() && "Node not type legal!");
10175     Reg = X86::RAX; size = 8;
10176     break;
10177   }
10178   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10179                                     Op.getOperand(2), SDValue());
10180   SDValue Ops[] = { cpIn.getValue(0),
10181                     Op.getOperand(1),
10182                     Op.getOperand(3),
10183                     DAG.getTargetConstant(size, MVT::i8),
10184                     cpIn.getValue(1) };
10185   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10186   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10187   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10188                                            Ops, 5, T, MMO);
10189   SDValue cpOut =
10190     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10191   return cpOut;
10192 }
10193
10194 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10195                                                  SelectionDAG &DAG) const {
10196   assert(Subtarget->is64Bit() && "Result not type legalized?");
10197   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10198   SDValue TheChain = Op.getOperand(0);
10199   DebugLoc dl = Op.getDebugLoc();
10200   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10201   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10202   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10203                                    rax.getValue(2));
10204   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10205                             DAG.getConstant(32, MVT::i8));
10206   SDValue Ops[] = {
10207     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10208     rdx.getValue(1)
10209   };
10210   return DAG.getMergeValues(Ops, 2, dl);
10211 }
10212
10213 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10214                                             SelectionDAG &DAG) const {
10215   EVT SrcVT = Op.getOperand(0).getValueType();
10216   EVT DstVT = Op.getValueType();
10217   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10218          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10219   assert((DstVT == MVT::i64 ||
10220           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10221          "Unexpected custom BITCAST");
10222   // i64 <=> MMX conversions are Legal.
10223   if (SrcVT==MVT::i64 && DstVT.isVector())
10224     return Op;
10225   if (DstVT==MVT::i64 && SrcVT.isVector())
10226     return Op;
10227   // MMX <=> MMX conversions are Legal.
10228   if (SrcVT.isVector() && DstVT.isVector())
10229     return Op;
10230   // All other conversions need to be expanded.
10231   return SDValue();
10232 }
10233
10234 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10235   SDNode *Node = Op.getNode();
10236   DebugLoc dl = Node->getDebugLoc();
10237   EVT T = Node->getValueType(0);
10238   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10239                               DAG.getConstant(0, T), Node->getOperand(2));
10240   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10241                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10242                        Node->getOperand(0),
10243                        Node->getOperand(1), negOp,
10244                        cast<AtomicSDNode>(Node)->getSrcValue(),
10245                        cast<AtomicSDNode>(Node)->getAlignment(),
10246                        cast<AtomicSDNode>(Node)->getOrdering(),
10247                        cast<AtomicSDNode>(Node)->getSynchScope());
10248 }
10249
10250 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10251   SDNode *Node = Op.getNode();
10252   DebugLoc dl = Node->getDebugLoc();
10253   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10254
10255   // Convert seq_cst store -> xchg
10256   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10257   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10258   //        (The only way to get a 16-byte store is cmpxchg16b)
10259   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10260   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10261       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10262     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10263                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10264                                  Node->getOperand(0),
10265                                  Node->getOperand(1), Node->getOperand(2),
10266                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10267                                  cast<AtomicSDNode>(Node)->getOrdering(),
10268                                  cast<AtomicSDNode>(Node)->getSynchScope());
10269     return Swap.getValue(1);
10270   }
10271   // Other atomic stores have a simple pattern.
10272   return Op;
10273 }
10274
10275 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10276   EVT VT = Op.getNode()->getValueType(0);
10277
10278   // Let legalize expand this if it isn't a legal type yet.
10279   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10280     return SDValue();
10281
10282   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10283
10284   unsigned Opc;
10285   bool ExtraOp = false;
10286   switch (Op.getOpcode()) {
10287   default: assert(0 && "Invalid code");
10288   case ISD::ADDC: Opc = X86ISD::ADD; break;
10289   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10290   case ISD::SUBC: Opc = X86ISD::SUB; break;
10291   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10292   }
10293
10294   if (!ExtraOp)
10295     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10296                        Op.getOperand(1));
10297   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10298                      Op.getOperand(1), Op.getOperand(2));
10299 }
10300
10301 /// LowerOperation - Provide custom lowering hooks for some operations.
10302 ///
10303 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10304   switch (Op.getOpcode()) {
10305   default: llvm_unreachable("Should not custom lower this!");
10306   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10307   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10308   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10309   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10310   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10311   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10312   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10313   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10314   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10315   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10316   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10317   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10318   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10319   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10320   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10321   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10322   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10323   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10324   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10325   case ISD::SHL_PARTS:
10326   case ISD::SRA_PARTS:
10327   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10328   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10329   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10330   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10331   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10332   case ISD::FABS:               return LowerFABS(Op, DAG);
10333   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10334   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10335   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10336   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10337   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
10338   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10339   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10340   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10341   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10342   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10343   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10344   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10345   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10346   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10347   case ISD::FRAME_TO_ARGS_OFFSET:
10348                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10349   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10350   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10351   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
10352   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10353   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10354   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10355   case ISD::MUL:                return LowerMUL(Op, DAG);
10356   case ISD::SRA:
10357   case ISD::SRL:
10358   case ISD::SHL:                return LowerShift(Op, DAG);
10359   case ISD::SADDO:
10360   case ISD::UADDO:
10361   case ISD::SSUBO:
10362   case ISD::USUBO:
10363   case ISD::SMULO:
10364   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10365   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10366   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10367   case ISD::ADDC:
10368   case ISD::ADDE:
10369   case ISD::SUBC:
10370   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10371   case ISD::ADD:                return LowerADD(Op, DAG);
10372   case ISD::SUB:                return LowerSUB(Op, DAG);
10373   }
10374 }
10375
10376 static void ReplaceATOMIC_LOAD(SDNode *Node,
10377                                   SmallVectorImpl<SDValue> &Results,
10378                                   SelectionDAG &DAG) {
10379   DebugLoc dl = Node->getDebugLoc();
10380   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10381
10382   // Convert wide load -> cmpxchg8b/cmpxchg16b
10383   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10384   //        (The only way to get a 16-byte load is cmpxchg16b)
10385   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10386   SDValue Zero = DAG.getConstant(0, VT);
10387   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10388                                Node->getOperand(0),
10389                                Node->getOperand(1), Zero, Zero,
10390                                cast<AtomicSDNode>(Node)->getMemOperand(),
10391                                cast<AtomicSDNode>(Node)->getOrdering(),
10392                                cast<AtomicSDNode>(Node)->getSynchScope());
10393   Results.push_back(Swap.getValue(0));
10394   Results.push_back(Swap.getValue(1));
10395 }
10396
10397 void X86TargetLowering::
10398 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10399                         SelectionDAG &DAG, unsigned NewOp) const {
10400   EVT T = Node->getValueType(0);
10401   DebugLoc dl = Node->getDebugLoc();
10402   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10403
10404   SDValue Chain = Node->getOperand(0);
10405   SDValue In1 = Node->getOperand(1);
10406   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10407                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10408   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10409                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10410   SDValue Ops[] = { Chain, In1, In2L, In2H };
10411   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10412   SDValue Result =
10413     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10414                             cast<MemSDNode>(Node)->getMemOperand());
10415   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10416   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10417   Results.push_back(Result.getValue(2));
10418 }
10419
10420 /// ReplaceNodeResults - Replace a node with an illegal result type
10421 /// with a new node built out of custom code.
10422 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10423                                            SmallVectorImpl<SDValue>&Results,
10424                                            SelectionDAG &DAG) const {
10425   DebugLoc dl = N->getDebugLoc();
10426   switch (N->getOpcode()) {
10427   default:
10428     assert(false && "Do not know how to custom type legalize this operation!");
10429     return;
10430   case ISD::SIGN_EXTEND_INREG:
10431   case ISD::ADDC:
10432   case ISD::ADDE:
10433   case ISD::SUBC:
10434   case ISD::SUBE:
10435     // We don't want to expand or promote these.
10436     return;
10437   case ISD::FP_TO_SINT: {
10438     std::pair<SDValue,SDValue> Vals =
10439         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10440     SDValue FIST = Vals.first, StackSlot = Vals.second;
10441     if (FIST.getNode() != 0) {
10442       EVT VT = N->getValueType(0);
10443       // Return a load from the stack slot.
10444       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10445                                     MachinePointerInfo(), false, false, 0));
10446     }
10447     return;
10448   }
10449   case ISD::READCYCLECOUNTER: {
10450     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10451     SDValue TheChain = N->getOperand(0);
10452     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10453     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10454                                      rd.getValue(1));
10455     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10456                                      eax.getValue(2));
10457     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10458     SDValue Ops[] = { eax, edx };
10459     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10460     Results.push_back(edx.getValue(1));
10461     return;
10462   }
10463   case ISD::ATOMIC_CMP_SWAP: {
10464     EVT T = N->getValueType(0);
10465     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10466     bool Regs64bit = T == MVT::i128;
10467     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10468     SDValue cpInL, cpInH;
10469     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10470                         DAG.getConstant(0, HalfT));
10471     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10472                         DAG.getConstant(1, HalfT));
10473     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10474                              Regs64bit ? X86::RAX : X86::EAX,
10475                              cpInL, SDValue());
10476     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10477                              Regs64bit ? X86::RDX : X86::EDX,
10478                              cpInH, cpInL.getValue(1));
10479     SDValue swapInL, swapInH;
10480     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10481                           DAG.getConstant(0, HalfT));
10482     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10483                           DAG.getConstant(1, HalfT));
10484     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10485                                Regs64bit ? X86::RBX : X86::EBX,
10486                                swapInL, cpInH.getValue(1));
10487     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10488                                Regs64bit ? X86::RCX : X86::ECX, 
10489                                swapInH, swapInL.getValue(1));
10490     SDValue Ops[] = { swapInH.getValue(0),
10491                       N->getOperand(1),
10492                       swapInH.getValue(1) };
10493     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10494     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10495     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10496                                   X86ISD::LCMPXCHG8_DAG;
10497     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10498                                              Ops, 3, T, MMO);
10499     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10500                                         Regs64bit ? X86::RAX : X86::EAX,
10501                                         HalfT, Result.getValue(1));
10502     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10503                                         Regs64bit ? X86::RDX : X86::EDX,
10504                                         HalfT, cpOutL.getValue(2));
10505     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10506     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10507     Results.push_back(cpOutH.getValue(1));
10508     return;
10509   }
10510   case ISD::ATOMIC_LOAD_ADD:
10511     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10512     return;
10513   case ISD::ATOMIC_LOAD_AND:
10514     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10515     return;
10516   case ISD::ATOMIC_LOAD_NAND:
10517     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10518     return;
10519   case ISD::ATOMIC_LOAD_OR:
10520     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10521     return;
10522   case ISD::ATOMIC_LOAD_SUB:
10523     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10524     return;
10525   case ISD::ATOMIC_LOAD_XOR:
10526     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10527     return;
10528   case ISD::ATOMIC_SWAP:
10529     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10530     return;
10531   case ISD::ATOMIC_LOAD:
10532     ReplaceATOMIC_LOAD(N, Results, DAG);
10533   }
10534 }
10535
10536 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10537   switch (Opcode) {
10538   default: return NULL;
10539   case X86ISD::BSF:                return "X86ISD::BSF";
10540   case X86ISD::BSR:                return "X86ISD::BSR";
10541   case X86ISD::SHLD:               return "X86ISD::SHLD";
10542   case X86ISD::SHRD:               return "X86ISD::SHRD";
10543   case X86ISD::FAND:               return "X86ISD::FAND";
10544   case X86ISD::FOR:                return "X86ISD::FOR";
10545   case X86ISD::FXOR:               return "X86ISD::FXOR";
10546   case X86ISD::FSRL:               return "X86ISD::FSRL";
10547   case X86ISD::FILD:               return "X86ISD::FILD";
10548   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10549   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10550   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10551   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10552   case X86ISD::FLD:                return "X86ISD::FLD";
10553   case X86ISD::FST:                return "X86ISD::FST";
10554   case X86ISD::CALL:               return "X86ISD::CALL";
10555   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10556   case X86ISD::BT:                 return "X86ISD::BT";
10557   case X86ISD::CMP:                return "X86ISD::CMP";
10558   case X86ISD::COMI:               return "X86ISD::COMI";
10559   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10560   case X86ISD::SETCC:              return "X86ISD::SETCC";
10561   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10562   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10563   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10564   case X86ISD::CMOV:               return "X86ISD::CMOV";
10565   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10566   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10567   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10568   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10569   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10570   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10571   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10572   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10573   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10574   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10575   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10576   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10577   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10578   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10579   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10580   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10581   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10582   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
10583   case X86ISD::FMAX:               return "X86ISD::FMAX";
10584   case X86ISD::FMIN:               return "X86ISD::FMIN";
10585   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10586   case X86ISD::FRCP:               return "X86ISD::FRCP";
10587   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10588   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10589   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10590   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10591   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10592   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10593   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10594   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10595   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10596   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10597   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10598   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10599   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10600   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10601   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10602   case X86ISD::VSHL:               return "X86ISD::VSHL";
10603   case X86ISD::VSRL:               return "X86ISD::VSRL";
10604   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10605   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10606   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10607   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10608   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10609   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10610   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10611   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10612   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10613   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10614   case X86ISD::ADD:                return "X86ISD::ADD";
10615   case X86ISD::SUB:                return "X86ISD::SUB";
10616   case X86ISD::ADC:                return "X86ISD::ADC";
10617   case X86ISD::SBB:                return "X86ISD::SBB";
10618   case X86ISD::SMUL:               return "X86ISD::SMUL";
10619   case X86ISD::UMUL:               return "X86ISD::UMUL";
10620   case X86ISD::INC:                return "X86ISD::INC";
10621   case X86ISD::DEC:                return "X86ISD::DEC";
10622   case X86ISD::OR:                 return "X86ISD::OR";
10623   case X86ISD::XOR:                return "X86ISD::XOR";
10624   case X86ISD::AND:                return "X86ISD::AND";
10625   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10626   case X86ISD::PTEST:              return "X86ISD::PTEST";
10627   case X86ISD::TESTP:              return "X86ISD::TESTP";
10628   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10629   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10630   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10631   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10632   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10633   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10634   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10635   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10636   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10637   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10638   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10639   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10640   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10641   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10642   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10643   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10644   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10645   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10646   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10647   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10648   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10649   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10650   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10651   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10652   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10653   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10654   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10655   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10656   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10657   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10658   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10659   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10660   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10661   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10662   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10663   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10664   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10665   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10666   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10667   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10668   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10669   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10670   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10671   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10672   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10673   }
10674 }
10675
10676 // isLegalAddressingMode - Return true if the addressing mode represented
10677 // by AM is legal for this target, for a load/store of the specified type.
10678 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10679                                               Type *Ty) const {
10680   // X86 supports extremely general addressing modes.
10681   CodeModel::Model M = getTargetMachine().getCodeModel();
10682   Reloc::Model R = getTargetMachine().getRelocationModel();
10683
10684   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10685   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10686     return false;
10687
10688   if (AM.BaseGV) {
10689     unsigned GVFlags =
10690       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10691
10692     // If a reference to this global requires an extra load, we can't fold it.
10693     if (isGlobalStubReference(GVFlags))
10694       return false;
10695
10696     // If BaseGV requires a register for the PIC base, we cannot also have a
10697     // BaseReg specified.
10698     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10699       return false;
10700
10701     // If lower 4G is not available, then we must use rip-relative addressing.
10702     if ((M != CodeModel::Small || R != Reloc::Static) &&
10703         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10704       return false;
10705   }
10706
10707   switch (AM.Scale) {
10708   case 0:
10709   case 1:
10710   case 2:
10711   case 4:
10712   case 8:
10713     // These scales always work.
10714     break;
10715   case 3:
10716   case 5:
10717   case 9:
10718     // These scales are formed with basereg+scalereg.  Only accept if there is
10719     // no basereg yet.
10720     if (AM.HasBaseReg)
10721       return false;
10722     break;
10723   default:  // Other stuff never works.
10724     return false;
10725   }
10726
10727   return true;
10728 }
10729
10730
10731 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10732   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10733     return false;
10734   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10735   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10736   if (NumBits1 <= NumBits2)
10737     return false;
10738   return true;
10739 }
10740
10741 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10742   if (!VT1.isInteger() || !VT2.isInteger())
10743     return false;
10744   unsigned NumBits1 = VT1.getSizeInBits();
10745   unsigned NumBits2 = VT2.getSizeInBits();
10746   if (NumBits1 <= NumBits2)
10747     return false;
10748   return true;
10749 }
10750
10751 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10752   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10753   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10754 }
10755
10756 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10757   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10758   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10759 }
10760
10761 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10762   // i16 instructions are longer (0x66 prefix) and potentially slower.
10763   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10764 }
10765
10766 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10767 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10768 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10769 /// are assumed to be legal.
10770 bool
10771 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10772                                       EVT VT) const {
10773   // Very little shuffling can be done for 64-bit vectors right now.
10774   if (VT.getSizeInBits() == 64)
10775     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10776
10777   // FIXME: pshufb, blends, shifts.
10778   return (VT.getVectorNumElements() == 2 ||
10779           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10780           isMOVLMask(M, VT) ||
10781           isSHUFPMask(M, VT) ||
10782           isPSHUFDMask(M, VT) ||
10783           isPSHUFHWMask(M, VT) ||
10784           isPSHUFLWMask(M, VT) ||
10785           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10786           isUNPCKLMask(M, VT) ||
10787           isUNPCKHMask(M, VT) ||
10788           isUNPCKL_v_undef_Mask(M, VT) ||
10789           isUNPCKH_v_undef_Mask(M, VT));
10790 }
10791
10792 bool
10793 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10794                                           EVT VT) const {
10795   unsigned NumElts = VT.getVectorNumElements();
10796   // FIXME: This collection of masks seems suspect.
10797   if (NumElts == 2)
10798     return true;
10799   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10800     return (isMOVLMask(Mask, VT)  ||
10801             isCommutedMOVLMask(Mask, VT, true) ||
10802             isSHUFPMask(Mask, VT) ||
10803             isCommutedSHUFPMask(Mask, VT));
10804   }
10805   return false;
10806 }
10807
10808 //===----------------------------------------------------------------------===//
10809 //                           X86 Scheduler Hooks
10810 //===----------------------------------------------------------------------===//
10811
10812 // private utility function
10813 MachineBasicBlock *
10814 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10815                                                        MachineBasicBlock *MBB,
10816                                                        unsigned regOpc,
10817                                                        unsigned immOpc,
10818                                                        unsigned LoadOpc,
10819                                                        unsigned CXchgOpc,
10820                                                        unsigned notOpc,
10821                                                        unsigned EAXreg,
10822                                                        TargetRegisterClass *RC,
10823                                                        bool invSrc) const {
10824   // For the atomic bitwise operator, we generate
10825   //   thisMBB:
10826   //   newMBB:
10827   //     ld  t1 = [bitinstr.addr]
10828   //     op  t2 = t1, [bitinstr.val]
10829   //     mov EAX = t1
10830   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10831   //     bz  newMBB
10832   //     fallthrough -->nextMBB
10833   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10834   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10835   MachineFunction::iterator MBBIter = MBB;
10836   ++MBBIter;
10837
10838   /// First build the CFG
10839   MachineFunction *F = MBB->getParent();
10840   MachineBasicBlock *thisMBB = MBB;
10841   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10842   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10843   F->insert(MBBIter, newMBB);
10844   F->insert(MBBIter, nextMBB);
10845
10846   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10847   nextMBB->splice(nextMBB->begin(), thisMBB,
10848                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10849                   thisMBB->end());
10850   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10851
10852   // Update thisMBB to fall through to newMBB
10853   thisMBB->addSuccessor(newMBB);
10854
10855   // newMBB jumps to itself and fall through to nextMBB
10856   newMBB->addSuccessor(nextMBB);
10857   newMBB->addSuccessor(newMBB);
10858
10859   // Insert instructions into newMBB based on incoming instruction
10860   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10861          "unexpected number of operands");
10862   DebugLoc dl = bInstr->getDebugLoc();
10863   MachineOperand& destOper = bInstr->getOperand(0);
10864   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10865   int numArgs = bInstr->getNumOperands() - 1;
10866   for (int i=0; i < numArgs; ++i)
10867     argOpers[i] = &bInstr->getOperand(i+1);
10868
10869   // x86 address has 4 operands: base, index, scale, and displacement
10870   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10871   int valArgIndx = lastAddrIndx + 1;
10872
10873   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10874   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10875   for (int i=0; i <= lastAddrIndx; ++i)
10876     (*MIB).addOperand(*argOpers[i]);
10877
10878   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10879   if (invSrc) {
10880     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10881   }
10882   else
10883     tt = t1;
10884
10885   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10886   assert((argOpers[valArgIndx]->isReg() ||
10887           argOpers[valArgIndx]->isImm()) &&
10888          "invalid operand");
10889   if (argOpers[valArgIndx]->isReg())
10890     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10891   else
10892     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10893   MIB.addReg(tt);
10894   (*MIB).addOperand(*argOpers[valArgIndx]);
10895
10896   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10897   MIB.addReg(t1);
10898
10899   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10900   for (int i=0; i <= lastAddrIndx; ++i)
10901     (*MIB).addOperand(*argOpers[i]);
10902   MIB.addReg(t2);
10903   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10904   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10905                     bInstr->memoperands_end());
10906
10907   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10908   MIB.addReg(EAXreg);
10909
10910   // insert branch
10911   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10912
10913   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10914   return nextMBB;
10915 }
10916
10917 // private utility function:  64 bit atomics on 32 bit host.
10918 MachineBasicBlock *
10919 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10920                                                        MachineBasicBlock *MBB,
10921                                                        unsigned regOpcL,
10922                                                        unsigned regOpcH,
10923                                                        unsigned immOpcL,
10924                                                        unsigned immOpcH,
10925                                                        bool invSrc) const {
10926   // For the atomic bitwise operator, we generate
10927   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10928   //     ld t1,t2 = [bitinstr.addr]
10929   //   newMBB:
10930   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10931   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10932   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10933   //     mov ECX, EBX <- t5, t6
10934   //     mov EAX, EDX <- t1, t2
10935   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10936   //     mov t3, t4 <- EAX, EDX
10937   //     bz  newMBB
10938   //     result in out1, out2
10939   //     fallthrough -->nextMBB
10940
10941   const TargetRegisterClass *RC = X86::GR32RegisterClass;
10942   const unsigned LoadOpc = X86::MOV32rm;
10943   const unsigned NotOpc = X86::NOT32r;
10944   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10945   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10946   MachineFunction::iterator MBBIter = MBB;
10947   ++MBBIter;
10948
10949   /// First build the CFG
10950   MachineFunction *F = MBB->getParent();
10951   MachineBasicBlock *thisMBB = MBB;
10952   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10953   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10954   F->insert(MBBIter, newMBB);
10955   F->insert(MBBIter, nextMBB);
10956
10957   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10958   nextMBB->splice(nextMBB->begin(), thisMBB,
10959                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10960                   thisMBB->end());
10961   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10962
10963   // Update thisMBB to fall through to newMBB
10964   thisMBB->addSuccessor(newMBB);
10965
10966   // newMBB jumps to itself and fall through to nextMBB
10967   newMBB->addSuccessor(nextMBB);
10968   newMBB->addSuccessor(newMBB);
10969
10970   DebugLoc dl = bInstr->getDebugLoc();
10971   // Insert instructions into newMBB based on incoming instruction
10972   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10973   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10974          "unexpected number of operands");
10975   MachineOperand& dest1Oper = bInstr->getOperand(0);
10976   MachineOperand& dest2Oper = bInstr->getOperand(1);
10977   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10978   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10979     argOpers[i] = &bInstr->getOperand(i+2);
10980
10981     // We use some of the operands multiple times, so conservatively just
10982     // clear any kill flags that might be present.
10983     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10984       argOpers[i]->setIsKill(false);
10985   }
10986
10987   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10988   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10989
10990   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10991   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10992   for (int i=0; i <= lastAddrIndx; ++i)
10993     (*MIB).addOperand(*argOpers[i]);
10994   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10995   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10996   // add 4 to displacement.
10997   for (int i=0; i <= lastAddrIndx-2; ++i)
10998     (*MIB).addOperand(*argOpers[i]);
10999   MachineOperand newOp3 = *(argOpers[3]);
11000   if (newOp3.isImm())
11001     newOp3.setImm(newOp3.getImm()+4);
11002   else
11003     newOp3.setOffset(newOp3.getOffset()+4);
11004   (*MIB).addOperand(newOp3);
11005   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11006
11007   // t3/4 are defined later, at the bottom of the loop
11008   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11009   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11010   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11011     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11012   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11013     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11014
11015   // The subsequent operations should be using the destination registers of
11016   //the PHI instructions.
11017   if (invSrc) {
11018     t1 = F->getRegInfo().createVirtualRegister(RC);
11019     t2 = F->getRegInfo().createVirtualRegister(RC);
11020     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11021     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11022   } else {
11023     t1 = dest1Oper.getReg();
11024     t2 = dest2Oper.getReg();
11025   }
11026
11027   int valArgIndx = lastAddrIndx + 1;
11028   assert((argOpers[valArgIndx]->isReg() ||
11029           argOpers[valArgIndx]->isImm()) &&
11030          "invalid operand");
11031   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11032   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11033   if (argOpers[valArgIndx]->isReg())
11034     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11035   else
11036     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11037   if (regOpcL != X86::MOV32rr)
11038     MIB.addReg(t1);
11039   (*MIB).addOperand(*argOpers[valArgIndx]);
11040   assert(argOpers[valArgIndx + 1]->isReg() ==
11041          argOpers[valArgIndx]->isReg());
11042   assert(argOpers[valArgIndx + 1]->isImm() ==
11043          argOpers[valArgIndx]->isImm());
11044   if (argOpers[valArgIndx + 1]->isReg())
11045     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11046   else
11047     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11048   if (regOpcH != X86::MOV32rr)
11049     MIB.addReg(t2);
11050   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11051
11052   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11053   MIB.addReg(t1);
11054   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11055   MIB.addReg(t2);
11056
11057   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11058   MIB.addReg(t5);
11059   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11060   MIB.addReg(t6);
11061
11062   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11063   for (int i=0; i <= lastAddrIndx; ++i)
11064     (*MIB).addOperand(*argOpers[i]);
11065
11066   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11067   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11068                     bInstr->memoperands_end());
11069
11070   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11071   MIB.addReg(X86::EAX);
11072   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11073   MIB.addReg(X86::EDX);
11074
11075   // insert branch
11076   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11077
11078   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11079   return nextMBB;
11080 }
11081
11082 // private utility function
11083 MachineBasicBlock *
11084 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11085                                                       MachineBasicBlock *MBB,
11086                                                       unsigned cmovOpc) const {
11087   // For the atomic min/max operator, we generate
11088   //   thisMBB:
11089   //   newMBB:
11090   //     ld t1 = [min/max.addr]
11091   //     mov t2 = [min/max.val]
11092   //     cmp  t1, t2
11093   //     cmov[cond] t2 = t1
11094   //     mov EAX = t1
11095   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11096   //     bz   newMBB
11097   //     fallthrough -->nextMBB
11098   //
11099   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11100   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11101   MachineFunction::iterator MBBIter = MBB;
11102   ++MBBIter;
11103
11104   /// First build the CFG
11105   MachineFunction *F = MBB->getParent();
11106   MachineBasicBlock *thisMBB = MBB;
11107   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11108   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11109   F->insert(MBBIter, newMBB);
11110   F->insert(MBBIter, nextMBB);
11111
11112   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11113   nextMBB->splice(nextMBB->begin(), thisMBB,
11114                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11115                   thisMBB->end());
11116   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11117
11118   // Update thisMBB to fall through to newMBB
11119   thisMBB->addSuccessor(newMBB);
11120
11121   // newMBB jumps to newMBB and fall through to nextMBB
11122   newMBB->addSuccessor(nextMBB);
11123   newMBB->addSuccessor(newMBB);
11124
11125   DebugLoc dl = mInstr->getDebugLoc();
11126   // Insert instructions into newMBB based on incoming instruction
11127   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11128          "unexpected number of operands");
11129   MachineOperand& destOper = mInstr->getOperand(0);
11130   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11131   int numArgs = mInstr->getNumOperands() - 1;
11132   for (int i=0; i < numArgs; ++i)
11133     argOpers[i] = &mInstr->getOperand(i+1);
11134
11135   // x86 address has 4 operands: base, index, scale, and displacement
11136   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11137   int valArgIndx = lastAddrIndx + 1;
11138
11139   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11140   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11141   for (int i=0; i <= lastAddrIndx; ++i)
11142     (*MIB).addOperand(*argOpers[i]);
11143
11144   // We only support register and immediate values
11145   assert((argOpers[valArgIndx]->isReg() ||
11146           argOpers[valArgIndx]->isImm()) &&
11147          "invalid operand");
11148
11149   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11150   if (argOpers[valArgIndx]->isReg())
11151     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11152   else
11153     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11154   (*MIB).addOperand(*argOpers[valArgIndx]);
11155
11156   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11157   MIB.addReg(t1);
11158
11159   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11160   MIB.addReg(t1);
11161   MIB.addReg(t2);
11162
11163   // Generate movc
11164   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11165   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11166   MIB.addReg(t2);
11167   MIB.addReg(t1);
11168
11169   // Cmp and exchange if none has modified the memory location
11170   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11171   for (int i=0; i <= lastAddrIndx; ++i)
11172     (*MIB).addOperand(*argOpers[i]);
11173   MIB.addReg(t3);
11174   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11175   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11176                     mInstr->memoperands_end());
11177
11178   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11179   MIB.addReg(X86::EAX);
11180
11181   // insert branch
11182   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11183
11184   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11185   return nextMBB;
11186 }
11187
11188 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11189 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11190 // in the .td file.
11191 MachineBasicBlock *
11192 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11193                             unsigned numArgs, bool memArg) const {
11194   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11195          "Target must have SSE4.2 or AVX features enabled");
11196
11197   DebugLoc dl = MI->getDebugLoc();
11198   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11199   unsigned Opc;
11200   if (!Subtarget->hasAVX()) {
11201     if (memArg)
11202       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11203     else
11204       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11205   } else {
11206     if (memArg)
11207       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11208     else
11209       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11210   }
11211
11212   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11213   for (unsigned i = 0; i < numArgs; ++i) {
11214     MachineOperand &Op = MI->getOperand(i+1);
11215     if (!(Op.isReg() && Op.isImplicit()))
11216       MIB.addOperand(Op);
11217   }
11218   BuildMI(*BB, MI, dl,
11219     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11220              MI->getOperand(0).getReg())
11221     .addReg(X86::XMM0);
11222
11223   MI->eraseFromParent();
11224   return BB;
11225 }
11226
11227 MachineBasicBlock *
11228 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11229   DebugLoc dl = MI->getDebugLoc();
11230   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11231
11232   // Address into RAX/EAX, other two args into ECX, EDX.
11233   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11234   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11235   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11236   for (int i = 0; i < X86::AddrNumOperands; ++i)
11237     MIB.addOperand(MI->getOperand(i));
11238
11239   unsigned ValOps = X86::AddrNumOperands;
11240   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11241     .addReg(MI->getOperand(ValOps).getReg());
11242   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11243     .addReg(MI->getOperand(ValOps+1).getReg());
11244
11245   // The instruction doesn't actually take any operands though.
11246   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11247
11248   MI->eraseFromParent(); // The pseudo is gone now.
11249   return BB;
11250 }
11251
11252 MachineBasicBlock *
11253 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11254   DebugLoc dl = MI->getDebugLoc();
11255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11256
11257   // First arg in ECX, the second in EAX.
11258   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11259     .addReg(MI->getOperand(0).getReg());
11260   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11261     .addReg(MI->getOperand(1).getReg());
11262
11263   // The instruction doesn't actually take any operands though.
11264   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11265
11266   MI->eraseFromParent(); // The pseudo is gone now.
11267   return BB;
11268 }
11269
11270 MachineBasicBlock *
11271 X86TargetLowering::EmitVAARG64WithCustomInserter(
11272                    MachineInstr *MI,
11273                    MachineBasicBlock *MBB) const {
11274   // Emit va_arg instruction on X86-64.
11275
11276   // Operands to this pseudo-instruction:
11277   // 0  ) Output        : destination address (reg)
11278   // 1-5) Input         : va_list address (addr, i64mem)
11279   // 6  ) ArgSize       : Size (in bytes) of vararg type
11280   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11281   // 8  ) Align         : Alignment of type
11282   // 9  ) EFLAGS (implicit-def)
11283
11284   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11285   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11286
11287   unsigned DestReg = MI->getOperand(0).getReg();
11288   MachineOperand &Base = MI->getOperand(1);
11289   MachineOperand &Scale = MI->getOperand(2);
11290   MachineOperand &Index = MI->getOperand(3);
11291   MachineOperand &Disp = MI->getOperand(4);
11292   MachineOperand &Segment = MI->getOperand(5);
11293   unsigned ArgSize = MI->getOperand(6).getImm();
11294   unsigned ArgMode = MI->getOperand(7).getImm();
11295   unsigned Align = MI->getOperand(8).getImm();
11296
11297   // Memory Reference
11298   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11299   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11300   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11301
11302   // Machine Information
11303   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11304   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11305   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11306   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11307   DebugLoc DL = MI->getDebugLoc();
11308
11309   // struct va_list {
11310   //   i32   gp_offset
11311   //   i32   fp_offset
11312   //   i64   overflow_area (address)
11313   //   i64   reg_save_area (address)
11314   // }
11315   // sizeof(va_list) = 24
11316   // alignment(va_list) = 8
11317
11318   unsigned TotalNumIntRegs = 6;
11319   unsigned TotalNumXMMRegs = 8;
11320   bool UseGPOffset = (ArgMode == 1);
11321   bool UseFPOffset = (ArgMode == 2);
11322   unsigned MaxOffset = TotalNumIntRegs * 8 +
11323                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11324
11325   /* Align ArgSize to a multiple of 8 */
11326   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11327   bool NeedsAlign = (Align > 8);
11328
11329   MachineBasicBlock *thisMBB = MBB;
11330   MachineBasicBlock *overflowMBB;
11331   MachineBasicBlock *offsetMBB;
11332   MachineBasicBlock *endMBB;
11333
11334   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11335   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11336   unsigned OffsetReg = 0;
11337
11338   if (!UseGPOffset && !UseFPOffset) {
11339     // If we only pull from the overflow region, we don't create a branch.
11340     // We don't need to alter control flow.
11341     OffsetDestReg = 0; // unused
11342     OverflowDestReg = DestReg;
11343
11344     offsetMBB = NULL;
11345     overflowMBB = thisMBB;
11346     endMBB = thisMBB;
11347   } else {
11348     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11349     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11350     // If not, pull from overflow_area. (branch to overflowMBB)
11351     //
11352     //       thisMBB
11353     //         |     .
11354     //         |        .
11355     //     offsetMBB   overflowMBB
11356     //         |        .
11357     //         |     .
11358     //        endMBB
11359
11360     // Registers for the PHI in endMBB
11361     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11362     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11363
11364     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11365     MachineFunction *MF = MBB->getParent();
11366     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11367     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11368     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11369
11370     MachineFunction::iterator MBBIter = MBB;
11371     ++MBBIter;
11372
11373     // Insert the new basic blocks
11374     MF->insert(MBBIter, offsetMBB);
11375     MF->insert(MBBIter, overflowMBB);
11376     MF->insert(MBBIter, endMBB);
11377
11378     // Transfer the remainder of MBB and its successor edges to endMBB.
11379     endMBB->splice(endMBB->begin(), thisMBB,
11380                     llvm::next(MachineBasicBlock::iterator(MI)),
11381                     thisMBB->end());
11382     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11383
11384     // Make offsetMBB and overflowMBB successors of thisMBB
11385     thisMBB->addSuccessor(offsetMBB);
11386     thisMBB->addSuccessor(overflowMBB);
11387
11388     // endMBB is a successor of both offsetMBB and overflowMBB
11389     offsetMBB->addSuccessor(endMBB);
11390     overflowMBB->addSuccessor(endMBB);
11391
11392     // Load the offset value into a register
11393     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11394     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11395       .addOperand(Base)
11396       .addOperand(Scale)
11397       .addOperand(Index)
11398       .addDisp(Disp, UseFPOffset ? 4 : 0)
11399       .addOperand(Segment)
11400       .setMemRefs(MMOBegin, MMOEnd);
11401
11402     // Check if there is enough room left to pull this argument.
11403     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11404       .addReg(OffsetReg)
11405       .addImm(MaxOffset + 8 - ArgSizeA8);
11406
11407     // Branch to "overflowMBB" if offset >= max
11408     // Fall through to "offsetMBB" otherwise
11409     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11410       .addMBB(overflowMBB);
11411   }
11412
11413   // In offsetMBB, emit code to use the reg_save_area.
11414   if (offsetMBB) {
11415     assert(OffsetReg != 0);
11416
11417     // Read the reg_save_area address.
11418     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11419     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11420       .addOperand(Base)
11421       .addOperand(Scale)
11422       .addOperand(Index)
11423       .addDisp(Disp, 16)
11424       .addOperand(Segment)
11425       .setMemRefs(MMOBegin, MMOEnd);
11426
11427     // Zero-extend the offset
11428     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11429       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11430         .addImm(0)
11431         .addReg(OffsetReg)
11432         .addImm(X86::sub_32bit);
11433
11434     // Add the offset to the reg_save_area to get the final address.
11435     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11436       .addReg(OffsetReg64)
11437       .addReg(RegSaveReg);
11438
11439     // Compute the offset for the next argument
11440     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11441     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11442       .addReg(OffsetReg)
11443       .addImm(UseFPOffset ? 16 : 8);
11444
11445     // Store it back into the va_list.
11446     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11447       .addOperand(Base)
11448       .addOperand(Scale)
11449       .addOperand(Index)
11450       .addDisp(Disp, UseFPOffset ? 4 : 0)
11451       .addOperand(Segment)
11452       .addReg(NextOffsetReg)
11453       .setMemRefs(MMOBegin, MMOEnd);
11454
11455     // Jump to endMBB
11456     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11457       .addMBB(endMBB);
11458   }
11459
11460   //
11461   // Emit code to use overflow area
11462   //
11463
11464   // Load the overflow_area address into a register.
11465   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11466   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11467     .addOperand(Base)
11468     .addOperand(Scale)
11469     .addOperand(Index)
11470     .addDisp(Disp, 8)
11471     .addOperand(Segment)
11472     .setMemRefs(MMOBegin, MMOEnd);
11473
11474   // If we need to align it, do so. Otherwise, just copy the address
11475   // to OverflowDestReg.
11476   if (NeedsAlign) {
11477     // Align the overflow address
11478     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11479     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11480
11481     // aligned_addr = (addr + (align-1)) & ~(align-1)
11482     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11483       .addReg(OverflowAddrReg)
11484       .addImm(Align-1);
11485
11486     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11487       .addReg(TmpReg)
11488       .addImm(~(uint64_t)(Align-1));
11489   } else {
11490     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11491       .addReg(OverflowAddrReg);
11492   }
11493
11494   // Compute the next overflow address after this argument.
11495   // (the overflow address should be kept 8-byte aligned)
11496   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11497   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11498     .addReg(OverflowDestReg)
11499     .addImm(ArgSizeA8);
11500
11501   // Store the new overflow address.
11502   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11503     .addOperand(Base)
11504     .addOperand(Scale)
11505     .addOperand(Index)
11506     .addDisp(Disp, 8)
11507     .addOperand(Segment)
11508     .addReg(NextAddrReg)
11509     .setMemRefs(MMOBegin, MMOEnd);
11510
11511   // If we branched, emit the PHI to the front of endMBB.
11512   if (offsetMBB) {
11513     BuildMI(*endMBB, endMBB->begin(), DL,
11514             TII->get(X86::PHI), DestReg)
11515       .addReg(OffsetDestReg).addMBB(offsetMBB)
11516       .addReg(OverflowDestReg).addMBB(overflowMBB);
11517   }
11518
11519   // Erase the pseudo instruction
11520   MI->eraseFromParent();
11521
11522   return endMBB;
11523 }
11524
11525 MachineBasicBlock *
11526 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11527                                                  MachineInstr *MI,
11528                                                  MachineBasicBlock *MBB) const {
11529   // Emit code to save XMM registers to the stack. The ABI says that the
11530   // number of registers to save is given in %al, so it's theoretically
11531   // possible to do an indirect jump trick to avoid saving all of them,
11532   // however this code takes a simpler approach and just executes all
11533   // of the stores if %al is non-zero. It's less code, and it's probably
11534   // easier on the hardware branch predictor, and stores aren't all that
11535   // expensive anyway.
11536
11537   // Create the new basic blocks. One block contains all the XMM stores,
11538   // and one block is the final destination regardless of whether any
11539   // stores were performed.
11540   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11541   MachineFunction *F = MBB->getParent();
11542   MachineFunction::iterator MBBIter = MBB;
11543   ++MBBIter;
11544   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11545   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11546   F->insert(MBBIter, XMMSaveMBB);
11547   F->insert(MBBIter, EndMBB);
11548
11549   // Transfer the remainder of MBB and its successor edges to EndMBB.
11550   EndMBB->splice(EndMBB->begin(), MBB,
11551                  llvm::next(MachineBasicBlock::iterator(MI)),
11552                  MBB->end());
11553   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11554
11555   // The original block will now fall through to the XMM save block.
11556   MBB->addSuccessor(XMMSaveMBB);
11557   // The XMMSaveMBB will fall through to the end block.
11558   XMMSaveMBB->addSuccessor(EndMBB);
11559
11560   // Now add the instructions.
11561   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11562   DebugLoc DL = MI->getDebugLoc();
11563
11564   unsigned CountReg = MI->getOperand(0).getReg();
11565   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11566   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11567
11568   if (!Subtarget->isTargetWin64()) {
11569     // If %al is 0, branch around the XMM save block.
11570     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11571     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11572     MBB->addSuccessor(EndMBB);
11573   }
11574
11575   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11576   // In the XMM save block, save all the XMM argument registers.
11577   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11578     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11579     MachineMemOperand *MMO =
11580       F->getMachineMemOperand(
11581           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11582         MachineMemOperand::MOStore,
11583         /*Size=*/16, /*Align=*/16);
11584     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11585       .addFrameIndex(RegSaveFrameIndex)
11586       .addImm(/*Scale=*/1)
11587       .addReg(/*IndexReg=*/0)
11588       .addImm(/*Disp=*/Offset)
11589       .addReg(/*Segment=*/0)
11590       .addReg(MI->getOperand(i).getReg())
11591       .addMemOperand(MMO);
11592   }
11593
11594   MI->eraseFromParent();   // The pseudo instruction is gone now.
11595
11596   return EndMBB;
11597 }
11598
11599 MachineBasicBlock *
11600 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11601                                      MachineBasicBlock *BB) const {
11602   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11603   DebugLoc DL = MI->getDebugLoc();
11604
11605   // To "insert" a SELECT_CC instruction, we actually have to insert the
11606   // diamond control-flow pattern.  The incoming instruction knows the
11607   // destination vreg to set, the condition code register to branch on, the
11608   // true/false values to select between, and a branch opcode to use.
11609   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11610   MachineFunction::iterator It = BB;
11611   ++It;
11612
11613   //  thisMBB:
11614   //  ...
11615   //   TrueVal = ...
11616   //   cmpTY ccX, r1, r2
11617   //   bCC copy1MBB
11618   //   fallthrough --> copy0MBB
11619   MachineBasicBlock *thisMBB = BB;
11620   MachineFunction *F = BB->getParent();
11621   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11622   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11623   F->insert(It, copy0MBB);
11624   F->insert(It, sinkMBB);
11625
11626   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11627   // live into the sink and copy blocks.
11628   const MachineFunction *MF = BB->getParent();
11629   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
11630   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
11631
11632   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
11633     const MachineOperand &MO = MI->getOperand(I);
11634     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
11635     unsigned Reg = MO.getReg();
11636     if (Reg != X86::EFLAGS) continue;
11637     copy0MBB->addLiveIn(Reg);
11638     sinkMBB->addLiveIn(Reg);
11639   }
11640
11641   // Transfer the remainder of BB and its successor edges to sinkMBB.
11642   sinkMBB->splice(sinkMBB->begin(), BB,
11643                   llvm::next(MachineBasicBlock::iterator(MI)),
11644                   BB->end());
11645   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11646
11647   // Add the true and fallthrough blocks as its successors.
11648   BB->addSuccessor(copy0MBB);
11649   BB->addSuccessor(sinkMBB);
11650
11651   // Create the conditional branch instruction.
11652   unsigned Opc =
11653     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11654   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11655
11656   //  copy0MBB:
11657   //   %FalseValue = ...
11658   //   # fallthrough to sinkMBB
11659   copy0MBB->addSuccessor(sinkMBB);
11660
11661   //  sinkMBB:
11662   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11663   //  ...
11664   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11665           TII->get(X86::PHI), MI->getOperand(0).getReg())
11666     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11667     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11668
11669   MI->eraseFromParent();   // The pseudo instruction is gone now.
11670   return sinkMBB;
11671 }
11672
11673 MachineBasicBlock *
11674 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11675                                         bool Is64Bit) const {
11676   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11677   DebugLoc DL = MI->getDebugLoc();
11678   MachineFunction *MF = BB->getParent();
11679   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11680
11681   assert(EnableSegmentedStacks);
11682
11683   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11684   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11685
11686   // BB:
11687   //  ... [Till the alloca]
11688   // If stacklet is not large enough, jump to mallocMBB
11689   //
11690   // bumpMBB:
11691   //  Allocate by subtracting from RSP
11692   //  Jump to continueMBB
11693   //
11694   // mallocMBB:
11695   //  Allocate by call to runtime
11696   //
11697   // continueMBB:
11698   //  ...
11699   //  [rest of original BB]
11700   //
11701
11702   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11703   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11704   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11705
11706   MachineRegisterInfo &MRI = MF->getRegInfo();
11707   const TargetRegisterClass *AddrRegClass =
11708     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11709
11710   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11711     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11712     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11713     sizeVReg = MI->getOperand(1).getReg(),
11714     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11715
11716   MachineFunction::iterator MBBIter = BB;
11717   ++MBBIter;
11718
11719   MF->insert(MBBIter, bumpMBB);
11720   MF->insert(MBBIter, mallocMBB);
11721   MF->insert(MBBIter, continueMBB);
11722
11723   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11724                       (MachineBasicBlock::iterator(MI)), BB->end());
11725   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11726
11727   // Add code to the main basic block to check if the stack limit has been hit,
11728   // and if so, jump to mallocMBB otherwise to bumpMBB.
11729   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11730   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11731     .addReg(tmpSPVReg).addReg(sizeVReg);
11732   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11733     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11734     .addReg(tmpSPVReg);
11735   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11736
11737   // bumpMBB simply decreases the stack pointer, since we know the current
11738   // stacklet has enough space.
11739   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11740     .addReg(tmpSPVReg);
11741   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11742     .addReg(tmpSPVReg);
11743   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11744
11745   // Calls into a routine in libgcc to allocate more space from the heap.
11746   if (Is64Bit) {
11747     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11748       .addReg(sizeVReg);
11749     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11750     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11751   } else {
11752     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11753       .addImm(12);
11754     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11755     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11756       .addExternalSymbol("__morestack_allocate_stack_space");
11757   }
11758
11759   if (!Is64Bit)
11760     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11761       .addImm(16);
11762
11763   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11764     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11765   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11766
11767   // Set up the CFG correctly.
11768   BB->addSuccessor(bumpMBB);
11769   BB->addSuccessor(mallocMBB);
11770   mallocMBB->addSuccessor(continueMBB);
11771   bumpMBB->addSuccessor(continueMBB);
11772
11773   // Take care of the PHI nodes.
11774   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11775           MI->getOperand(0).getReg())
11776     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11777     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11778
11779   // Delete the original pseudo instruction.
11780   MI->eraseFromParent();
11781
11782   // And we're done.
11783   return continueMBB;
11784 }
11785
11786 MachineBasicBlock *
11787 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11788                                           MachineBasicBlock *BB) const {
11789   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11790   DebugLoc DL = MI->getDebugLoc();
11791
11792   assert(!Subtarget->isTargetEnvMacho());
11793
11794   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11795   // non-trivial part is impdef of ESP.
11796
11797   if (Subtarget->isTargetWin64()) {
11798     if (Subtarget->isTargetCygMing()) {
11799       // ___chkstk(Mingw64):
11800       // Clobbers R10, R11, RAX and EFLAGS.
11801       // Updates RSP.
11802       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11803         .addExternalSymbol("___chkstk")
11804         .addReg(X86::RAX, RegState::Implicit)
11805         .addReg(X86::RSP, RegState::Implicit)
11806         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11807         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11808         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11809     } else {
11810       // __chkstk(MSVCRT): does not update stack pointer.
11811       // Clobbers R10, R11 and EFLAGS.
11812       // FIXME: RAX(allocated size) might be reused and not killed.
11813       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11814         .addExternalSymbol("__chkstk")
11815         .addReg(X86::RAX, RegState::Implicit)
11816         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11817       // RAX has the offset to subtracted from RSP.
11818       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11819         .addReg(X86::RSP)
11820         .addReg(X86::RAX);
11821     }
11822   } else {
11823     const char *StackProbeSymbol =
11824       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11825
11826     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11827       .addExternalSymbol(StackProbeSymbol)
11828       .addReg(X86::EAX, RegState::Implicit)
11829       .addReg(X86::ESP, RegState::Implicit)
11830       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11831       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11832       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11833   }
11834
11835   MI->eraseFromParent();   // The pseudo instruction is gone now.
11836   return BB;
11837 }
11838
11839 MachineBasicBlock *
11840 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11841                                       MachineBasicBlock *BB) const {
11842   // This is pretty easy.  We're taking the value that we received from
11843   // our load from the relocation, sticking it in either RDI (x86-64)
11844   // or EAX and doing an indirect call.  The return value will then
11845   // be in the normal return register.
11846   const X86InstrInfo *TII
11847     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11848   DebugLoc DL = MI->getDebugLoc();
11849   MachineFunction *F = BB->getParent();
11850
11851   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11852   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11853
11854   if (Subtarget->is64Bit()) {
11855     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11856                                       TII->get(X86::MOV64rm), X86::RDI)
11857     .addReg(X86::RIP)
11858     .addImm(0).addReg(0)
11859     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11860                       MI->getOperand(3).getTargetFlags())
11861     .addReg(0);
11862     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11863     addDirectMem(MIB, X86::RDI);
11864   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11865     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11866                                       TII->get(X86::MOV32rm), X86::EAX)
11867     .addReg(0)
11868     .addImm(0).addReg(0)
11869     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11870                       MI->getOperand(3).getTargetFlags())
11871     .addReg(0);
11872     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11873     addDirectMem(MIB, X86::EAX);
11874   } else {
11875     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11876                                       TII->get(X86::MOV32rm), X86::EAX)
11877     .addReg(TII->getGlobalBaseReg(F))
11878     .addImm(0).addReg(0)
11879     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11880                       MI->getOperand(3).getTargetFlags())
11881     .addReg(0);
11882     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11883     addDirectMem(MIB, X86::EAX);
11884   }
11885
11886   MI->eraseFromParent(); // The pseudo instruction is gone now.
11887   return BB;
11888 }
11889
11890 MachineBasicBlock *
11891 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11892                                                MachineBasicBlock *BB) const {
11893   switch (MI->getOpcode()) {
11894   default: assert(false && "Unexpected instr type to insert");
11895   case X86::TAILJMPd64:
11896   case X86::TAILJMPr64:
11897   case X86::TAILJMPm64:
11898     assert(!"TAILJMP64 would not be touched here.");
11899   case X86::TCRETURNdi64:
11900   case X86::TCRETURNri64:
11901   case X86::TCRETURNmi64:
11902     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11903     // On AMD64, additional defs should be added before register allocation.
11904     if (!Subtarget->isTargetWin64()) {
11905       MI->addRegisterDefined(X86::RSI);
11906       MI->addRegisterDefined(X86::RDI);
11907       MI->addRegisterDefined(X86::XMM6);
11908       MI->addRegisterDefined(X86::XMM7);
11909       MI->addRegisterDefined(X86::XMM8);
11910       MI->addRegisterDefined(X86::XMM9);
11911       MI->addRegisterDefined(X86::XMM10);
11912       MI->addRegisterDefined(X86::XMM11);
11913       MI->addRegisterDefined(X86::XMM12);
11914       MI->addRegisterDefined(X86::XMM13);
11915       MI->addRegisterDefined(X86::XMM14);
11916       MI->addRegisterDefined(X86::XMM15);
11917     }
11918     return BB;
11919   case X86::WIN_ALLOCA:
11920     return EmitLoweredWinAlloca(MI, BB);
11921   case X86::SEG_ALLOCA_32:
11922     return EmitLoweredSegAlloca(MI, BB, false);
11923   case X86::SEG_ALLOCA_64:
11924     return EmitLoweredSegAlloca(MI, BB, true);
11925   case X86::TLSCall_32:
11926   case X86::TLSCall_64:
11927     return EmitLoweredTLSCall(MI, BB);
11928   case X86::CMOV_GR8:
11929   case X86::CMOV_FR32:
11930   case X86::CMOV_FR64:
11931   case X86::CMOV_V4F32:
11932   case X86::CMOV_V2F64:
11933   case X86::CMOV_V2I64:
11934   case X86::CMOV_V8F32:
11935   case X86::CMOV_V4F64:
11936   case X86::CMOV_V4I64:
11937   case X86::CMOV_GR16:
11938   case X86::CMOV_GR32:
11939   case X86::CMOV_RFP32:
11940   case X86::CMOV_RFP64:
11941   case X86::CMOV_RFP80:
11942     return EmitLoweredSelect(MI, BB);
11943
11944   case X86::FP32_TO_INT16_IN_MEM:
11945   case X86::FP32_TO_INT32_IN_MEM:
11946   case X86::FP32_TO_INT64_IN_MEM:
11947   case X86::FP64_TO_INT16_IN_MEM:
11948   case X86::FP64_TO_INT32_IN_MEM:
11949   case X86::FP64_TO_INT64_IN_MEM:
11950   case X86::FP80_TO_INT16_IN_MEM:
11951   case X86::FP80_TO_INT32_IN_MEM:
11952   case X86::FP80_TO_INT64_IN_MEM: {
11953     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11954     DebugLoc DL = MI->getDebugLoc();
11955
11956     // Change the floating point control register to use "round towards zero"
11957     // mode when truncating to an integer value.
11958     MachineFunction *F = BB->getParent();
11959     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11960     addFrameReference(BuildMI(*BB, MI, DL,
11961                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
11962
11963     // Load the old value of the high byte of the control word...
11964     unsigned OldCW =
11965       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11966     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11967                       CWFrameIdx);
11968
11969     // Set the high part to be round to zero...
11970     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11971       .addImm(0xC7F);
11972
11973     // Reload the modified control word now...
11974     addFrameReference(BuildMI(*BB, MI, DL,
11975                               TII->get(X86::FLDCW16m)), CWFrameIdx);
11976
11977     // Restore the memory image of control word to original value
11978     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
11979       .addReg(OldCW);
11980
11981     // Get the X86 opcode to use.
11982     unsigned Opc;
11983     switch (MI->getOpcode()) {
11984     default: llvm_unreachable("illegal opcode!");
11985     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
11986     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
11987     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
11988     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
11989     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
11990     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
11991     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
11992     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
11993     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
11994     }
11995
11996     X86AddressMode AM;
11997     MachineOperand &Op = MI->getOperand(0);
11998     if (Op.isReg()) {
11999       AM.BaseType = X86AddressMode::RegBase;
12000       AM.Base.Reg = Op.getReg();
12001     } else {
12002       AM.BaseType = X86AddressMode::FrameIndexBase;
12003       AM.Base.FrameIndex = Op.getIndex();
12004     }
12005     Op = MI->getOperand(1);
12006     if (Op.isImm())
12007       AM.Scale = Op.getImm();
12008     Op = MI->getOperand(2);
12009     if (Op.isImm())
12010       AM.IndexReg = Op.getImm();
12011     Op = MI->getOperand(3);
12012     if (Op.isGlobal()) {
12013       AM.GV = Op.getGlobal();
12014     } else {
12015       AM.Disp = Op.getImm();
12016     }
12017     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12018                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12019
12020     // Reload the original control word now.
12021     addFrameReference(BuildMI(*BB, MI, DL,
12022                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12023
12024     MI->eraseFromParent();   // The pseudo instruction is gone now.
12025     return BB;
12026   }
12027     // String/text processing lowering.
12028   case X86::PCMPISTRM128REG:
12029   case X86::VPCMPISTRM128REG:
12030     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12031   case X86::PCMPISTRM128MEM:
12032   case X86::VPCMPISTRM128MEM:
12033     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12034   case X86::PCMPESTRM128REG:
12035   case X86::VPCMPESTRM128REG:
12036     return EmitPCMP(MI, BB, 5, false /* in mem */);
12037   case X86::PCMPESTRM128MEM:
12038   case X86::VPCMPESTRM128MEM:
12039     return EmitPCMP(MI, BB, 5, true /* in mem */);
12040
12041     // Thread synchronization.
12042   case X86::MONITOR:
12043     return EmitMonitor(MI, BB);
12044   case X86::MWAIT:
12045     return EmitMwait(MI, BB);
12046
12047     // Atomic Lowering.
12048   case X86::ATOMAND32:
12049     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12050                                                X86::AND32ri, X86::MOV32rm,
12051                                                X86::LCMPXCHG32,
12052                                                X86::NOT32r, X86::EAX,
12053                                                X86::GR32RegisterClass);
12054   case X86::ATOMOR32:
12055     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12056                                                X86::OR32ri, X86::MOV32rm,
12057                                                X86::LCMPXCHG32,
12058                                                X86::NOT32r, X86::EAX,
12059                                                X86::GR32RegisterClass);
12060   case X86::ATOMXOR32:
12061     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12062                                                X86::XOR32ri, X86::MOV32rm,
12063                                                X86::LCMPXCHG32,
12064                                                X86::NOT32r, X86::EAX,
12065                                                X86::GR32RegisterClass);
12066   case X86::ATOMNAND32:
12067     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12068                                                X86::AND32ri, X86::MOV32rm,
12069                                                X86::LCMPXCHG32,
12070                                                X86::NOT32r, X86::EAX,
12071                                                X86::GR32RegisterClass, true);
12072   case X86::ATOMMIN32:
12073     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12074   case X86::ATOMMAX32:
12075     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12076   case X86::ATOMUMIN32:
12077     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12078   case X86::ATOMUMAX32:
12079     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12080
12081   case X86::ATOMAND16:
12082     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12083                                                X86::AND16ri, X86::MOV16rm,
12084                                                X86::LCMPXCHG16,
12085                                                X86::NOT16r, X86::AX,
12086                                                X86::GR16RegisterClass);
12087   case X86::ATOMOR16:
12088     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12089                                                X86::OR16ri, X86::MOV16rm,
12090                                                X86::LCMPXCHG16,
12091                                                X86::NOT16r, X86::AX,
12092                                                X86::GR16RegisterClass);
12093   case X86::ATOMXOR16:
12094     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12095                                                X86::XOR16ri, X86::MOV16rm,
12096                                                X86::LCMPXCHG16,
12097                                                X86::NOT16r, X86::AX,
12098                                                X86::GR16RegisterClass);
12099   case X86::ATOMNAND16:
12100     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12101                                                X86::AND16ri, X86::MOV16rm,
12102                                                X86::LCMPXCHG16,
12103                                                X86::NOT16r, X86::AX,
12104                                                X86::GR16RegisterClass, true);
12105   case X86::ATOMMIN16:
12106     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12107   case X86::ATOMMAX16:
12108     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12109   case X86::ATOMUMIN16:
12110     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12111   case X86::ATOMUMAX16:
12112     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12113
12114   case X86::ATOMAND8:
12115     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12116                                                X86::AND8ri, X86::MOV8rm,
12117                                                X86::LCMPXCHG8,
12118                                                X86::NOT8r, X86::AL,
12119                                                X86::GR8RegisterClass);
12120   case X86::ATOMOR8:
12121     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12122                                                X86::OR8ri, X86::MOV8rm,
12123                                                X86::LCMPXCHG8,
12124                                                X86::NOT8r, X86::AL,
12125                                                X86::GR8RegisterClass);
12126   case X86::ATOMXOR8:
12127     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12128                                                X86::XOR8ri, X86::MOV8rm,
12129                                                X86::LCMPXCHG8,
12130                                                X86::NOT8r, X86::AL,
12131                                                X86::GR8RegisterClass);
12132   case X86::ATOMNAND8:
12133     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12134                                                X86::AND8ri, X86::MOV8rm,
12135                                                X86::LCMPXCHG8,
12136                                                X86::NOT8r, X86::AL,
12137                                                X86::GR8RegisterClass, true);
12138   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12139   // This group is for 64-bit host.
12140   case X86::ATOMAND64:
12141     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12142                                                X86::AND64ri32, X86::MOV64rm,
12143                                                X86::LCMPXCHG64,
12144                                                X86::NOT64r, X86::RAX,
12145                                                X86::GR64RegisterClass);
12146   case X86::ATOMOR64:
12147     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12148                                                X86::OR64ri32, X86::MOV64rm,
12149                                                X86::LCMPXCHG64,
12150                                                X86::NOT64r, X86::RAX,
12151                                                X86::GR64RegisterClass);
12152   case X86::ATOMXOR64:
12153     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12154                                                X86::XOR64ri32, X86::MOV64rm,
12155                                                X86::LCMPXCHG64,
12156                                                X86::NOT64r, X86::RAX,
12157                                                X86::GR64RegisterClass);
12158   case X86::ATOMNAND64:
12159     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12160                                                X86::AND64ri32, X86::MOV64rm,
12161                                                X86::LCMPXCHG64,
12162                                                X86::NOT64r, X86::RAX,
12163                                                X86::GR64RegisterClass, true);
12164   case X86::ATOMMIN64:
12165     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12166   case X86::ATOMMAX64:
12167     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12168   case X86::ATOMUMIN64:
12169     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12170   case X86::ATOMUMAX64:
12171     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12172
12173   // This group does 64-bit operations on a 32-bit host.
12174   case X86::ATOMAND6432:
12175     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12176                                                X86::AND32rr, X86::AND32rr,
12177                                                X86::AND32ri, X86::AND32ri,
12178                                                false);
12179   case X86::ATOMOR6432:
12180     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12181                                                X86::OR32rr, X86::OR32rr,
12182                                                X86::OR32ri, X86::OR32ri,
12183                                                false);
12184   case X86::ATOMXOR6432:
12185     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12186                                                X86::XOR32rr, X86::XOR32rr,
12187                                                X86::XOR32ri, X86::XOR32ri,
12188                                                false);
12189   case X86::ATOMNAND6432:
12190     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12191                                                X86::AND32rr, X86::AND32rr,
12192                                                X86::AND32ri, X86::AND32ri,
12193                                                true);
12194   case X86::ATOMADD6432:
12195     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12196                                                X86::ADD32rr, X86::ADC32rr,
12197                                                X86::ADD32ri, X86::ADC32ri,
12198                                                false);
12199   case X86::ATOMSUB6432:
12200     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12201                                                X86::SUB32rr, X86::SBB32rr,
12202                                                X86::SUB32ri, X86::SBB32ri,
12203                                                false);
12204   case X86::ATOMSWAP6432:
12205     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12206                                                X86::MOV32rr, X86::MOV32rr,
12207                                                X86::MOV32ri, X86::MOV32ri,
12208                                                false);
12209   case X86::VASTART_SAVE_XMM_REGS:
12210     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12211
12212   case X86::VAARG_64:
12213     return EmitVAARG64WithCustomInserter(MI, BB);
12214   }
12215 }
12216
12217 //===----------------------------------------------------------------------===//
12218 //                           X86 Optimization Hooks
12219 //===----------------------------------------------------------------------===//
12220
12221 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12222                                                        const APInt &Mask,
12223                                                        APInt &KnownZero,
12224                                                        APInt &KnownOne,
12225                                                        const SelectionDAG &DAG,
12226                                                        unsigned Depth) const {
12227   unsigned Opc = Op.getOpcode();
12228   assert((Opc >= ISD::BUILTIN_OP_END ||
12229           Opc == ISD::INTRINSIC_WO_CHAIN ||
12230           Opc == ISD::INTRINSIC_W_CHAIN ||
12231           Opc == ISD::INTRINSIC_VOID) &&
12232          "Should use MaskedValueIsZero if you don't know whether Op"
12233          " is a target node!");
12234
12235   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12236   switch (Opc) {
12237   default: break;
12238   case X86ISD::ADD:
12239   case X86ISD::SUB:
12240   case X86ISD::ADC:
12241   case X86ISD::SBB:
12242   case X86ISD::SMUL:
12243   case X86ISD::UMUL:
12244   case X86ISD::INC:
12245   case X86ISD::DEC:
12246   case X86ISD::OR:
12247   case X86ISD::XOR:
12248   case X86ISD::AND:
12249     // These nodes' second result is a boolean.
12250     if (Op.getResNo() == 0)
12251       break;
12252     // Fallthrough
12253   case X86ISD::SETCC:
12254     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12255                                        Mask.getBitWidth() - 1);
12256     break;
12257   }
12258 }
12259
12260 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12261                                                          unsigned Depth) const {
12262   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12263   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12264     return Op.getValueType().getScalarType().getSizeInBits();
12265
12266   // Fallback case.
12267   return 1;
12268 }
12269
12270 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12271 /// node is a GlobalAddress + offset.
12272 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12273                                        const GlobalValue* &GA,
12274                                        int64_t &Offset) const {
12275   if (N->getOpcode() == X86ISD::Wrapper) {
12276     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12277       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12278       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12279       return true;
12280     }
12281   }
12282   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12283 }
12284
12285 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12286 /// same as extracting the high 128-bit part of 256-bit vector and then
12287 /// inserting the result into the low part of a new 256-bit vector
12288 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12289   EVT VT = SVOp->getValueType(0);
12290   int NumElems = VT.getVectorNumElements();
12291
12292   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12293   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12294     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12295         SVOp->getMaskElt(j) >= 0)
12296       return false;
12297
12298   return true;
12299 }
12300
12301 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12302 /// same as extracting the low 128-bit part of 256-bit vector and then
12303 /// inserting the result into the high part of a new 256-bit vector
12304 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12305   EVT VT = SVOp->getValueType(0);
12306   int NumElems = VT.getVectorNumElements();
12307
12308   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12309   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12310     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12311         SVOp->getMaskElt(j) >= 0)
12312       return false;
12313
12314   return true;
12315 }
12316
12317 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12318 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12319                                         TargetLowering::DAGCombinerInfo &DCI) {
12320   DebugLoc dl = N->getDebugLoc();
12321   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12322   SDValue V1 = SVOp->getOperand(0);
12323   SDValue V2 = SVOp->getOperand(1);
12324   EVT VT = SVOp->getValueType(0);
12325   int NumElems = VT.getVectorNumElements();
12326
12327   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12328       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12329     //
12330     //                   0,0,0,...
12331     //                      |
12332     //    V      UNDEF    BUILD_VECTOR    UNDEF
12333     //     \      /           \           /
12334     //  CONCAT_VECTOR         CONCAT_VECTOR
12335     //         \                  /
12336     //          \                /
12337     //          RESULT: V + zero extended
12338     //
12339     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12340         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12341         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12342       return SDValue();
12343
12344     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12345       return SDValue();
12346
12347     // To match the shuffle mask, the first half of the mask should
12348     // be exactly the first vector, and all the rest a splat with the
12349     // first element of the second one.
12350     for (int i = 0; i < NumElems/2; ++i)
12351       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12352           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12353         return SDValue();
12354
12355     // Emit a zeroed vector and insert the desired subvector on its
12356     // first half.
12357     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
12358     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12359                          DAG.getConstant(0, MVT::i32), DAG, dl);
12360     return DCI.CombineTo(N, InsV);
12361   }
12362
12363   //===--------------------------------------------------------------------===//
12364   // Combine some shuffles into subvector extracts and inserts:
12365   //
12366
12367   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12368   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12369     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12370                                     DAG, dl);
12371     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12372                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12373     return DCI.CombineTo(N, InsV);
12374   }
12375
12376   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12377   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12378     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12379     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12380                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12381     return DCI.CombineTo(N, InsV);
12382   }
12383
12384   return SDValue();
12385 }
12386
12387 /// PerformShuffleCombine - Performs several different shuffle combines.
12388 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12389                                      TargetLowering::DAGCombinerInfo &DCI,
12390                                      const X86Subtarget *Subtarget) {
12391   DebugLoc dl = N->getDebugLoc();
12392   EVT VT = N->getValueType(0);
12393
12394   // Don't create instructions with illegal types after legalize types has run.
12395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12396   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12397     return SDValue();
12398
12399   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12400   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12401       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12402     return PerformShuffleCombine256(N, DAG, DCI);
12403
12404   // Only handle 128 wide vector from here on.
12405   if (VT.getSizeInBits() != 128)
12406     return SDValue();
12407
12408   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12409   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12410   // consecutive, non-overlapping, and in the right order.
12411   SmallVector<SDValue, 16> Elts;
12412   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12413     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12414
12415   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12416 }
12417
12418 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12419 /// generation and convert it from being a bunch of shuffles and extracts
12420 /// to a simple store and scalar loads to extract the elements.
12421 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12422                                                 const TargetLowering &TLI) {
12423   SDValue InputVector = N->getOperand(0);
12424
12425   // Only operate on vectors of 4 elements, where the alternative shuffling
12426   // gets to be more expensive.
12427   if (InputVector.getValueType() != MVT::v4i32)
12428     return SDValue();
12429
12430   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12431   // single use which is a sign-extend or zero-extend, and all elements are
12432   // used.
12433   SmallVector<SDNode *, 4> Uses;
12434   unsigned ExtractedElements = 0;
12435   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12436        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12437     if (UI.getUse().getResNo() != InputVector.getResNo())
12438       return SDValue();
12439
12440     SDNode *Extract = *UI;
12441     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12442       return SDValue();
12443
12444     if (Extract->getValueType(0) != MVT::i32)
12445       return SDValue();
12446     if (!Extract->hasOneUse())
12447       return SDValue();
12448     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12449         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12450       return SDValue();
12451     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12452       return SDValue();
12453
12454     // Record which element was extracted.
12455     ExtractedElements |=
12456       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12457
12458     Uses.push_back(Extract);
12459   }
12460
12461   // If not all the elements were used, this may not be worthwhile.
12462   if (ExtractedElements != 15)
12463     return SDValue();
12464
12465   // Ok, we've now decided to do the transformation.
12466   DebugLoc dl = InputVector.getDebugLoc();
12467
12468   // Store the value to a temporary stack slot.
12469   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12470   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12471                             MachinePointerInfo(), false, false, 0);
12472
12473   // Replace each use (extract) with a load of the appropriate element.
12474   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12475        UE = Uses.end(); UI != UE; ++UI) {
12476     SDNode *Extract = *UI;
12477
12478     // cOMpute the element's address.
12479     SDValue Idx = Extract->getOperand(1);
12480     unsigned EltSize =
12481         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12482     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12483     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12484
12485     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12486                                      StackPtr, OffsetVal);
12487
12488     // Load the scalar.
12489     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12490                                      ScalarAddr, MachinePointerInfo(),
12491                                      false, false, 0);
12492
12493     // Replace the exact with the load.
12494     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12495   }
12496
12497   // The replacement was made in place; don't return anything.
12498   return SDValue();
12499 }
12500
12501 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12502 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12503                                     const X86Subtarget *Subtarget) {
12504   DebugLoc DL = N->getDebugLoc();
12505   SDValue Cond = N->getOperand(0);
12506   // Get the LHS/RHS of the select.
12507   SDValue LHS = N->getOperand(1);
12508   SDValue RHS = N->getOperand(2);
12509
12510   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12511   // instructions match the semantics of the common C idiom x<y?x:y but not
12512   // x<=y?x:y, because of how they handle negative zero (which can be
12513   // ignored in unsafe-math mode).
12514   if (Subtarget->hasSSE2() &&
12515       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12516       Cond.getOpcode() == ISD::SETCC) {
12517     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12518
12519     unsigned Opcode = 0;
12520     // Check for x CC y ? x : y.
12521     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12522         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12523       switch (CC) {
12524       default: break;
12525       case ISD::SETULT:
12526         // Converting this to a min would handle NaNs incorrectly, and swapping
12527         // the operands would cause it to handle comparisons between positive
12528         // and negative zero incorrectly.
12529         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12530           if (!UnsafeFPMath &&
12531               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12532             break;
12533           std::swap(LHS, RHS);
12534         }
12535         Opcode = X86ISD::FMIN;
12536         break;
12537       case ISD::SETOLE:
12538         // Converting this to a min would handle comparisons between positive
12539         // and negative zero incorrectly.
12540         if (!UnsafeFPMath &&
12541             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12542           break;
12543         Opcode = X86ISD::FMIN;
12544         break;
12545       case ISD::SETULE:
12546         // Converting this to a min would handle both negative zeros and NaNs
12547         // incorrectly, but we can swap the operands to fix both.
12548         std::swap(LHS, RHS);
12549       case ISD::SETOLT:
12550       case ISD::SETLT:
12551       case ISD::SETLE:
12552         Opcode = X86ISD::FMIN;
12553         break;
12554
12555       case ISD::SETOGE:
12556         // Converting this to a max would handle comparisons between positive
12557         // and negative zero incorrectly.
12558         if (!UnsafeFPMath &&
12559             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12560           break;
12561         Opcode = X86ISD::FMAX;
12562         break;
12563       case ISD::SETUGT:
12564         // Converting this to a max would handle NaNs incorrectly, and swapping
12565         // the operands would cause it to handle comparisons between positive
12566         // and negative zero incorrectly.
12567         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12568           if (!UnsafeFPMath &&
12569               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12570             break;
12571           std::swap(LHS, RHS);
12572         }
12573         Opcode = X86ISD::FMAX;
12574         break;
12575       case ISD::SETUGE:
12576         // Converting this to a max would handle both negative zeros and NaNs
12577         // incorrectly, but we can swap the operands to fix both.
12578         std::swap(LHS, RHS);
12579       case ISD::SETOGT:
12580       case ISD::SETGT:
12581       case ISD::SETGE:
12582         Opcode = X86ISD::FMAX;
12583         break;
12584       }
12585     // Check for x CC y ? y : x -- a min/max with reversed arms.
12586     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12587                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12588       switch (CC) {
12589       default: break;
12590       case ISD::SETOGE:
12591         // Converting this to a min would handle comparisons between positive
12592         // and negative zero incorrectly, and swapping the operands would
12593         // cause it to handle NaNs incorrectly.
12594         if (!UnsafeFPMath &&
12595             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12596           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12597             break;
12598           std::swap(LHS, RHS);
12599         }
12600         Opcode = X86ISD::FMIN;
12601         break;
12602       case ISD::SETUGT:
12603         // Converting this to a min would handle NaNs incorrectly.
12604         if (!UnsafeFPMath &&
12605             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12606           break;
12607         Opcode = X86ISD::FMIN;
12608         break;
12609       case ISD::SETUGE:
12610         // Converting this to a min would handle both negative zeros and NaNs
12611         // incorrectly, but we can swap the operands to fix both.
12612         std::swap(LHS, RHS);
12613       case ISD::SETOGT:
12614       case ISD::SETGT:
12615       case ISD::SETGE:
12616         Opcode = X86ISD::FMIN;
12617         break;
12618
12619       case ISD::SETULT:
12620         // Converting this to a max would handle NaNs incorrectly.
12621         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12622           break;
12623         Opcode = X86ISD::FMAX;
12624         break;
12625       case ISD::SETOLE:
12626         // Converting this to a max would handle comparisons between positive
12627         // and negative zero incorrectly, and swapping the operands would
12628         // cause it to handle NaNs incorrectly.
12629         if (!UnsafeFPMath &&
12630             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12631           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12632             break;
12633           std::swap(LHS, RHS);
12634         }
12635         Opcode = X86ISD::FMAX;
12636         break;
12637       case ISD::SETULE:
12638         // Converting this to a max would handle both negative zeros and NaNs
12639         // incorrectly, but we can swap the operands to fix both.
12640         std::swap(LHS, RHS);
12641       case ISD::SETOLT:
12642       case ISD::SETLT:
12643       case ISD::SETLE:
12644         Opcode = X86ISD::FMAX;
12645         break;
12646       }
12647     }
12648
12649     if (Opcode)
12650       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12651   }
12652
12653   // If this is a select between two integer constants, try to do some
12654   // optimizations.
12655   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12656     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12657       // Don't do this for crazy integer types.
12658       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12659         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12660         // so that TrueC (the true value) is larger than FalseC.
12661         bool NeedsCondInvert = false;
12662
12663         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12664             // Efficiently invertible.
12665             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12666              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12667               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12668           NeedsCondInvert = true;
12669           std::swap(TrueC, FalseC);
12670         }
12671
12672         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12673         if (FalseC->getAPIntValue() == 0 &&
12674             TrueC->getAPIntValue().isPowerOf2()) {
12675           if (NeedsCondInvert) // Invert the condition if needed.
12676             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12677                                DAG.getConstant(1, Cond.getValueType()));
12678
12679           // Zero extend the condition if needed.
12680           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12681
12682           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12683           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12684                              DAG.getConstant(ShAmt, MVT::i8));
12685         }
12686
12687         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12688         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12689           if (NeedsCondInvert) // Invert the condition if needed.
12690             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12691                                DAG.getConstant(1, Cond.getValueType()));
12692
12693           // Zero extend the condition if needed.
12694           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12695                              FalseC->getValueType(0), Cond);
12696           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12697                              SDValue(FalseC, 0));
12698         }
12699
12700         // Optimize cases that will turn into an LEA instruction.  This requires
12701         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12702         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12703           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12704           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12705
12706           bool isFastMultiplier = false;
12707           if (Diff < 10) {
12708             switch ((unsigned char)Diff) {
12709               default: break;
12710               case 1:  // result = add base, cond
12711               case 2:  // result = lea base(    , cond*2)
12712               case 3:  // result = lea base(cond, cond*2)
12713               case 4:  // result = lea base(    , cond*4)
12714               case 5:  // result = lea base(cond, cond*4)
12715               case 8:  // result = lea base(    , cond*8)
12716               case 9:  // result = lea base(cond, cond*8)
12717                 isFastMultiplier = true;
12718                 break;
12719             }
12720           }
12721
12722           if (isFastMultiplier) {
12723             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12724             if (NeedsCondInvert) // Invert the condition if needed.
12725               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12726                                  DAG.getConstant(1, Cond.getValueType()));
12727
12728             // Zero extend the condition if needed.
12729             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12730                                Cond);
12731             // Scale the condition by the difference.
12732             if (Diff != 1)
12733               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12734                                  DAG.getConstant(Diff, Cond.getValueType()));
12735
12736             // Add the base if non-zero.
12737             if (FalseC->getAPIntValue() != 0)
12738               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12739                                  SDValue(FalseC, 0));
12740             return Cond;
12741           }
12742         }
12743       }
12744   }
12745
12746   return SDValue();
12747 }
12748
12749 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12750 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12751                                   TargetLowering::DAGCombinerInfo &DCI) {
12752   DebugLoc DL = N->getDebugLoc();
12753
12754   // If the flag operand isn't dead, don't touch this CMOV.
12755   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12756     return SDValue();
12757
12758   SDValue FalseOp = N->getOperand(0);
12759   SDValue TrueOp = N->getOperand(1);
12760   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12761   SDValue Cond = N->getOperand(3);
12762   if (CC == X86::COND_E || CC == X86::COND_NE) {
12763     switch (Cond.getOpcode()) {
12764     default: break;
12765     case X86ISD::BSR:
12766     case X86ISD::BSF:
12767       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12768       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12769         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12770     }
12771   }
12772
12773   // If this is a select between two integer constants, try to do some
12774   // optimizations.  Note that the operands are ordered the opposite of SELECT
12775   // operands.
12776   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12777     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12778       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12779       // larger than FalseC (the false value).
12780       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12781         CC = X86::GetOppositeBranchCondition(CC);
12782         std::swap(TrueC, FalseC);
12783       }
12784
12785       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12786       // This is efficient for any integer data type (including i8/i16) and
12787       // shift amount.
12788       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12789         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12790                            DAG.getConstant(CC, MVT::i8), Cond);
12791
12792         // Zero extend the condition if needed.
12793         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12794
12795         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12796         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12797                            DAG.getConstant(ShAmt, MVT::i8));
12798         if (N->getNumValues() == 2)  // Dead flag value?
12799           return DCI.CombineTo(N, Cond, SDValue());
12800         return Cond;
12801       }
12802
12803       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12804       // for any integer data type, including i8/i16.
12805       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12806         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12807                            DAG.getConstant(CC, MVT::i8), Cond);
12808
12809         // Zero extend the condition if needed.
12810         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12811                            FalseC->getValueType(0), Cond);
12812         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12813                            SDValue(FalseC, 0));
12814
12815         if (N->getNumValues() == 2)  // Dead flag value?
12816           return DCI.CombineTo(N, Cond, SDValue());
12817         return Cond;
12818       }
12819
12820       // Optimize cases that will turn into an LEA instruction.  This requires
12821       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12822       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12823         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12824         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12825
12826         bool isFastMultiplier = false;
12827         if (Diff < 10) {
12828           switch ((unsigned char)Diff) {
12829           default: break;
12830           case 1:  // result = add base, cond
12831           case 2:  // result = lea base(    , cond*2)
12832           case 3:  // result = lea base(cond, cond*2)
12833           case 4:  // result = lea base(    , cond*4)
12834           case 5:  // result = lea base(cond, cond*4)
12835           case 8:  // result = lea base(    , cond*8)
12836           case 9:  // result = lea base(cond, cond*8)
12837             isFastMultiplier = true;
12838             break;
12839           }
12840         }
12841
12842         if (isFastMultiplier) {
12843           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12844           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12845                              DAG.getConstant(CC, MVT::i8), Cond);
12846           // Zero extend the condition if needed.
12847           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12848                              Cond);
12849           // Scale the condition by the difference.
12850           if (Diff != 1)
12851             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12852                                DAG.getConstant(Diff, Cond.getValueType()));
12853
12854           // Add the base if non-zero.
12855           if (FalseC->getAPIntValue() != 0)
12856             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12857                                SDValue(FalseC, 0));
12858           if (N->getNumValues() == 2)  // Dead flag value?
12859             return DCI.CombineTo(N, Cond, SDValue());
12860           return Cond;
12861         }
12862       }
12863     }
12864   }
12865   return SDValue();
12866 }
12867
12868
12869 /// PerformMulCombine - Optimize a single multiply with constant into two
12870 /// in order to implement it with two cheaper instructions, e.g.
12871 /// LEA + SHL, LEA + LEA.
12872 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12873                                  TargetLowering::DAGCombinerInfo &DCI) {
12874   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12875     return SDValue();
12876
12877   EVT VT = N->getValueType(0);
12878   if (VT != MVT::i64)
12879     return SDValue();
12880
12881   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12882   if (!C)
12883     return SDValue();
12884   uint64_t MulAmt = C->getZExtValue();
12885   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12886     return SDValue();
12887
12888   uint64_t MulAmt1 = 0;
12889   uint64_t MulAmt2 = 0;
12890   if ((MulAmt % 9) == 0) {
12891     MulAmt1 = 9;
12892     MulAmt2 = MulAmt / 9;
12893   } else if ((MulAmt % 5) == 0) {
12894     MulAmt1 = 5;
12895     MulAmt2 = MulAmt / 5;
12896   } else if ((MulAmt % 3) == 0) {
12897     MulAmt1 = 3;
12898     MulAmt2 = MulAmt / 3;
12899   }
12900   if (MulAmt2 &&
12901       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12902     DebugLoc DL = N->getDebugLoc();
12903
12904     if (isPowerOf2_64(MulAmt2) &&
12905         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12906       // If second multiplifer is pow2, issue it first. We want the multiply by
12907       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12908       // is an add.
12909       std::swap(MulAmt1, MulAmt2);
12910
12911     SDValue NewMul;
12912     if (isPowerOf2_64(MulAmt1))
12913       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12914                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12915     else
12916       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12917                            DAG.getConstant(MulAmt1, VT));
12918
12919     if (isPowerOf2_64(MulAmt2))
12920       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12921                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12922     else
12923       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12924                            DAG.getConstant(MulAmt2, VT));
12925
12926     // Do not add new nodes to DAG combiner worklist.
12927     DCI.CombineTo(N, NewMul, false);
12928   }
12929   return SDValue();
12930 }
12931
12932 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12933   SDValue N0 = N->getOperand(0);
12934   SDValue N1 = N->getOperand(1);
12935   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12936   EVT VT = N0.getValueType();
12937
12938   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12939   // since the result of setcc_c is all zero's or all ones.
12940   if (N1C && N0.getOpcode() == ISD::AND &&
12941       N0.getOperand(1).getOpcode() == ISD::Constant) {
12942     SDValue N00 = N0.getOperand(0);
12943     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12944         ((N00.getOpcode() == ISD::ANY_EXTEND ||
12945           N00.getOpcode() == ISD::ZERO_EXTEND) &&
12946          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12947       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12948       APInt ShAmt = N1C->getAPIntValue();
12949       Mask = Mask.shl(ShAmt);
12950       if (Mask != 0)
12951         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12952                            N00, DAG.getConstant(Mask, VT));
12953     }
12954   }
12955
12956   return SDValue();
12957 }
12958
12959 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12960 ///                       when possible.
12961 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12962                                    const X86Subtarget *Subtarget) {
12963   EVT VT = N->getValueType(0);
12964   if (!VT.isVector() && VT.isInteger() &&
12965       N->getOpcode() == ISD::SHL)
12966     return PerformSHLCombine(N, DAG);
12967
12968   // On X86 with SSE2 support, we can transform this to a vector shift if
12969   // all elements are shifted by the same amount.  We can't do this in legalize
12970   // because the a constant vector is typically transformed to a constant pool
12971   // so we have no knowledge of the shift amount.
12972   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12973     return SDValue();
12974
12975   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
12976     return SDValue();
12977
12978   SDValue ShAmtOp = N->getOperand(1);
12979   EVT EltVT = VT.getVectorElementType();
12980   DebugLoc DL = N->getDebugLoc();
12981   SDValue BaseShAmt = SDValue();
12982   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
12983     unsigned NumElts = VT.getVectorNumElements();
12984     unsigned i = 0;
12985     for (; i != NumElts; ++i) {
12986       SDValue Arg = ShAmtOp.getOperand(i);
12987       if (Arg.getOpcode() == ISD::UNDEF) continue;
12988       BaseShAmt = Arg;
12989       break;
12990     }
12991     for (; i != NumElts; ++i) {
12992       SDValue Arg = ShAmtOp.getOperand(i);
12993       if (Arg.getOpcode() == ISD::UNDEF) continue;
12994       if (Arg != BaseShAmt) {
12995         return SDValue();
12996       }
12997     }
12998   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
12999              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13000     SDValue InVec = ShAmtOp.getOperand(0);
13001     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13002       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13003       unsigned i = 0;
13004       for (; i != NumElts; ++i) {
13005         SDValue Arg = InVec.getOperand(i);
13006         if (Arg.getOpcode() == ISD::UNDEF) continue;
13007         BaseShAmt = Arg;
13008         break;
13009       }
13010     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13011        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13012          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13013          if (C->getZExtValue() == SplatIdx)
13014            BaseShAmt = InVec.getOperand(1);
13015        }
13016     }
13017     if (BaseShAmt.getNode() == 0)
13018       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13019                               DAG.getIntPtrConstant(0));
13020   } else
13021     return SDValue();
13022
13023   // The shift amount is an i32.
13024   if (EltVT.bitsGT(MVT::i32))
13025     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13026   else if (EltVT.bitsLT(MVT::i32))
13027     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13028
13029   // The shift amount is identical so we can do a vector shift.
13030   SDValue  ValOp = N->getOperand(0);
13031   switch (N->getOpcode()) {
13032   default:
13033     llvm_unreachable("Unknown shift opcode!");
13034     break;
13035   case ISD::SHL:
13036     if (VT == MVT::v2i64)
13037       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13038                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13039                          ValOp, BaseShAmt);
13040     if (VT == MVT::v4i32)
13041       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13042                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13043                          ValOp, BaseShAmt);
13044     if (VT == MVT::v8i16)
13045       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13046                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13047                          ValOp, BaseShAmt);
13048     break;
13049   case ISD::SRA:
13050     if (VT == MVT::v4i32)
13051       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13052                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13053                          ValOp, BaseShAmt);
13054     if (VT == MVT::v8i16)
13055       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13056                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13057                          ValOp, BaseShAmt);
13058     break;
13059   case ISD::SRL:
13060     if (VT == MVT::v2i64)
13061       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13062                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13063                          ValOp, BaseShAmt);
13064     if (VT == MVT::v4i32)
13065       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13066                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13067                          ValOp, BaseShAmt);
13068     if (VT ==  MVT::v8i16)
13069       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13070                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13071                          ValOp, BaseShAmt);
13072     break;
13073   }
13074   return SDValue();
13075 }
13076
13077
13078 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13079 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13080 // and friends.  Likewise for OR -> CMPNEQSS.
13081 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13082                             TargetLowering::DAGCombinerInfo &DCI,
13083                             const X86Subtarget *Subtarget) {
13084   unsigned opcode;
13085
13086   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13087   // we're requiring SSE2 for both.
13088   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13089     SDValue N0 = N->getOperand(0);
13090     SDValue N1 = N->getOperand(1);
13091     SDValue CMP0 = N0->getOperand(1);
13092     SDValue CMP1 = N1->getOperand(1);
13093     DebugLoc DL = N->getDebugLoc();
13094
13095     // The SETCCs should both refer to the same CMP.
13096     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13097       return SDValue();
13098
13099     SDValue CMP00 = CMP0->getOperand(0);
13100     SDValue CMP01 = CMP0->getOperand(1);
13101     EVT     VT    = CMP00.getValueType();
13102
13103     if (VT == MVT::f32 || VT == MVT::f64) {
13104       bool ExpectingFlags = false;
13105       // Check for any users that want flags:
13106       for (SDNode::use_iterator UI = N->use_begin(),
13107              UE = N->use_end();
13108            !ExpectingFlags && UI != UE; ++UI)
13109         switch (UI->getOpcode()) {
13110         default:
13111         case ISD::BR_CC:
13112         case ISD::BRCOND:
13113         case ISD::SELECT:
13114           ExpectingFlags = true;
13115           break;
13116         case ISD::CopyToReg:
13117         case ISD::SIGN_EXTEND:
13118         case ISD::ZERO_EXTEND:
13119         case ISD::ANY_EXTEND:
13120           break;
13121         }
13122
13123       if (!ExpectingFlags) {
13124         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13125         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13126
13127         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13128           X86::CondCode tmp = cc0;
13129           cc0 = cc1;
13130           cc1 = tmp;
13131         }
13132
13133         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13134             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13135           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13136           X86ISD::NodeType NTOperator = is64BitFP ?
13137             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13138           // FIXME: need symbolic constants for these magic numbers.
13139           // See X86ATTInstPrinter.cpp:printSSECC().
13140           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13141           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13142                                               DAG.getConstant(x86cc, MVT::i8));
13143           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13144                                               OnesOrZeroesF);
13145           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13146                                       DAG.getConstant(1, MVT::i32));
13147           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13148           return OneBitOfTruth;
13149         }
13150       }
13151     }
13152   }
13153   return SDValue();
13154 }
13155
13156 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13157 /// so it can be folded inside ANDNP.
13158 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13159   EVT VT = N->getValueType(0);
13160
13161   // Match direct AllOnes for 128 and 256-bit vectors
13162   if (ISD::isBuildVectorAllOnes(N))
13163     return true;
13164
13165   // Look through a bit convert.
13166   if (N->getOpcode() == ISD::BITCAST)
13167     N = N->getOperand(0).getNode();
13168
13169   // Sometimes the operand may come from a insert_subvector building a 256-bit
13170   // allones vector
13171   if (VT.getSizeInBits() == 256 &&
13172       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13173     SDValue V1 = N->getOperand(0);
13174     SDValue V2 = N->getOperand(1);
13175
13176     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13177         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13178         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13179         ISD::isBuildVectorAllOnes(V2.getNode()))
13180       return true;
13181   }
13182
13183   return false;
13184 }
13185
13186 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13187                                  TargetLowering::DAGCombinerInfo &DCI,
13188                                  const X86Subtarget *Subtarget) {
13189   if (DCI.isBeforeLegalizeOps())
13190     return SDValue();
13191
13192   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13193   if (R.getNode())
13194     return R;
13195
13196   // Want to form ANDNP nodes:
13197   // 1) In the hopes of then easily combining them with OR and AND nodes
13198   //    to form PBLEND/PSIGN.
13199   // 2) To match ANDN packed intrinsics
13200   EVT VT = N->getValueType(0);
13201   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13202     return SDValue();
13203
13204   SDValue N0 = N->getOperand(0);
13205   SDValue N1 = N->getOperand(1);
13206   DebugLoc DL = N->getDebugLoc();
13207
13208   // Check LHS for vnot
13209   if (N0.getOpcode() == ISD::XOR &&
13210       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13211       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13212     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13213
13214   // Check RHS for vnot
13215   if (N1.getOpcode() == ISD::XOR &&
13216       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13217       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13218     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13219
13220   return SDValue();
13221 }
13222
13223 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13224                                 TargetLowering::DAGCombinerInfo &DCI,
13225                                 const X86Subtarget *Subtarget) {
13226   if (DCI.isBeforeLegalizeOps())
13227     return SDValue();
13228
13229   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13230   if (R.getNode())
13231     return R;
13232
13233   EVT VT = N->getValueType(0);
13234   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13235     return SDValue();
13236
13237   SDValue N0 = N->getOperand(0);
13238   SDValue N1 = N->getOperand(1);
13239
13240   // look for psign/blend
13241   if (Subtarget->hasSSSE3()) {
13242     if (VT == MVT::v2i64) {
13243       // Canonicalize pandn to RHS
13244       if (N0.getOpcode() == X86ISD::ANDNP)
13245         std::swap(N0, N1);
13246       // or (and (m, x), (pandn m, y))
13247       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13248         SDValue Mask = N1.getOperand(0);
13249         SDValue X    = N1.getOperand(1);
13250         SDValue Y;
13251         if (N0.getOperand(0) == Mask)
13252           Y = N0.getOperand(1);
13253         if (N0.getOperand(1) == Mask)
13254           Y = N0.getOperand(0);
13255
13256         // Check to see if the mask appeared in both the AND and ANDNP and
13257         if (!Y.getNode())
13258           return SDValue();
13259
13260         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13261         if (Mask.getOpcode() != ISD::BITCAST ||
13262             X.getOpcode() != ISD::BITCAST ||
13263             Y.getOpcode() != ISD::BITCAST)
13264           return SDValue();
13265
13266         // Look through mask bitcast.
13267         Mask = Mask.getOperand(0);
13268         EVT MaskVT = Mask.getValueType();
13269
13270         // Validate that the Mask operand is a vector sra node.  The sra node
13271         // will be an intrinsic.
13272         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13273           return SDValue();
13274
13275         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13276         // there is no psrai.b
13277         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13278         case Intrinsic::x86_sse2_psrai_w:
13279         case Intrinsic::x86_sse2_psrai_d:
13280           break;
13281         default: return SDValue();
13282         }
13283
13284         // Check that the SRA is all signbits.
13285         SDValue SraC = Mask.getOperand(2);
13286         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13287         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13288         if ((SraAmt + 1) != EltBits)
13289           return SDValue();
13290
13291         DebugLoc DL = N->getDebugLoc();
13292
13293         // Now we know we at least have a plendvb with the mask val.  See if
13294         // we can form a psignb/w/d.
13295         // psign = x.type == y.type == mask.type && y = sub(0, x);
13296         X = X.getOperand(0);
13297         Y = Y.getOperand(0);
13298         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13299             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13300             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13301           unsigned Opc = 0;
13302           switch (EltBits) {
13303           case 8: Opc = X86ISD::PSIGNB; break;
13304           case 16: Opc = X86ISD::PSIGNW; break;
13305           case 32: Opc = X86ISD::PSIGND; break;
13306           default: break;
13307           }
13308           if (Opc) {
13309             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13310             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13311           }
13312         }
13313         // PBLENDVB only available on SSE 4.1
13314         if (!Subtarget->hasSSE41())
13315           return SDValue();
13316
13317         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13318         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13319         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13320         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
13321         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13322       }
13323     }
13324   }
13325
13326   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13327   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13328     std::swap(N0, N1);
13329   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13330     return SDValue();
13331   if (!N0.hasOneUse() || !N1.hasOneUse())
13332     return SDValue();
13333
13334   SDValue ShAmt0 = N0.getOperand(1);
13335   if (ShAmt0.getValueType() != MVT::i8)
13336     return SDValue();
13337   SDValue ShAmt1 = N1.getOperand(1);
13338   if (ShAmt1.getValueType() != MVT::i8)
13339     return SDValue();
13340   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13341     ShAmt0 = ShAmt0.getOperand(0);
13342   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13343     ShAmt1 = ShAmt1.getOperand(0);
13344
13345   DebugLoc DL = N->getDebugLoc();
13346   unsigned Opc = X86ISD::SHLD;
13347   SDValue Op0 = N0.getOperand(0);
13348   SDValue Op1 = N1.getOperand(0);
13349   if (ShAmt0.getOpcode() == ISD::SUB) {
13350     Opc = X86ISD::SHRD;
13351     std::swap(Op0, Op1);
13352     std::swap(ShAmt0, ShAmt1);
13353   }
13354
13355   unsigned Bits = VT.getSizeInBits();
13356   if (ShAmt1.getOpcode() == ISD::SUB) {
13357     SDValue Sum = ShAmt1.getOperand(0);
13358     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13359       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13360       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13361         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13362       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13363         return DAG.getNode(Opc, DL, VT,
13364                            Op0, Op1,
13365                            DAG.getNode(ISD::TRUNCATE, DL,
13366                                        MVT::i8, ShAmt0));
13367     }
13368   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13369     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13370     if (ShAmt0C &&
13371         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13372       return DAG.getNode(Opc, DL, VT,
13373                          N0.getOperand(0), N1.getOperand(0),
13374                          DAG.getNode(ISD::TRUNCATE, DL,
13375                                        MVT::i8, ShAmt0));
13376   }
13377
13378   return SDValue();
13379 }
13380
13381 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13382 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13383                                    const X86Subtarget *Subtarget) {
13384   StoreSDNode *St = cast<StoreSDNode>(N);
13385   EVT VT = St->getValue().getValueType();
13386   EVT StVT = St->getMemoryVT();
13387   DebugLoc dl = St->getDebugLoc();
13388   SDValue StoredVal = St->getOperand(1);
13389   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13390
13391   // If we are saving a concatination of two XMM registers, perform two stores.
13392   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13393   // 128-bit ones. If in the future the cost becomes only one memory access the
13394   // first version would be better.
13395   if (VT.getSizeInBits() == 256 &&
13396     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13397     StoredVal.getNumOperands() == 2) {
13398
13399     SDValue Value0 = StoredVal.getOperand(0);
13400     SDValue Value1 = StoredVal.getOperand(1);
13401
13402     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13403     SDValue Ptr0 = St->getBasePtr();
13404     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13405
13406     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13407                                 St->getPointerInfo(), St->isVolatile(),
13408                                 St->isNonTemporal(), St->getAlignment());
13409     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13410                                 St->getPointerInfo(), St->isVolatile(),
13411                                 St->isNonTemporal(), St->getAlignment());
13412     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13413   }
13414
13415   // Optimize trunc store (of multiple scalars) to shuffle and store.
13416   // First, pack all of the elements in one place. Next, store to memory
13417   // in fewer chunks.
13418   if (St->isTruncatingStore() && VT.isVector()) {
13419     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13420     unsigned NumElems = VT.getVectorNumElements();
13421     assert(StVT != VT && "Cannot truncate to the same type");
13422     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13423     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13424
13425     // From, To sizes and ElemCount must be pow of two
13426     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13427     // We are going to use the original vector elt for storing.
13428     // accumulated smaller vector elements must be a multiple of bigger size.
13429     if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13430     unsigned SizeRatio  = FromSz / ToSz;
13431
13432     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13433
13434     // Create a type on which we perform the shuffle
13435     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13436             StVT.getScalarType(), NumElems*SizeRatio);
13437
13438     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13439
13440     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13441     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13442     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13443
13444     // Can't shuffle using an illegal type
13445     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13446
13447     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13448                                 DAG.getUNDEF(WideVec.getValueType()),
13449                                 ShuffleVec.data());
13450     // At this point all of the data is stored at the bottom of the
13451     // register. We now need to save it to mem.
13452
13453     // Find the largest store unit
13454     MVT StoreType = MVT::i8;
13455     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13456          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13457       MVT Tp = (MVT::SimpleValueType)tp;
13458       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13459         StoreType = Tp;
13460     }
13461
13462     // Bitcast the original vector into a vector of store-size units
13463     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13464             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13465     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13466     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13467     SmallVector<SDValue, 8> Chains;
13468     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13469                                         TLI.getPointerTy());
13470     SDValue Ptr = St->getBasePtr();
13471
13472     // Perform one or more big stores into memory.
13473     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13474       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13475                                    StoreType, ShuffWide,
13476                                    DAG.getIntPtrConstant(i));
13477       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13478                                 St->getPointerInfo(), St->isVolatile(),
13479                                 St->isNonTemporal(), St->getAlignment());
13480       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13481       Chains.push_back(Ch);
13482     }
13483
13484     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13485                                Chains.size());
13486   }
13487
13488
13489   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13490   // the FP state in cases where an emms may be missing.
13491   // A preferable solution to the general problem is to figure out the right
13492   // places to insert EMMS.  This qualifies as a quick hack.
13493
13494   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13495   if (VT.getSizeInBits() != 64)
13496     return SDValue();
13497
13498   const Function *F = DAG.getMachineFunction().getFunction();
13499   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13500   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13501     && Subtarget->hasSSE2();
13502   if ((VT.isVector() ||
13503        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13504       isa<LoadSDNode>(St->getValue()) &&
13505       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13506       St->getChain().hasOneUse() && !St->isVolatile()) {
13507     SDNode* LdVal = St->getValue().getNode();
13508     LoadSDNode *Ld = 0;
13509     int TokenFactorIndex = -1;
13510     SmallVector<SDValue, 8> Ops;
13511     SDNode* ChainVal = St->getChain().getNode();
13512     // Must be a store of a load.  We currently handle two cases:  the load
13513     // is a direct child, and it's under an intervening TokenFactor.  It is
13514     // possible to dig deeper under nested TokenFactors.
13515     if (ChainVal == LdVal)
13516       Ld = cast<LoadSDNode>(St->getChain());
13517     else if (St->getValue().hasOneUse() &&
13518              ChainVal->getOpcode() == ISD::TokenFactor) {
13519       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13520         if (ChainVal->getOperand(i).getNode() == LdVal) {
13521           TokenFactorIndex = i;
13522           Ld = cast<LoadSDNode>(St->getValue());
13523         } else
13524           Ops.push_back(ChainVal->getOperand(i));
13525       }
13526     }
13527
13528     if (!Ld || !ISD::isNormalLoad(Ld))
13529       return SDValue();
13530
13531     // If this is not the MMX case, i.e. we are just turning i64 load/store
13532     // into f64 load/store, avoid the transformation if there are multiple
13533     // uses of the loaded value.
13534     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13535       return SDValue();
13536
13537     DebugLoc LdDL = Ld->getDebugLoc();
13538     DebugLoc StDL = N->getDebugLoc();
13539     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13540     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13541     // pair instead.
13542     if (Subtarget->is64Bit() || F64IsLegal) {
13543       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13544       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13545                                   Ld->getPointerInfo(), Ld->isVolatile(),
13546                                   Ld->isNonTemporal(), Ld->getAlignment());
13547       SDValue NewChain = NewLd.getValue(1);
13548       if (TokenFactorIndex != -1) {
13549         Ops.push_back(NewChain);
13550         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13551                                Ops.size());
13552       }
13553       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13554                           St->getPointerInfo(),
13555                           St->isVolatile(), St->isNonTemporal(),
13556                           St->getAlignment());
13557     }
13558
13559     // Otherwise, lower to two pairs of 32-bit loads / stores.
13560     SDValue LoAddr = Ld->getBasePtr();
13561     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13562                                  DAG.getConstant(4, MVT::i32));
13563
13564     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13565                                Ld->getPointerInfo(),
13566                                Ld->isVolatile(), Ld->isNonTemporal(),
13567                                Ld->getAlignment());
13568     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13569                                Ld->getPointerInfo().getWithOffset(4),
13570                                Ld->isVolatile(), Ld->isNonTemporal(),
13571                                MinAlign(Ld->getAlignment(), 4));
13572
13573     SDValue NewChain = LoLd.getValue(1);
13574     if (TokenFactorIndex != -1) {
13575       Ops.push_back(LoLd);
13576       Ops.push_back(HiLd);
13577       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13578                              Ops.size());
13579     }
13580
13581     LoAddr = St->getBasePtr();
13582     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13583                          DAG.getConstant(4, MVT::i32));
13584
13585     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13586                                 St->getPointerInfo(),
13587                                 St->isVolatile(), St->isNonTemporal(),
13588                                 St->getAlignment());
13589     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13590                                 St->getPointerInfo().getWithOffset(4),
13591                                 St->isVolatile(),
13592                                 St->isNonTemporal(),
13593                                 MinAlign(St->getAlignment(), 4));
13594     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13595   }
13596   return SDValue();
13597 }
13598
13599 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13600 /// X86ISD::FXOR nodes.
13601 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13602   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13603   // F[X]OR(0.0, x) -> x
13604   // F[X]OR(x, 0.0) -> x
13605   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13606     if (C->getValueAPF().isPosZero())
13607       return N->getOperand(1);
13608   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13609     if (C->getValueAPF().isPosZero())
13610       return N->getOperand(0);
13611   return SDValue();
13612 }
13613
13614 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13615 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13616   // FAND(0.0, x) -> 0.0
13617   // FAND(x, 0.0) -> 0.0
13618   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13619     if (C->getValueAPF().isPosZero())
13620       return N->getOperand(0);
13621   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13622     if (C->getValueAPF().isPosZero())
13623       return N->getOperand(1);
13624   return SDValue();
13625 }
13626
13627 static SDValue PerformBTCombine(SDNode *N,
13628                                 SelectionDAG &DAG,
13629                                 TargetLowering::DAGCombinerInfo &DCI) {
13630   // BT ignores high bits in the bit index operand.
13631   SDValue Op1 = N->getOperand(1);
13632   if (Op1.hasOneUse()) {
13633     unsigned BitWidth = Op1.getValueSizeInBits();
13634     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13635     APInt KnownZero, KnownOne;
13636     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13637                                           !DCI.isBeforeLegalizeOps());
13638     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13639     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13640         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13641       DCI.CommitTargetLoweringOpt(TLO);
13642   }
13643   return SDValue();
13644 }
13645
13646 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13647   SDValue Op = N->getOperand(0);
13648   if (Op.getOpcode() == ISD::BITCAST)
13649     Op = Op.getOperand(0);
13650   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13651   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13652       VT.getVectorElementType().getSizeInBits() ==
13653       OpVT.getVectorElementType().getSizeInBits()) {
13654     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13655   }
13656   return SDValue();
13657 }
13658
13659 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13660   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13661   //           (and (i32 x86isd::setcc_carry), 1)
13662   // This eliminates the zext. This transformation is necessary because
13663   // ISD::SETCC is always legalized to i8.
13664   DebugLoc dl = N->getDebugLoc();
13665   SDValue N0 = N->getOperand(0);
13666   EVT VT = N->getValueType(0);
13667   if (N0.getOpcode() == ISD::AND &&
13668       N0.hasOneUse() &&
13669       N0.getOperand(0).hasOneUse()) {
13670     SDValue N00 = N0.getOperand(0);
13671     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13672       return SDValue();
13673     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13674     if (!C || C->getZExtValue() != 1)
13675       return SDValue();
13676     return DAG.getNode(ISD::AND, dl, VT,
13677                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13678                                    N00.getOperand(0), N00.getOperand(1)),
13679                        DAG.getConstant(1, VT));
13680   }
13681
13682   return SDValue();
13683 }
13684
13685 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13686 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13687   unsigned X86CC = N->getConstantOperandVal(0);
13688   SDValue EFLAG = N->getOperand(1);
13689   DebugLoc DL = N->getDebugLoc();
13690
13691   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13692   // a zext and produces an all-ones bit which is more useful than 0/1 in some
13693   // cases.
13694   if (X86CC == X86::COND_B)
13695     return DAG.getNode(ISD::AND, DL, MVT::i8,
13696                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13697                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
13698                        DAG.getConstant(1, MVT::i8));
13699
13700   return SDValue();
13701 }
13702
13703 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13704                                         const X86TargetLowering *XTLI) {
13705   SDValue Op0 = N->getOperand(0);
13706   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13707   // a 32-bit target where SSE doesn't support i64->FP operations.
13708   if (Op0.getOpcode() == ISD::LOAD) {
13709     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13710     EVT VT = Ld->getValueType(0);
13711     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13712         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13713         !XTLI->getSubtarget()->is64Bit() &&
13714         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13715       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13716                                           Ld->getChain(), Op0, DAG);
13717       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13718       return FILDChain;
13719     }
13720   }
13721   return SDValue();
13722 }
13723
13724 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13725 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13726                                  X86TargetLowering::DAGCombinerInfo &DCI) {
13727   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13728   // the result is either zero or one (depending on the input carry bit).
13729   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13730   if (X86::isZeroNode(N->getOperand(0)) &&
13731       X86::isZeroNode(N->getOperand(1)) &&
13732       // We don't have a good way to replace an EFLAGS use, so only do this when
13733       // dead right now.
13734       SDValue(N, 1).use_empty()) {
13735     DebugLoc DL = N->getDebugLoc();
13736     EVT VT = N->getValueType(0);
13737     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13738     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13739                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13740                                            DAG.getConstant(X86::COND_B,MVT::i8),
13741                                            N->getOperand(2)),
13742                                DAG.getConstant(1, VT));
13743     return DCI.CombineTo(N, Res1, CarryOut);
13744   }
13745
13746   return SDValue();
13747 }
13748
13749 // fold (add Y, (sete  X, 0)) -> adc  0, Y
13750 //      (add Y, (setne X, 0)) -> sbb -1, Y
13751 //      (sub (sete  X, 0), Y) -> sbb  0, Y
13752 //      (sub (setne X, 0), Y) -> adc -1, Y
13753 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13754   DebugLoc DL = N->getDebugLoc();
13755
13756   // Look through ZExts.
13757   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13758   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13759     return SDValue();
13760
13761   SDValue SetCC = Ext.getOperand(0);
13762   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13763     return SDValue();
13764
13765   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13766   if (CC != X86::COND_E && CC != X86::COND_NE)
13767     return SDValue();
13768
13769   SDValue Cmp = SetCC.getOperand(1);
13770   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13771       !X86::isZeroNode(Cmp.getOperand(1)) ||
13772       !Cmp.getOperand(0).getValueType().isInteger())
13773     return SDValue();
13774
13775   SDValue CmpOp0 = Cmp.getOperand(0);
13776   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13777                                DAG.getConstant(1, CmpOp0.getValueType()));
13778
13779   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13780   if (CC == X86::COND_NE)
13781     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13782                        DL, OtherVal.getValueType(), OtherVal,
13783                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13784   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13785                      DL, OtherVal.getValueType(), OtherVal,
13786                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13787 }
13788
13789 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13790   SDValue Op0 = N->getOperand(0);
13791   SDValue Op1 = N->getOperand(1);
13792
13793   // X86 can't encode an immediate LHS of a sub. See if we can push the
13794   // negation into a preceding instruction.
13795   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13796     // If the RHS of the sub is a XOR with one use and a constant, invert the
13797     // immediate. Then add one to the LHS of the sub so we can turn
13798     // X-Y -> X+~Y+1, saving one register.
13799     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13800         isa<ConstantSDNode>(Op1.getOperand(1))) {
13801       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13802       EVT VT = Op0.getValueType();
13803       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13804                                    Op1.getOperand(0),
13805                                    DAG.getConstant(~XorC, VT));
13806       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13807                          DAG.getConstant(C->getAPIntValue()+1, VT));
13808     }
13809   }
13810
13811   return OptimizeConditionalInDecrement(N, DAG);
13812 }
13813
13814 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13815                                              DAGCombinerInfo &DCI) const {
13816   SelectionDAG &DAG = DCI.DAG;
13817   switch (N->getOpcode()) {
13818   default: break;
13819   case ISD::EXTRACT_VECTOR_ELT:
13820     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13821   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
13822   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
13823   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
13824   case ISD::SUB:            return PerformSubCombine(N, DAG);
13825   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
13826   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
13827   case ISD::SHL:
13828   case ISD::SRA:
13829   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
13830   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
13831   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
13832   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
13833   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
13834   case X86ISD::FXOR:
13835   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
13836   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
13837   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
13838   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
13839   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
13840   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
13841   case X86ISD::SHUFPS:      // Handle all target specific shuffles
13842   case X86ISD::SHUFPD:
13843   case X86ISD::PALIGN:
13844   case X86ISD::PUNPCKHBW:
13845   case X86ISD::PUNPCKHWD:
13846   case X86ISD::PUNPCKHDQ:
13847   case X86ISD::PUNPCKHQDQ:
13848   case X86ISD::UNPCKHPS:
13849   case X86ISD::UNPCKHPD:
13850   case X86ISD::VUNPCKHPSY:
13851   case X86ISD::VUNPCKHPDY:
13852   case X86ISD::PUNPCKLBW:
13853   case X86ISD::PUNPCKLWD:
13854   case X86ISD::PUNPCKLDQ:
13855   case X86ISD::PUNPCKLQDQ:
13856   case X86ISD::UNPCKLPS:
13857   case X86ISD::UNPCKLPD:
13858   case X86ISD::VUNPCKLPSY:
13859   case X86ISD::VUNPCKLPDY:
13860   case X86ISD::MOVHLPS:
13861   case X86ISD::MOVLHPS:
13862   case X86ISD::PSHUFD:
13863   case X86ISD::PSHUFHW:
13864   case X86ISD::PSHUFLW:
13865   case X86ISD::MOVSS:
13866   case X86ISD::MOVSD:
13867   case X86ISD::VPERMILPS:
13868   case X86ISD::VPERMILPSY:
13869   case X86ISD::VPERMILPD:
13870   case X86ISD::VPERMILPDY:
13871   case X86ISD::VPERM2F128:
13872   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13873   }
13874
13875   return SDValue();
13876 }
13877
13878 /// isTypeDesirableForOp - Return true if the target has native support for
13879 /// the specified value type and it is 'desirable' to use the type for the
13880 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13881 /// instruction encodings are longer and some i16 instructions are slow.
13882 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13883   if (!isTypeLegal(VT))
13884     return false;
13885   if (VT != MVT::i16)
13886     return true;
13887
13888   switch (Opc) {
13889   default:
13890     return true;
13891   case ISD::LOAD:
13892   case ISD::SIGN_EXTEND:
13893   case ISD::ZERO_EXTEND:
13894   case ISD::ANY_EXTEND:
13895   case ISD::SHL:
13896   case ISD::SRL:
13897   case ISD::SUB:
13898   case ISD::ADD:
13899   case ISD::MUL:
13900   case ISD::AND:
13901   case ISD::OR:
13902   case ISD::XOR:
13903     return false;
13904   }
13905 }
13906
13907 /// IsDesirableToPromoteOp - This method query the target whether it is
13908 /// beneficial for dag combiner to promote the specified node. If true, it
13909 /// should return the desired promotion type by reference.
13910 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13911   EVT VT = Op.getValueType();
13912   if (VT != MVT::i16)
13913     return false;
13914
13915   bool Promote = false;
13916   bool Commute = false;
13917   switch (Op.getOpcode()) {
13918   default: break;
13919   case ISD::LOAD: {
13920     LoadSDNode *LD = cast<LoadSDNode>(Op);
13921     // If the non-extending load has a single use and it's not live out, then it
13922     // might be folded.
13923     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13924                                                      Op.hasOneUse()*/) {
13925       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13926              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13927         // The only case where we'd want to promote LOAD (rather then it being
13928         // promoted as an operand is when it's only use is liveout.
13929         if (UI->getOpcode() != ISD::CopyToReg)
13930           return false;
13931       }
13932     }
13933     Promote = true;
13934     break;
13935   }
13936   case ISD::SIGN_EXTEND:
13937   case ISD::ZERO_EXTEND:
13938   case ISD::ANY_EXTEND:
13939     Promote = true;
13940     break;
13941   case ISD::SHL:
13942   case ISD::SRL: {
13943     SDValue N0 = Op.getOperand(0);
13944     // Look out for (store (shl (load), x)).
13945     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13946       return false;
13947     Promote = true;
13948     break;
13949   }
13950   case ISD::ADD:
13951   case ISD::MUL:
13952   case ISD::AND:
13953   case ISD::OR:
13954   case ISD::XOR:
13955     Commute = true;
13956     // fallthrough
13957   case ISD::SUB: {
13958     SDValue N0 = Op.getOperand(0);
13959     SDValue N1 = Op.getOperand(1);
13960     if (!Commute && MayFoldLoad(N1))
13961       return false;
13962     // Avoid disabling potential load folding opportunities.
13963     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13964       return false;
13965     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13966       return false;
13967     Promote = true;
13968   }
13969   }
13970
13971   PVT = MVT::i32;
13972   return Promote;
13973 }
13974
13975 //===----------------------------------------------------------------------===//
13976 //                           X86 Inline Assembly Support
13977 //===----------------------------------------------------------------------===//
13978
13979 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
13980   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13981
13982   std::string AsmStr = IA->getAsmString();
13983
13984   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
13985   SmallVector<StringRef, 4> AsmPieces;
13986   SplitString(AsmStr, AsmPieces, ";\n");
13987
13988   switch (AsmPieces.size()) {
13989   default: return false;
13990   case 1:
13991     AsmStr = AsmPieces[0];
13992     AsmPieces.clear();
13993     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
13994
13995     // FIXME: this should verify that we are targeting a 486 or better.  If not,
13996     // we will turn this bswap into something that will be lowered to logical ops
13997     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
13998     // so don't worry about this.
13999     // bswap $0
14000     if (AsmPieces.size() == 2 &&
14001         (AsmPieces[0] == "bswap" ||
14002          AsmPieces[0] == "bswapq" ||
14003          AsmPieces[0] == "bswapl") &&
14004         (AsmPieces[1] == "$0" ||
14005          AsmPieces[1] == "${0:q}")) {
14006       // No need to check constraints, nothing other than the equivalent of
14007       // "=r,0" would be valid here.
14008       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14009       if (!Ty || Ty->getBitWidth() % 16 != 0)
14010         return false;
14011       return IntrinsicLowering::LowerToByteSwap(CI);
14012     }
14013     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14014     if (CI->getType()->isIntegerTy(16) &&
14015         AsmPieces.size() == 3 &&
14016         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14017         AsmPieces[1] == "$$8," &&
14018         AsmPieces[2] == "${0:w}" &&
14019         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14020       AsmPieces.clear();
14021       const std::string &ConstraintsStr = IA->getConstraintString();
14022       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14023       std::sort(AsmPieces.begin(), AsmPieces.end());
14024       if (AsmPieces.size() == 4 &&
14025           AsmPieces[0] == "~{cc}" &&
14026           AsmPieces[1] == "~{dirflag}" &&
14027           AsmPieces[2] == "~{flags}" &&
14028           AsmPieces[3] == "~{fpsr}") {
14029         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14030         if (!Ty || Ty->getBitWidth() % 16 != 0)
14031           return false;
14032         return IntrinsicLowering::LowerToByteSwap(CI);
14033       }
14034     }
14035     break;
14036   case 3:
14037     if (CI->getType()->isIntegerTy(32) &&
14038         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14039       SmallVector<StringRef, 4> Words;
14040       SplitString(AsmPieces[0], Words, " \t,");
14041       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14042           Words[2] == "${0:w}") {
14043         Words.clear();
14044         SplitString(AsmPieces[1], Words, " \t,");
14045         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14046             Words[2] == "$0") {
14047           Words.clear();
14048           SplitString(AsmPieces[2], Words, " \t,");
14049           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14050               Words[2] == "${0:w}") {
14051             AsmPieces.clear();
14052             const std::string &ConstraintsStr = IA->getConstraintString();
14053             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14054             std::sort(AsmPieces.begin(), AsmPieces.end());
14055             if (AsmPieces.size() == 4 &&
14056                 AsmPieces[0] == "~{cc}" &&
14057                 AsmPieces[1] == "~{dirflag}" &&
14058                 AsmPieces[2] == "~{flags}" &&
14059                 AsmPieces[3] == "~{fpsr}") {
14060               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14061               if (!Ty || Ty->getBitWidth() % 16 != 0)
14062                 return false;
14063               return IntrinsicLowering::LowerToByteSwap(CI);
14064             }
14065           }
14066         }
14067       }
14068     }
14069
14070     if (CI->getType()->isIntegerTy(64)) {
14071       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14072       if (Constraints.size() >= 2 &&
14073           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14074           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14075         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14076         SmallVector<StringRef, 4> Words;
14077         SplitString(AsmPieces[0], Words, " \t");
14078         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14079           Words.clear();
14080           SplitString(AsmPieces[1], Words, " \t");
14081           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14082             Words.clear();
14083             SplitString(AsmPieces[2], Words, " \t,");
14084             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14085                 Words[2] == "%edx") {
14086               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14087               if (!Ty || Ty->getBitWidth() % 16 != 0)
14088                 return false;
14089               return IntrinsicLowering::LowerToByteSwap(CI);
14090             }
14091           }
14092         }
14093       }
14094     }
14095     break;
14096   }
14097   return false;
14098 }
14099
14100
14101
14102 /// getConstraintType - Given a constraint letter, return the type of
14103 /// constraint it is for this target.
14104 X86TargetLowering::ConstraintType
14105 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14106   if (Constraint.size() == 1) {
14107     switch (Constraint[0]) {
14108     case 'R':
14109     case 'q':
14110     case 'Q':
14111     case 'f':
14112     case 't':
14113     case 'u':
14114     case 'y':
14115     case 'x':
14116     case 'Y':
14117     case 'l':
14118       return C_RegisterClass;
14119     case 'a':
14120     case 'b':
14121     case 'c':
14122     case 'd':
14123     case 'S':
14124     case 'D':
14125     case 'A':
14126       return C_Register;
14127     case 'I':
14128     case 'J':
14129     case 'K':
14130     case 'L':
14131     case 'M':
14132     case 'N':
14133     case 'G':
14134     case 'C':
14135     case 'e':
14136     case 'Z':
14137       return C_Other;
14138     default:
14139       break;
14140     }
14141   }
14142   return TargetLowering::getConstraintType(Constraint);
14143 }
14144
14145 /// Examine constraint type and operand type and determine a weight value.
14146 /// This object must already have been set up with the operand type
14147 /// and the current alternative constraint selected.
14148 TargetLowering::ConstraintWeight
14149   X86TargetLowering::getSingleConstraintMatchWeight(
14150     AsmOperandInfo &info, const char *constraint) const {
14151   ConstraintWeight weight = CW_Invalid;
14152   Value *CallOperandVal = info.CallOperandVal;
14153     // If we don't have a value, we can't do a match,
14154     // but allow it at the lowest weight.
14155   if (CallOperandVal == NULL)
14156     return CW_Default;
14157   Type *type = CallOperandVal->getType();
14158   // Look at the constraint type.
14159   switch (*constraint) {
14160   default:
14161     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14162   case 'R':
14163   case 'q':
14164   case 'Q':
14165   case 'a':
14166   case 'b':
14167   case 'c':
14168   case 'd':
14169   case 'S':
14170   case 'D':
14171   case 'A':
14172     if (CallOperandVal->getType()->isIntegerTy())
14173       weight = CW_SpecificReg;
14174     break;
14175   case 'f':
14176   case 't':
14177   case 'u':
14178       if (type->isFloatingPointTy())
14179         weight = CW_SpecificReg;
14180       break;
14181   case 'y':
14182       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14183         weight = CW_SpecificReg;
14184       break;
14185   case 'x':
14186   case 'Y':
14187     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14188       weight = CW_Register;
14189     break;
14190   case 'I':
14191     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14192       if (C->getZExtValue() <= 31)
14193         weight = CW_Constant;
14194     }
14195     break;
14196   case 'J':
14197     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14198       if (C->getZExtValue() <= 63)
14199         weight = CW_Constant;
14200     }
14201     break;
14202   case 'K':
14203     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14204       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14205         weight = CW_Constant;
14206     }
14207     break;
14208   case 'L':
14209     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14210       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14211         weight = CW_Constant;
14212     }
14213     break;
14214   case 'M':
14215     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14216       if (C->getZExtValue() <= 3)
14217         weight = CW_Constant;
14218     }
14219     break;
14220   case 'N':
14221     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14222       if (C->getZExtValue() <= 0xff)
14223         weight = CW_Constant;
14224     }
14225     break;
14226   case 'G':
14227   case 'C':
14228     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14229       weight = CW_Constant;
14230     }
14231     break;
14232   case 'e':
14233     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14234       if ((C->getSExtValue() >= -0x80000000LL) &&
14235           (C->getSExtValue() <= 0x7fffffffLL))
14236         weight = CW_Constant;
14237     }
14238     break;
14239   case 'Z':
14240     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14241       if (C->getZExtValue() <= 0xffffffff)
14242         weight = CW_Constant;
14243     }
14244     break;
14245   }
14246   return weight;
14247 }
14248
14249 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14250 /// with another that has more specific requirements based on the type of the
14251 /// corresponding operand.
14252 const char *X86TargetLowering::
14253 LowerXConstraint(EVT ConstraintVT) const {
14254   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14255   // 'f' like normal targets.
14256   if (ConstraintVT.isFloatingPoint()) {
14257     if (Subtarget->hasXMMInt())
14258       return "Y";
14259     if (Subtarget->hasXMM())
14260       return "x";
14261   }
14262
14263   return TargetLowering::LowerXConstraint(ConstraintVT);
14264 }
14265
14266 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14267 /// vector.  If it is invalid, don't add anything to Ops.
14268 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14269                                                      std::string &Constraint,
14270                                                      std::vector<SDValue>&Ops,
14271                                                      SelectionDAG &DAG) const {
14272   SDValue Result(0, 0);
14273
14274   // Only support length 1 constraints for now.
14275   if (Constraint.length() > 1) return;
14276
14277   char ConstraintLetter = Constraint[0];
14278   switch (ConstraintLetter) {
14279   default: break;
14280   case 'I':
14281     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14282       if (C->getZExtValue() <= 31) {
14283         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14284         break;
14285       }
14286     }
14287     return;
14288   case 'J':
14289     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14290       if (C->getZExtValue() <= 63) {
14291         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14292         break;
14293       }
14294     }
14295     return;
14296   case 'K':
14297     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14298       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14299         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14300         break;
14301       }
14302     }
14303     return;
14304   case 'N':
14305     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14306       if (C->getZExtValue() <= 255) {
14307         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14308         break;
14309       }
14310     }
14311     return;
14312   case 'e': {
14313     // 32-bit signed value
14314     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14315       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14316                                            C->getSExtValue())) {
14317         // Widen to 64 bits here to get it sign extended.
14318         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14319         break;
14320       }
14321     // FIXME gcc accepts some relocatable values here too, but only in certain
14322     // memory models; it's complicated.
14323     }
14324     return;
14325   }
14326   case 'Z': {
14327     // 32-bit unsigned value
14328     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14329       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14330                                            C->getZExtValue())) {
14331         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14332         break;
14333       }
14334     }
14335     // FIXME gcc accepts some relocatable values here too, but only in certain
14336     // memory models; it's complicated.
14337     return;
14338   }
14339   case 'i': {
14340     // Literal immediates are always ok.
14341     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14342       // Widen to 64 bits here to get it sign extended.
14343       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14344       break;
14345     }
14346
14347     // In any sort of PIC mode addresses need to be computed at runtime by
14348     // adding in a register or some sort of table lookup.  These can't
14349     // be used as immediates.
14350     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14351       return;
14352
14353     // If we are in non-pic codegen mode, we allow the address of a global (with
14354     // an optional displacement) to be used with 'i'.
14355     GlobalAddressSDNode *GA = 0;
14356     int64_t Offset = 0;
14357
14358     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14359     while (1) {
14360       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14361         Offset += GA->getOffset();
14362         break;
14363       } else if (Op.getOpcode() == ISD::ADD) {
14364         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14365           Offset += C->getZExtValue();
14366           Op = Op.getOperand(0);
14367           continue;
14368         }
14369       } else if (Op.getOpcode() == ISD::SUB) {
14370         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14371           Offset += -C->getZExtValue();
14372           Op = Op.getOperand(0);
14373           continue;
14374         }
14375       }
14376
14377       // Otherwise, this isn't something we can handle, reject it.
14378       return;
14379     }
14380
14381     const GlobalValue *GV = GA->getGlobal();
14382     // If we require an extra load to get this address, as in PIC mode, we
14383     // can't accept it.
14384     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14385                                                         getTargetMachine())))
14386       return;
14387
14388     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14389                                         GA->getValueType(0), Offset);
14390     break;
14391   }
14392   }
14393
14394   if (Result.getNode()) {
14395     Ops.push_back(Result);
14396     return;
14397   }
14398   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14399 }
14400
14401 std::pair<unsigned, const TargetRegisterClass*>
14402 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14403                                                 EVT VT) const {
14404   // First, see if this is a constraint that directly corresponds to an LLVM
14405   // register class.
14406   if (Constraint.size() == 1) {
14407     // GCC Constraint Letters
14408     switch (Constraint[0]) {
14409     default: break;
14410       // TODO: Slight differences here in allocation order and leaving
14411       // RIP in the class. Do they matter any more here than they do
14412       // in the normal allocation?
14413     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14414       if (Subtarget->is64Bit()) {
14415         if (VT == MVT::i32 || VT == MVT::f32)
14416           return std::make_pair(0U, X86::GR32RegisterClass);
14417         else if (VT == MVT::i16)
14418           return std::make_pair(0U, X86::GR16RegisterClass);
14419         else if (VT == MVT::i8 || VT == MVT::i1)
14420           return std::make_pair(0U, X86::GR8RegisterClass);
14421         else if (VT == MVT::i64 || VT == MVT::f64)
14422           return std::make_pair(0U, X86::GR64RegisterClass);
14423         break;
14424       }
14425       // 32-bit fallthrough
14426     case 'Q':   // Q_REGS
14427       if (VT == MVT::i32 || VT == MVT::f32)
14428         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14429       else if (VT == MVT::i16)
14430         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14431       else if (VT == MVT::i8 || VT == MVT::i1)
14432         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14433       else if (VT == MVT::i64)
14434         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14435       break;
14436     case 'r':   // GENERAL_REGS
14437     case 'l':   // INDEX_REGS
14438       if (VT == MVT::i8 || VT == MVT::i1)
14439         return std::make_pair(0U, X86::GR8RegisterClass);
14440       if (VT == MVT::i16)
14441         return std::make_pair(0U, X86::GR16RegisterClass);
14442       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14443         return std::make_pair(0U, X86::GR32RegisterClass);
14444       return std::make_pair(0U, X86::GR64RegisterClass);
14445     case 'R':   // LEGACY_REGS
14446       if (VT == MVT::i8 || VT == MVT::i1)
14447         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14448       if (VT == MVT::i16)
14449         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14450       if (VT == MVT::i32 || !Subtarget->is64Bit())
14451         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14452       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14453     case 'f':  // FP Stack registers.
14454       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14455       // value to the correct fpstack register class.
14456       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14457         return std::make_pair(0U, X86::RFP32RegisterClass);
14458       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14459         return std::make_pair(0U, X86::RFP64RegisterClass);
14460       return std::make_pair(0U, X86::RFP80RegisterClass);
14461     case 'y':   // MMX_REGS if MMX allowed.
14462       if (!Subtarget->hasMMX()) break;
14463       return std::make_pair(0U, X86::VR64RegisterClass);
14464     case 'Y':   // SSE_REGS if SSE2 allowed
14465       if (!Subtarget->hasXMMInt()) break;
14466       // FALL THROUGH.
14467     case 'x':   // SSE_REGS if SSE1 allowed
14468       if (!Subtarget->hasXMM()) break;
14469
14470       switch (VT.getSimpleVT().SimpleTy) {
14471       default: break;
14472       // Scalar SSE types.
14473       case MVT::f32:
14474       case MVT::i32:
14475         return std::make_pair(0U, X86::FR32RegisterClass);
14476       case MVT::f64:
14477       case MVT::i64:
14478         return std::make_pair(0U, X86::FR64RegisterClass);
14479       // Vector types.
14480       case MVT::v16i8:
14481       case MVT::v8i16:
14482       case MVT::v4i32:
14483       case MVT::v2i64:
14484       case MVT::v4f32:
14485       case MVT::v2f64:
14486         return std::make_pair(0U, X86::VR128RegisterClass);
14487       }
14488       break;
14489     }
14490   }
14491
14492   // Use the default implementation in TargetLowering to convert the register
14493   // constraint into a member of a register class.
14494   std::pair<unsigned, const TargetRegisterClass*> Res;
14495   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14496
14497   // Not found as a standard register?
14498   if (Res.second == 0) {
14499     // Map st(0) -> st(7) -> ST0
14500     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14501         tolower(Constraint[1]) == 's' &&
14502         tolower(Constraint[2]) == 't' &&
14503         Constraint[3] == '(' &&
14504         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14505         Constraint[5] == ')' &&
14506         Constraint[6] == '}') {
14507
14508       Res.first = X86::ST0+Constraint[4]-'0';
14509       Res.second = X86::RFP80RegisterClass;
14510       return Res;
14511     }
14512
14513     // GCC allows "st(0)" to be called just plain "st".
14514     if (StringRef("{st}").equals_lower(Constraint)) {
14515       Res.first = X86::ST0;
14516       Res.second = X86::RFP80RegisterClass;
14517       return Res;
14518     }
14519
14520     // flags -> EFLAGS
14521     if (StringRef("{flags}").equals_lower(Constraint)) {
14522       Res.first = X86::EFLAGS;
14523       Res.second = X86::CCRRegisterClass;
14524       return Res;
14525     }
14526
14527     // 'A' means EAX + EDX.
14528     if (Constraint == "A") {
14529       Res.first = X86::EAX;
14530       Res.second = X86::GR32_ADRegisterClass;
14531       return Res;
14532     }
14533     return Res;
14534   }
14535
14536   // Otherwise, check to see if this is a register class of the wrong value
14537   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14538   // turn into {ax},{dx}.
14539   if (Res.second->hasType(VT))
14540     return Res;   // Correct type already, nothing to do.
14541
14542   // All of the single-register GCC register classes map their values onto
14543   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14544   // really want an 8-bit or 32-bit register, map to the appropriate register
14545   // class and return the appropriate register.
14546   if (Res.second == X86::GR16RegisterClass) {
14547     if (VT == MVT::i8) {
14548       unsigned DestReg = 0;
14549       switch (Res.first) {
14550       default: break;
14551       case X86::AX: DestReg = X86::AL; break;
14552       case X86::DX: DestReg = X86::DL; break;
14553       case X86::CX: DestReg = X86::CL; break;
14554       case X86::BX: DestReg = X86::BL; break;
14555       }
14556       if (DestReg) {
14557         Res.first = DestReg;
14558         Res.second = X86::GR8RegisterClass;
14559       }
14560     } else if (VT == MVT::i32) {
14561       unsigned DestReg = 0;
14562       switch (Res.first) {
14563       default: break;
14564       case X86::AX: DestReg = X86::EAX; break;
14565       case X86::DX: DestReg = X86::EDX; break;
14566       case X86::CX: DestReg = X86::ECX; break;
14567       case X86::BX: DestReg = X86::EBX; break;
14568       case X86::SI: DestReg = X86::ESI; break;
14569       case X86::DI: DestReg = X86::EDI; break;
14570       case X86::BP: DestReg = X86::EBP; break;
14571       case X86::SP: DestReg = X86::ESP; break;
14572       }
14573       if (DestReg) {
14574         Res.first = DestReg;
14575         Res.second = X86::GR32RegisterClass;
14576       }
14577     } else if (VT == MVT::i64) {
14578       unsigned DestReg = 0;
14579       switch (Res.first) {
14580       default: break;
14581       case X86::AX: DestReg = X86::RAX; break;
14582       case X86::DX: DestReg = X86::RDX; break;
14583       case X86::CX: DestReg = X86::RCX; break;
14584       case X86::BX: DestReg = X86::RBX; break;
14585       case X86::SI: DestReg = X86::RSI; break;
14586       case X86::DI: DestReg = X86::RDI; break;
14587       case X86::BP: DestReg = X86::RBP; break;
14588       case X86::SP: DestReg = X86::RSP; break;
14589       }
14590       if (DestReg) {
14591         Res.first = DestReg;
14592         Res.second = X86::GR64RegisterClass;
14593       }
14594     }
14595   } else if (Res.second == X86::FR32RegisterClass ||
14596              Res.second == X86::FR64RegisterClass ||
14597              Res.second == X86::VR128RegisterClass) {
14598     // Handle references to XMM physical registers that got mapped into the
14599     // wrong class.  This can happen with constraints like {xmm0} where the
14600     // target independent register mapper will just pick the first match it can
14601     // find, ignoring the required type.
14602     if (VT == MVT::f32)
14603       Res.second = X86::FR32RegisterClass;
14604     else if (VT == MVT::f64)
14605       Res.second = X86::FR64RegisterClass;
14606     else if (X86::VR128RegisterClass->hasType(VT))
14607       Res.second = X86::VR128RegisterClass;
14608   }
14609
14610   return Res;
14611 }