Move more code around and duplicate AVX patterns: MOVHPS and MOVLPS
[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
525   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
526     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
527                        MVT::i64 : MVT::i32, Custom);
528   else if (EnableSegmentedStacks)
529     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
530                        MVT::i64 : MVT::i32, Custom);
531   else
532     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
533                        MVT::i64 : MVT::i32, Expand);
534
535   if (!UseSoftFloat && X86ScalarSSEf64) {
536     // f32 and f64 use SSE.
537     // Set up the FP register classes.
538     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
539     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
540
541     // Use ANDPD to simulate FABS.
542     setOperationAction(ISD::FABS , MVT::f64, Custom);
543     setOperationAction(ISD::FABS , MVT::f32, Custom);
544
545     // Use XORP to simulate FNEG.
546     setOperationAction(ISD::FNEG , MVT::f64, Custom);
547     setOperationAction(ISD::FNEG , MVT::f32, Custom);
548
549     // Use ANDPD and ORPD to simulate FCOPYSIGN.
550     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
551     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
552
553     // Lower this to FGETSIGNx86 plus an AND.
554     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
555     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
556
557     // We don't support sin/cos/fmod
558     setOperationAction(ISD::FSIN , MVT::f64, Expand);
559     setOperationAction(ISD::FCOS , MVT::f64, Expand);
560     setOperationAction(ISD::FSIN , MVT::f32, Expand);
561     setOperationAction(ISD::FCOS , MVT::f32, Expand);
562
563     // Expand FP immediates into loads from the stack, except for the special
564     // cases we handle.
565     addLegalFPImmediate(APFloat(+0.0)); // xorpd
566     addLegalFPImmediate(APFloat(+0.0f)); // xorps
567   } else if (!UseSoftFloat && X86ScalarSSEf32) {
568     // Use SSE for f32, x87 for f64.
569     // Set up the FP register classes.
570     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
571     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
572
573     // Use ANDPS to simulate FABS.
574     setOperationAction(ISD::FABS , MVT::f32, Custom);
575
576     // Use XORP to simulate FNEG.
577     setOperationAction(ISD::FNEG , MVT::f32, Custom);
578
579     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
580
581     // Use ANDPS and ORPS to simulate FCOPYSIGN.
582     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
583     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
584
585     // We don't support sin/cos/fmod
586     setOperationAction(ISD::FSIN , MVT::f32, Expand);
587     setOperationAction(ISD::FCOS , MVT::f32, Expand);
588
589     // Special cases we handle for FP constants.
590     addLegalFPImmediate(APFloat(+0.0f)); // xorps
591     addLegalFPImmediate(APFloat(+0.0)); // FLD0
592     addLegalFPImmediate(APFloat(+1.0)); // FLD1
593     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
594     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
595
596     if (!UnsafeFPMath) {
597       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
598       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
599     }
600   } else if (!UseSoftFloat) {
601     // f32 and f64 in x87.
602     // Set up the FP register classes.
603     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
604     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
605
606     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
607     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
608     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
609     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
610
611     if (!UnsafeFPMath) {
612       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
613       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
614     }
615     addLegalFPImmediate(APFloat(+0.0)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
620     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
621     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
622     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
623   }
624
625   // We don't support FMA.
626   setOperationAction(ISD::FMA, MVT::f64, Expand);
627   setOperationAction(ISD::FMA, MVT::f32, Expand);
628
629   // Long double always uses X87.
630   if (!UseSoftFloat) {
631     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
632     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
634     {
635       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
636       addLegalFPImmediate(TmpFlt);  // FLD0
637       TmpFlt.changeSign();
638       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
639
640       bool ignored;
641       APFloat TmpFlt2(+1.0);
642       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
643                       &ignored);
644       addLegalFPImmediate(TmpFlt2);  // FLD1
645       TmpFlt2.changeSign();
646       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
647     }
648
649     if (!UnsafeFPMath) {
650       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
651       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
652     }
653
654     setOperationAction(ISD::FMA, MVT::f80, Expand);
655   }
656
657   // Always use a library call for pow.
658   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
660   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
661
662   setOperationAction(ISD::FLOG, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
664   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP, MVT::f80, Expand);
666   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
667
668   // First set operation action for all vector types to either promote
669   // (for widening) or expand (for scalarization). Then we will selectively
670   // turn on ones that can be effectively codegen'd.
671   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
672        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
673     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
674     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
675     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
676     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
677     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
678     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
679     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
680     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
681     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
691     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
727     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
728          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
729       setTruncStoreAction((MVT::SimpleValueType)VT,
730                           (MVT::SimpleValueType)InnerVT, Expand);
731     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
732     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
733     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
734   }
735
736   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
737   // with -msoft-float, disable use of MMX as well.
738   if (!UseSoftFloat && Subtarget->hasMMX()) {
739     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
740     // No operations on x86mmx supported, everything uses intrinsics.
741   }
742
743   // MMX-sized vectors (other than x86mmx) are expected to be expanded
744   // into smaller operations.
745   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
746   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
747   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
748   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
749   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
750   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
751   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
752   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
753   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
754   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
755   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
756   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
757   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
758   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
759   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
760   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
761   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
762   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
763   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
764   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
765   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
766   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
767   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
768   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
769   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
770   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
771   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
772   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
773   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
774
775   if (!UseSoftFloat && Subtarget->hasXMM()) {
776     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
786     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
787     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
788     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
789     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
790   }
791
792   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
793     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
794
795     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
796     // registers cannot be used even for integer operations.
797     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
798     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
799     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
800     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
801
802     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
803     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
804     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
805     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
808     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
809     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
810     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
812     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
813     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
814     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
815     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
816     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
817     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
818
819     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
820     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
821     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
822     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
823
824     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
825     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
826     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
827     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
828     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
829
830     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
831     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
832     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
833     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
834     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
835
836     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
837     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
838       EVT VT = (MVT::SimpleValueType)i;
839       // Do not attempt to custom lower non-power-of-2 vectors
840       if (!isPowerOf2_32(VT.getVectorNumElements()))
841         continue;
842       // Do not attempt to custom lower non-128-bit vectors
843       if (!VT.is128BitVector())
844         continue;
845       setOperationAction(ISD::BUILD_VECTOR,
846                          VT.getSimpleVT().SimpleTy, Custom);
847       setOperationAction(ISD::VECTOR_SHUFFLE,
848                          VT.getSimpleVT().SimpleTy, Custom);
849       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
850                          VT.getSimpleVT().SimpleTy, Custom);
851     }
852
853     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
854     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
855     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
856     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
857     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
858     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
859
860     if (Subtarget->is64Bit()) {
861       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
862       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
863     }
864
865     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
866     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
867       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
868       EVT VT = SVT;
869
870       // Do not attempt to promote non-128-bit vectors
871       if (!VT.is128BitVector())
872         continue;
873
874       setOperationAction(ISD::AND,    SVT, Promote);
875       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
876       setOperationAction(ISD::OR,     SVT, Promote);
877       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
878       setOperationAction(ISD::XOR,    SVT, Promote);
879       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
880       setOperationAction(ISD::LOAD,   SVT, Promote);
881       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
882       setOperationAction(ISD::SELECT, SVT, Promote);
883       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
884     }
885
886     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
887
888     // Custom lower v2i64 and v2f64 selects.
889     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
890     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
891     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
892     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
893
894     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
895     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
896   }
897
898   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
899     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
900     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
901     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
902     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
903     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
904     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
905     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
906     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
907     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
908     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
909
910     // FIXME: Do we need to handle scalar-to-vector here?
911     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
912
913     // Can turn SHL into an integer multiply.
914     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
915     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
916
917     // i8 and i16 vectors are custom , because the source register and source
918     // source memory operand types are not the same width.  f32 vectors are
919     // custom since the immediate controlling the insert encodes additional
920     // information.
921     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
922     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
923     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
924     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
925
926     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
927     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
928     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
929     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
930
931     if (Subtarget->is64Bit()) {
932       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
933       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
934     }
935   }
936
937   if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
938     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
939     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
940     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
941     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
942
943     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
944     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
945     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
946
947     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
948     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
949   }
950
951   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
952     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
953
954   if (!UseSoftFloat && Subtarget->hasAVX()) {
955     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
956     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
957     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
958     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
959     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
960     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
961
962     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
963     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
964     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
965
966     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
972
973     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
974     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
975     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
976     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
977     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
978     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
979
980     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
981     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
982     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
983
984     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
985     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
986     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
987     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
988     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
989     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
990
991     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
992     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
993     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
994     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
995
996     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
997     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
998     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
999     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1000
1001     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1002     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1003
1004     setOperationAction(ISD::VSETCC,            MVT::v32i8, Custom);
1005     setOperationAction(ISD::VSETCC,            MVT::v16i16, Custom);
1006     setOperationAction(ISD::VSETCC,            MVT::v8i32, Custom);
1007     setOperationAction(ISD::VSETCC,            MVT::v4i64, Custom);
1008
1009     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1010     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1011     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1012
1013     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1014     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1015     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1016     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1017
1018     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1019     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1020     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1021     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1022
1023     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1024     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1025     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1026     // Don't lower v32i8 because there is no 128-bit byte mul
1027
1028     // Custom lower several nodes for 256-bit types.
1029     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1030                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1031       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1032       EVT VT = SVT;
1033
1034       // Extract subvector is special because the value type
1035       // (result) is 128-bit but the source is 256-bit wide.
1036       if (VT.is128BitVector())
1037         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1038
1039       // Do not attempt to custom lower other non-256-bit vectors
1040       if (!VT.is256BitVector())
1041         continue;
1042
1043       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1044       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1045       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1046       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1047       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1048       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1049     }
1050
1051     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1052     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1053       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1054       EVT VT = SVT;
1055
1056       // Do not attempt to promote non-256-bit vectors
1057       if (!VT.is256BitVector())
1058         continue;
1059
1060       setOperationAction(ISD::AND,    SVT, Promote);
1061       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1062       setOperationAction(ISD::OR,     SVT, Promote);
1063       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1064       setOperationAction(ISD::XOR,    SVT, Promote);
1065       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1066       setOperationAction(ISD::LOAD,   SVT, Promote);
1067       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1068       setOperationAction(ISD::SELECT, SVT, Promote);
1069       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1070     }
1071   }
1072
1073   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1074   // of this type with custom code.
1075   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1076          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1077     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1078   }
1079
1080   // We want to custom lower some of our intrinsics.
1081   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1082
1083
1084   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1085   // handle type legalization for these operations here.
1086   //
1087   // FIXME: We really should do custom legalization for addition and
1088   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1089   // than generic legalization for 64-bit multiplication-with-overflow, though.
1090   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1091     // Add/Sub/Mul with overflow operations are custom lowered.
1092     MVT VT = IntVTs[i];
1093     setOperationAction(ISD::SADDO, VT, Custom);
1094     setOperationAction(ISD::UADDO, VT, Custom);
1095     setOperationAction(ISD::SSUBO, VT, Custom);
1096     setOperationAction(ISD::USUBO, VT, Custom);
1097     setOperationAction(ISD::SMULO, VT, Custom);
1098     setOperationAction(ISD::UMULO, VT, Custom);
1099   }
1100
1101   // There are no 8-bit 3-address imul/mul instructions
1102   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1103   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1104
1105   if (!Subtarget->is64Bit()) {
1106     // These libcalls are not available in 32-bit.
1107     setLibcallName(RTLIB::SHL_I128, 0);
1108     setLibcallName(RTLIB::SRL_I128, 0);
1109     setLibcallName(RTLIB::SRA_I128, 0);
1110   }
1111
1112   // We have target-specific dag combine patterns for the following nodes:
1113   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1114   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1115   setTargetDAGCombine(ISD::BUILD_VECTOR);
1116   setTargetDAGCombine(ISD::SELECT);
1117   setTargetDAGCombine(ISD::SHL);
1118   setTargetDAGCombine(ISD::SRA);
1119   setTargetDAGCombine(ISD::SRL);
1120   setTargetDAGCombine(ISD::OR);
1121   setTargetDAGCombine(ISD::AND);
1122   setTargetDAGCombine(ISD::ADD);
1123   setTargetDAGCombine(ISD::SUB);
1124   setTargetDAGCombine(ISD::STORE);
1125   setTargetDAGCombine(ISD::ZERO_EXTEND);
1126   setTargetDAGCombine(ISD::SINT_TO_FP);
1127   if (Subtarget->is64Bit())
1128     setTargetDAGCombine(ISD::MUL);
1129
1130   computeRegisterProperties();
1131
1132   // On Darwin, -Os means optimize for size without hurting performance,
1133   // do not reduce the limit.
1134   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1135   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1136   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1137   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1138   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1139   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1140   setPrefLoopAlignment(16);
1141   benefitFromCodePlacementOpt = true;
1142
1143   setPrefFunctionAlignment(4);
1144 }
1145
1146
1147 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1148   return MVT::i8;
1149 }
1150
1151
1152 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1153 /// the desired ByVal argument alignment.
1154 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1155   if (MaxAlign == 16)
1156     return;
1157   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1158     if (VTy->getBitWidth() == 128)
1159       MaxAlign = 16;
1160   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1161     unsigned EltAlign = 0;
1162     getMaxByValAlign(ATy->getElementType(), EltAlign);
1163     if (EltAlign > MaxAlign)
1164       MaxAlign = EltAlign;
1165   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1166     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1167       unsigned EltAlign = 0;
1168       getMaxByValAlign(STy->getElementType(i), EltAlign);
1169       if (EltAlign > MaxAlign)
1170         MaxAlign = EltAlign;
1171       if (MaxAlign == 16)
1172         break;
1173     }
1174   }
1175   return;
1176 }
1177
1178 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1179 /// function arguments in the caller parameter area. For X86, aggregates
1180 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1181 /// are at 4-byte boundaries.
1182 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1183   if (Subtarget->is64Bit()) {
1184     // Max of 8 and alignment of type.
1185     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1186     if (TyAlign > 8)
1187       return TyAlign;
1188     return 8;
1189   }
1190
1191   unsigned Align = 4;
1192   if (Subtarget->hasXMM())
1193     getMaxByValAlign(Ty, Align);
1194   return Align;
1195 }
1196
1197 /// getOptimalMemOpType - Returns the target specific optimal type for load
1198 /// and store operations as a result of memset, memcpy, and memmove
1199 /// lowering. If DstAlign is zero that means it's safe to destination
1200 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1201 /// means there isn't a need to check it against alignment requirement,
1202 /// probably because the source does not need to be loaded. If
1203 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1204 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1205 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1206 /// constant so it does not need to be loaded.
1207 /// It returns EVT::Other if the type should be determined using generic
1208 /// target-independent logic.
1209 EVT
1210 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1211                                        unsigned DstAlign, unsigned SrcAlign,
1212                                        bool NonScalarIntSafe,
1213                                        bool MemcpyStrSrc,
1214                                        MachineFunction &MF) const {
1215   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1216   // linux.  This is because the stack realignment code can't handle certain
1217   // cases like PR2962.  This should be removed when PR2962 is fixed.
1218   const Function *F = MF.getFunction();
1219   if (NonScalarIntSafe &&
1220       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1221     if (Size >= 16 &&
1222         (Subtarget->isUnalignedMemAccessFast() ||
1223          ((DstAlign == 0 || DstAlign >= 16) &&
1224           (SrcAlign == 0 || SrcAlign >= 16))) &&
1225         Subtarget->getStackAlignment() >= 16) {
1226       if (Subtarget->hasSSE2())
1227         return MVT::v4i32;
1228       if (Subtarget->hasSSE1())
1229         return MVT::v4f32;
1230     } else if (!MemcpyStrSrc && Size >= 8 &&
1231                !Subtarget->is64Bit() &&
1232                Subtarget->getStackAlignment() >= 8 &&
1233                Subtarget->hasXMMInt()) {
1234       // Do not use f64 to lower memcpy if source is string constant. It's
1235       // better to use i32 to avoid the loads.
1236       return MVT::f64;
1237     }
1238   }
1239   if (Subtarget->is64Bit() && Size >= 8)
1240     return MVT::i64;
1241   return MVT::i32;
1242 }
1243
1244 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1245 /// current function.  The returned value is a member of the
1246 /// MachineJumpTableInfo::JTEntryKind enum.
1247 unsigned X86TargetLowering::getJumpTableEncoding() const {
1248   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1249   // symbol.
1250   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1251       Subtarget->isPICStyleGOT())
1252     return MachineJumpTableInfo::EK_Custom32;
1253
1254   // Otherwise, use the normal jump table encoding heuristics.
1255   return TargetLowering::getJumpTableEncoding();
1256 }
1257
1258 const MCExpr *
1259 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1260                                              const MachineBasicBlock *MBB,
1261                                              unsigned uid,MCContext &Ctx) const{
1262   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1263          Subtarget->isPICStyleGOT());
1264   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1265   // entries.
1266   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1267                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1268 }
1269
1270 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1271 /// jumptable.
1272 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1273                                                     SelectionDAG &DAG) const {
1274   if (!Subtarget->is64Bit())
1275     // This doesn't have DebugLoc associated with it, but is not really the
1276     // same as a Register.
1277     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1278   return Table;
1279 }
1280
1281 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1282 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1283 /// MCExpr.
1284 const MCExpr *X86TargetLowering::
1285 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1286                              MCContext &Ctx) const {
1287   // X86-64 uses RIP relative addressing based on the jump table label.
1288   if (Subtarget->isPICStyleRIPRel())
1289     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1290
1291   // Otherwise, the reference is relative to the PIC base.
1292   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1293 }
1294
1295 // FIXME: Why this routine is here? Move to RegInfo!
1296 std::pair<const TargetRegisterClass*, uint8_t>
1297 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1298   const TargetRegisterClass *RRC = 0;
1299   uint8_t Cost = 1;
1300   switch (VT.getSimpleVT().SimpleTy) {
1301   default:
1302     return TargetLowering::findRepresentativeClass(VT);
1303   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1304     RRC = (Subtarget->is64Bit()
1305            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1306     break;
1307   case MVT::x86mmx:
1308     RRC = X86::VR64RegisterClass;
1309     break;
1310   case MVT::f32: case MVT::f64:
1311   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1312   case MVT::v4f32: case MVT::v2f64:
1313   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1314   case MVT::v4f64:
1315     RRC = X86::VR128RegisterClass;
1316     break;
1317   }
1318   return std::make_pair(RRC, Cost);
1319 }
1320
1321 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1322                                                unsigned &Offset) const {
1323   if (!Subtarget->isTargetLinux())
1324     return false;
1325
1326   if (Subtarget->is64Bit()) {
1327     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1328     Offset = 0x28;
1329     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1330       AddressSpace = 256;
1331     else
1332       AddressSpace = 257;
1333   } else {
1334     // %gs:0x14 on i386
1335     Offset = 0x14;
1336     AddressSpace = 256;
1337   }
1338   return true;
1339 }
1340
1341
1342 //===----------------------------------------------------------------------===//
1343 //               Return Value Calling Convention Implementation
1344 //===----------------------------------------------------------------------===//
1345
1346 #include "X86GenCallingConv.inc"
1347
1348 bool
1349 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1350                                   MachineFunction &MF, bool isVarArg,
1351                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1352                         LLVMContext &Context) const {
1353   SmallVector<CCValAssign, 16> RVLocs;
1354   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1355                  RVLocs, Context);
1356   return CCInfo.CheckReturn(Outs, RetCC_X86);
1357 }
1358
1359 SDValue
1360 X86TargetLowering::LowerReturn(SDValue Chain,
1361                                CallingConv::ID CallConv, bool isVarArg,
1362                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1363                                const SmallVectorImpl<SDValue> &OutVals,
1364                                DebugLoc dl, SelectionDAG &DAG) const {
1365   MachineFunction &MF = DAG.getMachineFunction();
1366   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1367
1368   SmallVector<CCValAssign, 16> RVLocs;
1369   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1370                  RVLocs, *DAG.getContext());
1371   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1372
1373   // Add the regs to the liveout set for the function.
1374   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1375   for (unsigned i = 0; i != RVLocs.size(); ++i)
1376     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1377       MRI.addLiveOut(RVLocs[i].getLocReg());
1378
1379   SDValue Flag;
1380
1381   SmallVector<SDValue, 6> RetOps;
1382   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1383   // Operand #1 = Bytes To Pop
1384   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1385                    MVT::i16));
1386
1387   // Copy the result values into the output registers.
1388   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1389     CCValAssign &VA = RVLocs[i];
1390     assert(VA.isRegLoc() && "Can only return in registers!");
1391     SDValue ValToCopy = OutVals[i];
1392     EVT ValVT = ValToCopy.getValueType();
1393
1394     // If this is x86-64, and we disabled SSE, we can't return FP values,
1395     // or SSE or MMX vectors.
1396     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1397          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1398           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1399       report_fatal_error("SSE register return with SSE disabled");
1400     }
1401     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1402     // llvm-gcc has never done it right and no one has noticed, so this
1403     // should be OK for now.
1404     if (ValVT == MVT::f64 &&
1405         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1406       report_fatal_error("SSE2 register return with SSE2 disabled");
1407
1408     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1409     // the RET instruction and handled by the FP Stackifier.
1410     if (VA.getLocReg() == X86::ST0 ||
1411         VA.getLocReg() == X86::ST1) {
1412       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1413       // change the value to the FP stack register class.
1414       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1415         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1416       RetOps.push_back(ValToCopy);
1417       // Don't emit a copytoreg.
1418       continue;
1419     }
1420
1421     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1422     // which is returned in RAX / RDX.
1423     if (Subtarget->is64Bit()) {
1424       if (ValVT == MVT::x86mmx) {
1425         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1426           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1427           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1428                                   ValToCopy);
1429           // If we don't have SSE2 available, convert to v4f32 so the generated
1430           // register is legal.
1431           if (!Subtarget->hasSSE2())
1432             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1433         }
1434       }
1435     }
1436
1437     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1438     Flag = Chain.getValue(1);
1439   }
1440
1441   // The x86-64 ABI for returning structs by value requires that we copy
1442   // the sret argument into %rax for the return. We saved the argument into
1443   // a virtual register in the entry block, so now we copy the value out
1444   // and into %rax.
1445   if (Subtarget->is64Bit() &&
1446       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1447     MachineFunction &MF = DAG.getMachineFunction();
1448     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1449     unsigned Reg = FuncInfo->getSRetReturnReg();
1450     assert(Reg &&
1451            "SRetReturnReg should have been set in LowerFormalArguments().");
1452     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1453
1454     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1455     Flag = Chain.getValue(1);
1456
1457     // RAX now acts like a return value.
1458     MRI.addLiveOut(X86::RAX);
1459   }
1460
1461   RetOps[0] = Chain;  // Update chain.
1462
1463   // Add the flag if we have it.
1464   if (Flag.getNode())
1465     RetOps.push_back(Flag);
1466
1467   return DAG.getNode(X86ISD::RET_FLAG, dl,
1468                      MVT::Other, &RetOps[0], RetOps.size());
1469 }
1470
1471 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1472   if (N->getNumValues() != 1)
1473     return false;
1474   if (!N->hasNUsesOfValue(1, 0))
1475     return false;
1476
1477   SDNode *Copy = *N->use_begin();
1478   if (Copy->getOpcode() != ISD::CopyToReg &&
1479       Copy->getOpcode() != ISD::FP_EXTEND)
1480     return false;
1481
1482   bool HasRet = false;
1483   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1484        UI != UE; ++UI) {
1485     if (UI->getOpcode() != X86ISD::RET_FLAG)
1486       return false;
1487     HasRet = true;
1488   }
1489
1490   return HasRet;
1491 }
1492
1493 EVT
1494 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1495                                             ISD::NodeType ExtendKind) const {
1496   MVT ReturnMVT;
1497   // TODO: Is this also valid on 32-bit?
1498   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1499     ReturnMVT = MVT::i8;
1500   else
1501     ReturnMVT = MVT::i32;
1502
1503   EVT MinVT = getRegisterType(Context, ReturnMVT);
1504   return VT.bitsLT(MinVT) ? MinVT : VT;
1505 }
1506
1507 /// LowerCallResult - Lower the result values of a call into the
1508 /// appropriate copies out of appropriate physical registers.
1509 ///
1510 SDValue
1511 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1512                                    CallingConv::ID CallConv, bool isVarArg,
1513                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1514                                    DebugLoc dl, SelectionDAG &DAG,
1515                                    SmallVectorImpl<SDValue> &InVals) const {
1516
1517   // Assign locations to each value returned by this call.
1518   SmallVector<CCValAssign, 16> RVLocs;
1519   bool Is64Bit = Subtarget->is64Bit();
1520   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1521                  getTargetMachine(), RVLocs, *DAG.getContext());
1522   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1523
1524   // Copy all of the result registers out of their specified physreg.
1525   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1526     CCValAssign &VA = RVLocs[i];
1527     EVT CopyVT = VA.getValVT();
1528
1529     // If this is x86-64, and we disabled SSE, we can't return FP values
1530     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1531         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1532       report_fatal_error("SSE register return with SSE disabled");
1533     }
1534
1535     SDValue Val;
1536
1537     // If this is a call to a function that returns an fp value on the floating
1538     // point stack, we must guarantee the the value is popped from the stack, so
1539     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1540     // if the return value is not used. We use the FpPOP_RETVAL instruction
1541     // instead.
1542     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1543       // If we prefer to use the value in xmm registers, copy it out as f80 and
1544       // use a truncate to move it from fp stack reg to xmm reg.
1545       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1546       SDValue Ops[] = { Chain, InFlag };
1547       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1548                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1549       Val = Chain.getValue(0);
1550
1551       // Round the f80 to the right size, which also moves it to the appropriate
1552       // xmm register.
1553       if (CopyVT != VA.getValVT())
1554         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1555                           // This truncation won't change the value.
1556                           DAG.getIntPtrConstant(1));
1557     } else {
1558       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1559                                  CopyVT, InFlag).getValue(1);
1560       Val = Chain.getValue(0);
1561     }
1562     InFlag = Chain.getValue(2);
1563     InVals.push_back(Val);
1564   }
1565
1566   return Chain;
1567 }
1568
1569
1570 //===----------------------------------------------------------------------===//
1571 //                C & StdCall & Fast Calling Convention implementation
1572 //===----------------------------------------------------------------------===//
1573 //  StdCall calling convention seems to be standard for many Windows' API
1574 //  routines and around. It differs from C calling convention just a little:
1575 //  callee should clean up the stack, not caller. Symbols should be also
1576 //  decorated in some fancy way :) It doesn't support any vector arguments.
1577 //  For info on fast calling convention see Fast Calling Convention (tail call)
1578 //  implementation LowerX86_32FastCCCallTo.
1579
1580 /// CallIsStructReturn - Determines whether a call uses struct return
1581 /// semantics.
1582 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1583   if (Outs.empty())
1584     return false;
1585
1586   return Outs[0].Flags.isSRet();
1587 }
1588
1589 /// ArgsAreStructReturn - Determines whether a function uses struct
1590 /// return semantics.
1591 static bool
1592 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1593   if (Ins.empty())
1594     return false;
1595
1596   return Ins[0].Flags.isSRet();
1597 }
1598
1599 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1600 /// by "Src" to address "Dst" with size and alignment information specified by
1601 /// the specific parameter attribute. The copy will be passed as a byval
1602 /// function parameter.
1603 static SDValue
1604 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1605                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1606                           DebugLoc dl) {
1607   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1608
1609   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1610                        /*isVolatile*/false, /*AlwaysInline=*/true,
1611                        MachinePointerInfo(), MachinePointerInfo());
1612 }
1613
1614 /// IsTailCallConvention - Return true if the calling convention is one that
1615 /// supports tail call optimization.
1616 static bool IsTailCallConvention(CallingConv::ID CC) {
1617   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1618 }
1619
1620 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1621   if (!CI->isTailCall())
1622     return false;
1623
1624   CallSite CS(CI);
1625   CallingConv::ID CalleeCC = CS.getCallingConv();
1626   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1627     return false;
1628
1629   return true;
1630 }
1631
1632 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1633 /// a tailcall target by changing its ABI.
1634 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1635   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1636 }
1637
1638 SDValue
1639 X86TargetLowering::LowerMemArgument(SDValue Chain,
1640                                     CallingConv::ID CallConv,
1641                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1642                                     DebugLoc dl, SelectionDAG &DAG,
1643                                     const CCValAssign &VA,
1644                                     MachineFrameInfo *MFI,
1645                                     unsigned i) const {
1646   // Create the nodes corresponding to a load from this parameter slot.
1647   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1648   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1649   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1650   EVT ValVT;
1651
1652   // If value is passed by pointer we have address passed instead of the value
1653   // itself.
1654   if (VA.getLocInfo() == CCValAssign::Indirect)
1655     ValVT = VA.getLocVT();
1656   else
1657     ValVT = VA.getValVT();
1658
1659   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1660   // changed with more analysis.
1661   // In case of tail call optimization mark all arguments mutable. Since they
1662   // could be overwritten by lowering of arguments in case of a tail call.
1663   if (Flags.isByVal()) {
1664     unsigned Bytes = Flags.getByValSize();
1665     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1666     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1667     return DAG.getFrameIndex(FI, getPointerTy());
1668   } else {
1669     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1670                                     VA.getLocMemOffset(), isImmutable);
1671     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1672     return DAG.getLoad(ValVT, dl, Chain, FIN,
1673                        MachinePointerInfo::getFixedStack(FI),
1674                        false, false, 0);
1675   }
1676 }
1677
1678 SDValue
1679 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1680                                         CallingConv::ID CallConv,
1681                                         bool isVarArg,
1682                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1683                                         DebugLoc dl,
1684                                         SelectionDAG &DAG,
1685                                         SmallVectorImpl<SDValue> &InVals)
1686                                           const {
1687   MachineFunction &MF = DAG.getMachineFunction();
1688   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1689
1690   const Function* Fn = MF.getFunction();
1691   if (Fn->hasExternalLinkage() &&
1692       Subtarget->isTargetCygMing() &&
1693       Fn->getName() == "main")
1694     FuncInfo->setForceFramePointer(true);
1695
1696   MachineFrameInfo *MFI = MF.getFrameInfo();
1697   bool Is64Bit = Subtarget->is64Bit();
1698   bool IsWin64 = Subtarget->isTargetWin64();
1699
1700   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1701          "Var args not supported with calling convention fastcc or ghc");
1702
1703   // Assign locations to all of the incoming arguments.
1704   SmallVector<CCValAssign, 16> ArgLocs;
1705   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1706                  ArgLocs, *DAG.getContext());
1707
1708   // Allocate shadow area for Win64
1709   if (IsWin64) {
1710     CCInfo.AllocateStack(32, 8);
1711   }
1712
1713   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1714
1715   unsigned LastVal = ~0U;
1716   SDValue ArgValue;
1717   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1718     CCValAssign &VA = ArgLocs[i];
1719     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1720     // places.
1721     assert(VA.getValNo() != LastVal &&
1722            "Don't support value assigned to multiple locs yet");
1723     LastVal = VA.getValNo();
1724
1725     if (VA.isRegLoc()) {
1726       EVT RegVT = VA.getLocVT();
1727       TargetRegisterClass *RC = NULL;
1728       if (RegVT == MVT::i32)
1729         RC = X86::GR32RegisterClass;
1730       else if (Is64Bit && RegVT == MVT::i64)
1731         RC = X86::GR64RegisterClass;
1732       else if (RegVT == MVT::f32)
1733         RC = X86::FR32RegisterClass;
1734       else if (RegVT == MVT::f64)
1735         RC = X86::FR64RegisterClass;
1736       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1737         RC = X86::VR256RegisterClass;
1738       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1739         RC = X86::VR128RegisterClass;
1740       else if (RegVT == MVT::x86mmx)
1741         RC = X86::VR64RegisterClass;
1742       else
1743         llvm_unreachable("Unknown argument type!");
1744
1745       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1746       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1747
1748       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1749       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1750       // right size.
1751       if (VA.getLocInfo() == CCValAssign::SExt)
1752         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1753                                DAG.getValueType(VA.getValVT()));
1754       else if (VA.getLocInfo() == CCValAssign::ZExt)
1755         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1756                                DAG.getValueType(VA.getValVT()));
1757       else if (VA.getLocInfo() == CCValAssign::BCvt)
1758         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1759
1760       if (VA.isExtInLoc()) {
1761         // Handle MMX values passed in XMM regs.
1762         if (RegVT.isVector()) {
1763           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1764                                  ArgValue);
1765         } else
1766           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1767       }
1768     } else {
1769       assert(VA.isMemLoc());
1770       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1771     }
1772
1773     // If value is passed via pointer - do a load.
1774     if (VA.getLocInfo() == CCValAssign::Indirect)
1775       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1776                              MachinePointerInfo(), false, false, 0);
1777
1778     InVals.push_back(ArgValue);
1779   }
1780
1781   // The x86-64 ABI for returning structs by value requires that we copy
1782   // the sret argument into %rax for the return. Save the argument into
1783   // a virtual register so that we can access it from the return points.
1784   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1785     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1786     unsigned Reg = FuncInfo->getSRetReturnReg();
1787     if (!Reg) {
1788       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1789       FuncInfo->setSRetReturnReg(Reg);
1790     }
1791     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1792     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1793   }
1794
1795   unsigned StackSize = CCInfo.getNextStackOffset();
1796   // Align stack specially for tail calls.
1797   if (FuncIsMadeTailCallSafe(CallConv))
1798     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1799
1800   // If the function takes variable number of arguments, make a frame index for
1801   // the start of the first vararg value... for expansion of llvm.va_start.
1802   if (isVarArg) {
1803     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1804                     CallConv != CallingConv::X86_ThisCall)) {
1805       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1806     }
1807     if (Is64Bit) {
1808       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1809
1810       // FIXME: We should really autogenerate these arrays
1811       static const unsigned GPR64ArgRegsWin64[] = {
1812         X86::RCX, X86::RDX, X86::R8,  X86::R9
1813       };
1814       static const unsigned GPR64ArgRegs64Bit[] = {
1815         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1816       };
1817       static const unsigned XMMArgRegs64Bit[] = {
1818         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1819         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1820       };
1821       const unsigned *GPR64ArgRegs;
1822       unsigned NumXMMRegs = 0;
1823
1824       if (IsWin64) {
1825         // The XMM registers which might contain var arg parameters are shadowed
1826         // in their paired GPR.  So we only need to save the GPR to their home
1827         // slots.
1828         TotalNumIntRegs = 4;
1829         GPR64ArgRegs = GPR64ArgRegsWin64;
1830       } else {
1831         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1832         GPR64ArgRegs = GPR64ArgRegs64Bit;
1833
1834         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1835       }
1836       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1837                                                        TotalNumIntRegs);
1838
1839       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1840       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1841              "SSE register cannot be used when SSE is disabled!");
1842       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1843              "SSE register cannot be used when SSE is disabled!");
1844       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1845         // Kernel mode asks for SSE to be disabled, so don't push them
1846         // on the stack.
1847         TotalNumXMMRegs = 0;
1848
1849       if (IsWin64) {
1850         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1851         // Get to the caller-allocated home save location.  Add 8 to account
1852         // for the return address.
1853         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1854         FuncInfo->setRegSaveFrameIndex(
1855           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1856         // Fixup to set vararg frame on shadow area (4 x i64).
1857         if (NumIntRegs < 4)
1858           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1859       } else {
1860         // For X86-64, if there are vararg parameters that are passed via
1861         // registers, then we must store them to their spots on the stack so they
1862         // may be loaded by deferencing the result of va_next.
1863         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1864         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1865         FuncInfo->setRegSaveFrameIndex(
1866           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1867                                false));
1868       }
1869
1870       // Store the integer parameter registers.
1871       SmallVector<SDValue, 8> MemOps;
1872       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1873                                         getPointerTy());
1874       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1875       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1876         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1877                                   DAG.getIntPtrConstant(Offset));
1878         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1879                                      X86::GR64RegisterClass);
1880         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1881         SDValue Store =
1882           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1883                        MachinePointerInfo::getFixedStack(
1884                          FuncInfo->getRegSaveFrameIndex(), Offset),
1885                        false, false, 0);
1886         MemOps.push_back(Store);
1887         Offset += 8;
1888       }
1889
1890       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1891         // Now store the XMM (fp + vector) parameter registers.
1892         SmallVector<SDValue, 11> SaveXMMOps;
1893         SaveXMMOps.push_back(Chain);
1894
1895         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1896         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1897         SaveXMMOps.push_back(ALVal);
1898
1899         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1900                                FuncInfo->getRegSaveFrameIndex()));
1901         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1902                                FuncInfo->getVarArgsFPOffset()));
1903
1904         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1905           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1906                                        X86::VR128RegisterClass);
1907           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1908           SaveXMMOps.push_back(Val);
1909         }
1910         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1911                                      MVT::Other,
1912                                      &SaveXMMOps[0], SaveXMMOps.size()));
1913       }
1914
1915       if (!MemOps.empty())
1916         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1917                             &MemOps[0], MemOps.size());
1918     }
1919   }
1920
1921   // Some CCs need callee pop.
1922   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1923     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1924   } else {
1925     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1926     // If this is an sret function, the return should pop the hidden pointer.
1927     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1928       FuncInfo->setBytesToPopOnReturn(4);
1929   }
1930
1931   if (!Is64Bit) {
1932     // RegSaveFrameIndex is X86-64 only.
1933     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1934     if (CallConv == CallingConv::X86_FastCall ||
1935         CallConv == CallingConv::X86_ThisCall)
1936       // fastcc functions can't have varargs.
1937       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1938   }
1939
1940   FuncInfo->setArgumentStackSize(StackSize);
1941
1942   return Chain;
1943 }
1944
1945 SDValue
1946 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1947                                     SDValue StackPtr, SDValue Arg,
1948                                     DebugLoc dl, SelectionDAG &DAG,
1949                                     const CCValAssign &VA,
1950                                     ISD::ArgFlagsTy Flags) const {
1951   unsigned LocMemOffset = VA.getLocMemOffset();
1952   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1953   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1954   if (Flags.isByVal())
1955     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1956
1957   return DAG.getStore(Chain, dl, Arg, PtrOff,
1958                       MachinePointerInfo::getStack(LocMemOffset),
1959                       false, false, 0);
1960 }
1961
1962 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1963 /// optimization is performed and it is required.
1964 SDValue
1965 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1966                                            SDValue &OutRetAddr, SDValue Chain,
1967                                            bool IsTailCall, bool Is64Bit,
1968                                            int FPDiff, DebugLoc dl) const {
1969   // Adjust the Return address stack slot.
1970   EVT VT = getPointerTy();
1971   OutRetAddr = getReturnAddressFrameIndex(DAG);
1972
1973   // Load the "old" Return address.
1974   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1975                            false, false, 0);
1976   return SDValue(OutRetAddr.getNode(), 1);
1977 }
1978
1979 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1980 /// optimization is performed and it is required (FPDiff!=0).
1981 static SDValue
1982 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1983                          SDValue Chain, SDValue RetAddrFrIdx,
1984                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1985   // Store the return address to the appropriate stack slot.
1986   if (!FPDiff) return Chain;
1987   // Calculate the new stack slot for the return address.
1988   int SlotSize = Is64Bit ? 8 : 4;
1989   int NewReturnAddrFI =
1990     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1991   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1992   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1993   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1994                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1995                        false, false, 0);
1996   return Chain;
1997 }
1998
1999 SDValue
2000 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2001                              CallingConv::ID CallConv, bool isVarArg,
2002                              bool &isTailCall,
2003                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2004                              const SmallVectorImpl<SDValue> &OutVals,
2005                              const SmallVectorImpl<ISD::InputArg> &Ins,
2006                              DebugLoc dl, SelectionDAG &DAG,
2007                              SmallVectorImpl<SDValue> &InVals) const {
2008   MachineFunction &MF = DAG.getMachineFunction();
2009   bool Is64Bit        = Subtarget->is64Bit();
2010   bool IsWin64        = Subtarget->isTargetWin64();
2011   bool IsStructRet    = CallIsStructReturn(Outs);
2012   bool IsSibcall      = false;
2013
2014   if (isTailCall) {
2015     // Check if it's really possible to do a tail call.
2016     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2017                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2018                                                    Outs, OutVals, Ins, DAG);
2019
2020     // Sibcalls are automatically detected tailcalls which do not require
2021     // ABI changes.
2022     if (!GuaranteedTailCallOpt && isTailCall)
2023       IsSibcall = true;
2024
2025     if (isTailCall)
2026       ++NumTailCalls;
2027   }
2028
2029   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2030          "Var args not supported with calling convention fastcc or ghc");
2031
2032   // Analyze operands of the call, assigning locations to each operand.
2033   SmallVector<CCValAssign, 16> ArgLocs;
2034   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2035                  ArgLocs, *DAG.getContext());
2036
2037   // Allocate shadow area for Win64
2038   if (IsWin64) {
2039     CCInfo.AllocateStack(32, 8);
2040   }
2041
2042   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2043
2044   // Get a count of how many bytes are to be pushed on the stack.
2045   unsigned NumBytes = CCInfo.getNextStackOffset();
2046   if (IsSibcall)
2047     // This is a sibcall. The memory operands are available in caller's
2048     // own caller's stack.
2049     NumBytes = 0;
2050   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2051     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2052
2053   int FPDiff = 0;
2054   if (isTailCall && !IsSibcall) {
2055     // Lower arguments at fp - stackoffset + fpdiff.
2056     unsigned NumBytesCallerPushed =
2057       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2058     FPDiff = NumBytesCallerPushed - NumBytes;
2059
2060     // Set the delta of movement of the returnaddr stackslot.
2061     // But only set if delta is greater than previous delta.
2062     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2063       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2064   }
2065
2066   if (!IsSibcall)
2067     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2068
2069   SDValue RetAddrFrIdx;
2070   // Load return address for tail calls.
2071   if (isTailCall && FPDiff)
2072     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2073                                     Is64Bit, FPDiff, dl);
2074
2075   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2076   SmallVector<SDValue, 8> MemOpChains;
2077   SDValue StackPtr;
2078
2079   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2080   // of tail call optimization arguments are handle later.
2081   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2082     CCValAssign &VA = ArgLocs[i];
2083     EVT RegVT = VA.getLocVT();
2084     SDValue Arg = OutVals[i];
2085     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2086     bool isByVal = Flags.isByVal();
2087
2088     // Promote the value if needed.
2089     switch (VA.getLocInfo()) {
2090     default: llvm_unreachable("Unknown loc info!");
2091     case CCValAssign::Full: break;
2092     case CCValAssign::SExt:
2093       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2094       break;
2095     case CCValAssign::ZExt:
2096       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2097       break;
2098     case CCValAssign::AExt:
2099       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2100         // Special case: passing MMX values in XMM registers.
2101         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2102         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2103         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2104       } else
2105         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2106       break;
2107     case CCValAssign::BCvt:
2108       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2109       break;
2110     case CCValAssign::Indirect: {
2111       // Store the argument.
2112       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2113       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2114       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2115                            MachinePointerInfo::getFixedStack(FI),
2116                            false, false, 0);
2117       Arg = SpillSlot;
2118       break;
2119     }
2120     }
2121
2122     if (VA.isRegLoc()) {
2123       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2124       if (isVarArg && IsWin64) {
2125         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2126         // shadow reg if callee is a varargs function.
2127         unsigned ShadowReg = 0;
2128         switch (VA.getLocReg()) {
2129         case X86::XMM0: ShadowReg = X86::RCX; break;
2130         case X86::XMM1: ShadowReg = X86::RDX; break;
2131         case X86::XMM2: ShadowReg = X86::R8; break;
2132         case X86::XMM3: ShadowReg = X86::R9; break;
2133         }
2134         if (ShadowReg)
2135           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2136       }
2137     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2138       assert(VA.isMemLoc());
2139       if (StackPtr.getNode() == 0)
2140         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2141       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2142                                              dl, DAG, VA, Flags));
2143     }
2144   }
2145
2146   if (!MemOpChains.empty())
2147     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2148                         &MemOpChains[0], MemOpChains.size());
2149
2150   // Build a sequence of copy-to-reg nodes chained together with token chain
2151   // and flag operands which copy the outgoing args into registers.
2152   SDValue InFlag;
2153   // Tail call byval lowering might overwrite argument registers so in case of
2154   // tail call optimization the copies to registers are lowered later.
2155   if (!isTailCall)
2156     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2157       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2158                                RegsToPass[i].second, InFlag);
2159       InFlag = Chain.getValue(1);
2160     }
2161
2162   if (Subtarget->isPICStyleGOT()) {
2163     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2164     // GOT pointer.
2165     if (!isTailCall) {
2166       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2167                                DAG.getNode(X86ISD::GlobalBaseReg,
2168                                            DebugLoc(), getPointerTy()),
2169                                InFlag);
2170       InFlag = Chain.getValue(1);
2171     } else {
2172       // If we are tail calling and generating PIC/GOT style code load the
2173       // address of the callee into ECX. The value in ecx is used as target of
2174       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2175       // for tail calls on PIC/GOT architectures. Normally we would just put the
2176       // address of GOT into ebx and then call target@PLT. But for tail calls
2177       // ebx would be restored (since ebx is callee saved) before jumping to the
2178       // target@PLT.
2179
2180       // Note: The actual moving to ECX is done further down.
2181       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2182       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2183           !G->getGlobal()->hasProtectedVisibility())
2184         Callee = LowerGlobalAddress(Callee, DAG);
2185       else if (isa<ExternalSymbolSDNode>(Callee))
2186         Callee = LowerExternalSymbol(Callee, DAG);
2187     }
2188   }
2189
2190   if (Is64Bit && isVarArg && !IsWin64) {
2191     // From AMD64 ABI document:
2192     // For calls that may call functions that use varargs or stdargs
2193     // (prototype-less calls or calls to functions containing ellipsis (...) in
2194     // the declaration) %al is used as hidden argument to specify the number
2195     // of SSE registers used. The contents of %al do not need to match exactly
2196     // the number of registers, but must be an ubound on the number of SSE
2197     // registers used and is in the range 0 - 8 inclusive.
2198
2199     // Count the number of XMM registers allocated.
2200     static const unsigned XMMArgRegs[] = {
2201       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2202       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2203     };
2204     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2205     assert((Subtarget->hasXMM() || !NumXMMRegs)
2206            && "SSE registers cannot be used when SSE is disabled");
2207
2208     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2209                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2210     InFlag = Chain.getValue(1);
2211   }
2212
2213
2214   // For tail calls lower the arguments to the 'real' stack slot.
2215   if (isTailCall) {
2216     // Force all the incoming stack arguments to be loaded from the stack
2217     // before any new outgoing arguments are stored to the stack, because the
2218     // outgoing stack slots may alias the incoming argument stack slots, and
2219     // the alias isn't otherwise explicit. This is slightly more conservative
2220     // than necessary, because it means that each store effectively depends
2221     // on every argument instead of just those arguments it would clobber.
2222     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2223
2224     SmallVector<SDValue, 8> MemOpChains2;
2225     SDValue FIN;
2226     int FI = 0;
2227     // Do not flag preceding copytoreg stuff together with the following stuff.
2228     InFlag = SDValue();
2229     if (GuaranteedTailCallOpt) {
2230       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2231         CCValAssign &VA = ArgLocs[i];
2232         if (VA.isRegLoc())
2233           continue;
2234         assert(VA.isMemLoc());
2235         SDValue Arg = OutVals[i];
2236         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2237         // Create frame index.
2238         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2239         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2240         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2241         FIN = DAG.getFrameIndex(FI, getPointerTy());
2242
2243         if (Flags.isByVal()) {
2244           // Copy relative to framepointer.
2245           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2246           if (StackPtr.getNode() == 0)
2247             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2248                                           getPointerTy());
2249           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2250
2251           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2252                                                            ArgChain,
2253                                                            Flags, DAG, dl));
2254         } else {
2255           // Store relative to framepointer.
2256           MemOpChains2.push_back(
2257             DAG.getStore(ArgChain, dl, Arg, FIN,
2258                          MachinePointerInfo::getFixedStack(FI),
2259                          false, false, 0));
2260         }
2261       }
2262     }
2263
2264     if (!MemOpChains2.empty())
2265       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2266                           &MemOpChains2[0], MemOpChains2.size());
2267
2268     // Copy arguments to their registers.
2269     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2270       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2271                                RegsToPass[i].second, InFlag);
2272       InFlag = Chain.getValue(1);
2273     }
2274     InFlag =SDValue();
2275
2276     // Store the return address to the appropriate stack slot.
2277     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2278                                      FPDiff, dl);
2279   }
2280
2281   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2282     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2283     // In the 64-bit large code model, we have to make all calls
2284     // through a register, since the call instruction's 32-bit
2285     // pc-relative offset may not be large enough to hold the whole
2286     // address.
2287   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2288     // If the callee is a GlobalAddress node (quite common, every direct call
2289     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2290     // it.
2291
2292     // We should use extra load for direct calls to dllimported functions in
2293     // non-JIT mode.
2294     const GlobalValue *GV = G->getGlobal();
2295     if (!GV->hasDLLImportLinkage()) {
2296       unsigned char OpFlags = 0;
2297       bool ExtraLoad = false;
2298       unsigned WrapperKind = ISD::DELETED_NODE;
2299
2300       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2301       // external symbols most go through the PLT in PIC mode.  If the symbol
2302       // has hidden or protected visibility, or if it is static or local, then
2303       // we don't need to use the PLT - we can directly call it.
2304       if (Subtarget->isTargetELF() &&
2305           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2306           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2307         OpFlags = X86II::MO_PLT;
2308       } else if (Subtarget->isPICStyleStubAny() &&
2309                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2310                  (!Subtarget->getTargetTriple().isMacOSX() ||
2311                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2312         // PC-relative references to external symbols should go through $stub,
2313         // unless we're building with the leopard linker or later, which
2314         // automatically synthesizes these stubs.
2315         OpFlags = X86II::MO_DARWIN_STUB;
2316       } else if (Subtarget->isPICStyleRIPRel() &&
2317                  isa<Function>(GV) &&
2318                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2319         // If the function is marked as non-lazy, generate an indirect call
2320         // which loads from the GOT directly. This avoids runtime overhead
2321         // at the cost of eager binding (and one extra byte of encoding).
2322         OpFlags = X86II::MO_GOTPCREL;
2323         WrapperKind = X86ISD::WrapperRIP;
2324         ExtraLoad = true;
2325       }
2326
2327       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2328                                           G->getOffset(), OpFlags);
2329
2330       // Add a wrapper if needed.
2331       if (WrapperKind != ISD::DELETED_NODE)
2332         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2333       // Add extra indirection if needed.
2334       if (ExtraLoad)
2335         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2336                              MachinePointerInfo::getGOT(),
2337                              false, false, 0);
2338     }
2339   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2340     unsigned char OpFlags = 0;
2341
2342     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2343     // external symbols should go through the PLT.
2344     if (Subtarget->isTargetELF() &&
2345         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2346       OpFlags = X86II::MO_PLT;
2347     } else if (Subtarget->isPICStyleStubAny() &&
2348                (!Subtarget->getTargetTriple().isMacOSX() ||
2349                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2350       // PC-relative references to external symbols should go through $stub,
2351       // unless we're building with the leopard linker or later, which
2352       // automatically synthesizes these stubs.
2353       OpFlags = X86II::MO_DARWIN_STUB;
2354     }
2355
2356     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2357                                          OpFlags);
2358   }
2359
2360   // Returns a chain & a flag for retval copy to use.
2361   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2362   SmallVector<SDValue, 8> Ops;
2363
2364   if (!IsSibcall && isTailCall) {
2365     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2366                            DAG.getIntPtrConstant(0, true), InFlag);
2367     InFlag = Chain.getValue(1);
2368   }
2369
2370   Ops.push_back(Chain);
2371   Ops.push_back(Callee);
2372
2373   if (isTailCall)
2374     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2375
2376   // Add argument registers to the end of the list so that they are known live
2377   // into the call.
2378   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2379     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2380                                   RegsToPass[i].second.getValueType()));
2381
2382   // Add an implicit use GOT pointer in EBX.
2383   if (!isTailCall && Subtarget->isPICStyleGOT())
2384     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2385
2386   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2387   if (Is64Bit && isVarArg && !IsWin64)
2388     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2389
2390   if (InFlag.getNode())
2391     Ops.push_back(InFlag);
2392
2393   if (isTailCall) {
2394     // We used to do:
2395     //// If this is the first return lowered for this function, add the regs
2396     //// to the liveout set for the function.
2397     // This isn't right, although it's probably harmless on x86; liveouts
2398     // should be computed from returns not tail calls.  Consider a void
2399     // function making a tail call to a function returning int.
2400     return DAG.getNode(X86ISD::TC_RETURN, dl,
2401                        NodeTys, &Ops[0], Ops.size());
2402   }
2403
2404   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2405   InFlag = Chain.getValue(1);
2406
2407   // Create the CALLSEQ_END node.
2408   unsigned NumBytesForCalleeToPush;
2409   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2410     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2411   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2412     // If this is a call to a struct-return function, the callee
2413     // pops the hidden struct pointer, so we have to push it back.
2414     // This is common for Darwin/X86, Linux & Mingw32 targets.
2415     NumBytesForCalleeToPush = 4;
2416   else
2417     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2418
2419   // Returns a flag for retval copy to use.
2420   if (!IsSibcall) {
2421     Chain = DAG.getCALLSEQ_END(Chain,
2422                                DAG.getIntPtrConstant(NumBytes, true),
2423                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2424                                                      true),
2425                                InFlag);
2426     InFlag = Chain.getValue(1);
2427   }
2428
2429   // Handle result values, copying them out of physregs into vregs that we
2430   // return.
2431   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2432                          Ins, dl, DAG, InVals);
2433 }
2434
2435
2436 //===----------------------------------------------------------------------===//
2437 //                Fast Calling Convention (tail call) implementation
2438 //===----------------------------------------------------------------------===//
2439
2440 //  Like std call, callee cleans arguments, convention except that ECX is
2441 //  reserved for storing the tail called function address. Only 2 registers are
2442 //  free for argument passing (inreg). Tail call optimization is performed
2443 //  provided:
2444 //                * tailcallopt is enabled
2445 //                * caller/callee are fastcc
2446 //  On X86_64 architecture with GOT-style position independent code only local
2447 //  (within module) calls are supported at the moment.
2448 //  To keep the stack aligned according to platform abi the function
2449 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2450 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2451 //  If a tail called function callee has more arguments than the caller the
2452 //  caller needs to make sure that there is room to move the RETADDR to. This is
2453 //  achieved by reserving an area the size of the argument delta right after the
2454 //  original REtADDR, but before the saved framepointer or the spilled registers
2455 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2456 //  stack layout:
2457 //    arg1
2458 //    arg2
2459 //    RETADDR
2460 //    [ new RETADDR
2461 //      move area ]
2462 //    (possible EBP)
2463 //    ESI
2464 //    EDI
2465 //    local1 ..
2466
2467 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2468 /// for a 16 byte align requirement.
2469 unsigned
2470 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2471                                                SelectionDAG& DAG) const {
2472   MachineFunction &MF = DAG.getMachineFunction();
2473   const TargetMachine &TM = MF.getTarget();
2474   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2475   unsigned StackAlignment = TFI.getStackAlignment();
2476   uint64_t AlignMask = StackAlignment - 1;
2477   int64_t Offset = StackSize;
2478   uint64_t SlotSize = TD->getPointerSize();
2479   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2480     // Number smaller than 12 so just add the difference.
2481     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2482   } else {
2483     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2484     Offset = ((~AlignMask) & Offset) + StackAlignment +
2485       (StackAlignment-SlotSize);
2486   }
2487   return Offset;
2488 }
2489
2490 /// MatchingStackOffset - Return true if the given stack call argument is
2491 /// already available in the same position (relatively) of the caller's
2492 /// incoming argument stack.
2493 static
2494 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2495                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2496                          const X86InstrInfo *TII) {
2497   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2498   int FI = INT_MAX;
2499   if (Arg.getOpcode() == ISD::CopyFromReg) {
2500     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2501     if (!TargetRegisterInfo::isVirtualRegister(VR))
2502       return false;
2503     MachineInstr *Def = MRI->getVRegDef(VR);
2504     if (!Def)
2505       return false;
2506     if (!Flags.isByVal()) {
2507       if (!TII->isLoadFromStackSlot(Def, FI))
2508         return false;
2509     } else {
2510       unsigned Opcode = Def->getOpcode();
2511       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2512           Def->getOperand(1).isFI()) {
2513         FI = Def->getOperand(1).getIndex();
2514         Bytes = Flags.getByValSize();
2515       } else
2516         return false;
2517     }
2518   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2519     if (Flags.isByVal())
2520       // ByVal argument is passed in as a pointer but it's now being
2521       // dereferenced. e.g.
2522       // define @foo(%struct.X* %A) {
2523       //   tail call @bar(%struct.X* byval %A)
2524       // }
2525       return false;
2526     SDValue Ptr = Ld->getBasePtr();
2527     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2528     if (!FINode)
2529       return false;
2530     FI = FINode->getIndex();
2531   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2532     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2533     FI = FINode->getIndex();
2534     Bytes = Flags.getByValSize();
2535   } else
2536     return false;
2537
2538   assert(FI != INT_MAX);
2539   if (!MFI->isFixedObjectIndex(FI))
2540     return false;
2541   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2542 }
2543
2544 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2545 /// for tail call optimization. Targets which want to do tail call
2546 /// optimization should implement this function.
2547 bool
2548 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2549                                                      CallingConv::ID CalleeCC,
2550                                                      bool isVarArg,
2551                                                      bool isCalleeStructRet,
2552                                                      bool isCallerStructRet,
2553                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2554                                     const SmallVectorImpl<SDValue> &OutVals,
2555                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2556                                                      SelectionDAG& DAG) const {
2557   if (!IsTailCallConvention(CalleeCC) &&
2558       CalleeCC != CallingConv::C)
2559     return false;
2560
2561   // If -tailcallopt is specified, make fastcc functions tail-callable.
2562   const MachineFunction &MF = DAG.getMachineFunction();
2563   const Function *CallerF = DAG.getMachineFunction().getFunction();
2564   CallingConv::ID CallerCC = CallerF->getCallingConv();
2565   bool CCMatch = CallerCC == CalleeCC;
2566
2567   if (GuaranteedTailCallOpt) {
2568     if (IsTailCallConvention(CalleeCC) && CCMatch)
2569       return true;
2570     return false;
2571   }
2572
2573   // Look for obvious safe cases to perform tail call optimization that do not
2574   // require ABI changes. This is what gcc calls sibcall.
2575
2576   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2577   // emit a special epilogue.
2578   if (RegInfo->needsStackRealignment(MF))
2579     return false;
2580
2581   // Also avoid sibcall optimization if either caller or callee uses struct
2582   // return semantics.
2583   if (isCalleeStructRet || isCallerStructRet)
2584     return false;
2585
2586   // An stdcall caller is expected to clean up its arguments; the callee
2587   // isn't going to do that.
2588   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2589     return false;
2590
2591   // Do not sibcall optimize vararg calls unless all arguments are passed via
2592   // registers.
2593   if (isVarArg && !Outs.empty()) {
2594
2595     // Optimizing for varargs on Win64 is unlikely to be safe without
2596     // additional testing.
2597     if (Subtarget->isTargetWin64())
2598       return false;
2599
2600     SmallVector<CCValAssign, 16> ArgLocs;
2601     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2602                    getTargetMachine(), ArgLocs, *DAG.getContext());
2603
2604     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2605     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2606       if (!ArgLocs[i].isRegLoc())
2607         return false;
2608   }
2609
2610   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2611   // Therefore if it's not used by the call it is not safe to optimize this into
2612   // a sibcall.
2613   bool Unused = false;
2614   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2615     if (!Ins[i].Used) {
2616       Unused = true;
2617       break;
2618     }
2619   }
2620   if (Unused) {
2621     SmallVector<CCValAssign, 16> RVLocs;
2622     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2623                    getTargetMachine(), RVLocs, *DAG.getContext());
2624     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2625     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2626       CCValAssign &VA = RVLocs[i];
2627       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2628         return false;
2629     }
2630   }
2631
2632   // If the calling conventions do not match, then we'd better make sure the
2633   // results are returned in the same way as what the caller expects.
2634   if (!CCMatch) {
2635     SmallVector<CCValAssign, 16> RVLocs1;
2636     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2637                     getTargetMachine(), RVLocs1, *DAG.getContext());
2638     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2639
2640     SmallVector<CCValAssign, 16> RVLocs2;
2641     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2642                     getTargetMachine(), RVLocs2, *DAG.getContext());
2643     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2644
2645     if (RVLocs1.size() != RVLocs2.size())
2646       return false;
2647     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2648       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2649         return false;
2650       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2651         return false;
2652       if (RVLocs1[i].isRegLoc()) {
2653         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2654           return false;
2655       } else {
2656         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2657           return false;
2658       }
2659     }
2660   }
2661
2662   // If the callee takes no arguments then go on to check the results of the
2663   // call.
2664   if (!Outs.empty()) {
2665     // Check if stack adjustment is needed. For now, do not do this if any
2666     // argument is passed on the stack.
2667     SmallVector<CCValAssign, 16> ArgLocs;
2668     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2669                    getTargetMachine(), ArgLocs, *DAG.getContext());
2670
2671     // Allocate shadow area for Win64
2672     if (Subtarget->isTargetWin64()) {
2673       CCInfo.AllocateStack(32, 8);
2674     }
2675
2676     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2677     if (CCInfo.getNextStackOffset()) {
2678       MachineFunction &MF = DAG.getMachineFunction();
2679       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2680         return false;
2681
2682       // Check if the arguments are already laid out in the right way as
2683       // the caller's fixed stack objects.
2684       MachineFrameInfo *MFI = MF.getFrameInfo();
2685       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2686       const X86InstrInfo *TII =
2687         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2688       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2689         CCValAssign &VA = ArgLocs[i];
2690         SDValue Arg = OutVals[i];
2691         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2692         if (VA.getLocInfo() == CCValAssign::Indirect)
2693           return false;
2694         if (!VA.isRegLoc()) {
2695           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2696                                    MFI, MRI, TII))
2697             return false;
2698         }
2699       }
2700     }
2701
2702     // If the tailcall address may be in a register, then make sure it's
2703     // possible to register allocate for it. In 32-bit, the call address can
2704     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2705     // callee-saved registers are restored. These happen to be the same
2706     // registers used to pass 'inreg' arguments so watch out for those.
2707     if (!Subtarget->is64Bit() &&
2708         !isa<GlobalAddressSDNode>(Callee) &&
2709         !isa<ExternalSymbolSDNode>(Callee)) {
2710       unsigned NumInRegs = 0;
2711       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2712         CCValAssign &VA = ArgLocs[i];
2713         if (!VA.isRegLoc())
2714           continue;
2715         unsigned Reg = VA.getLocReg();
2716         switch (Reg) {
2717         default: break;
2718         case X86::EAX: case X86::EDX: case X86::ECX:
2719           if (++NumInRegs == 3)
2720             return false;
2721           break;
2722         }
2723       }
2724     }
2725   }
2726
2727   return true;
2728 }
2729
2730 FastISel *
2731 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2732   return X86::createFastISel(funcInfo);
2733 }
2734
2735
2736 //===----------------------------------------------------------------------===//
2737 //                           Other Lowering Hooks
2738 //===----------------------------------------------------------------------===//
2739
2740 static bool MayFoldLoad(SDValue Op) {
2741   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2742 }
2743
2744 static bool MayFoldIntoStore(SDValue Op) {
2745   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2746 }
2747
2748 static bool isTargetShuffle(unsigned Opcode) {
2749   switch(Opcode) {
2750   default: return false;
2751   case X86ISD::PSHUFD:
2752   case X86ISD::PSHUFHW:
2753   case X86ISD::PSHUFLW:
2754   case X86ISD::SHUFPD:
2755   case X86ISD::PALIGN:
2756   case X86ISD::SHUFPS:
2757   case X86ISD::MOVLHPS:
2758   case X86ISD::MOVLHPD:
2759   case X86ISD::MOVHLPS:
2760   case X86ISD::MOVLPS:
2761   case X86ISD::MOVLPD:
2762   case X86ISD::MOVSHDUP:
2763   case X86ISD::MOVSLDUP:
2764   case X86ISD::MOVDDUP:
2765   case X86ISD::MOVSS:
2766   case X86ISD::MOVSD:
2767   case X86ISD::UNPCKLPS:
2768   case X86ISD::UNPCKLPD:
2769   case X86ISD::VUNPCKLPSY:
2770   case X86ISD::VUNPCKLPDY:
2771   case X86ISD::PUNPCKLWD:
2772   case X86ISD::PUNPCKLBW:
2773   case X86ISD::PUNPCKLDQ:
2774   case X86ISD::PUNPCKLQDQ:
2775   case X86ISD::UNPCKHPS:
2776   case X86ISD::UNPCKHPD:
2777   case X86ISD::VUNPCKHPSY:
2778   case X86ISD::VUNPCKHPDY:
2779   case X86ISD::PUNPCKHWD:
2780   case X86ISD::PUNPCKHBW:
2781   case X86ISD::PUNPCKHDQ:
2782   case X86ISD::PUNPCKHQDQ:
2783   case X86ISD::VPERMILPS:
2784   case X86ISD::VPERMILPSY:
2785   case X86ISD::VPERMILPD:
2786   case X86ISD::VPERMILPDY:
2787   case X86ISD::VPERM2F128:
2788     return true;
2789   }
2790   return false;
2791 }
2792
2793 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2794                                                SDValue V1, SelectionDAG &DAG) {
2795   switch(Opc) {
2796   default: llvm_unreachable("Unknown x86 shuffle node");
2797   case X86ISD::MOVSHDUP:
2798   case X86ISD::MOVSLDUP:
2799   case X86ISD::MOVDDUP:
2800     return DAG.getNode(Opc, dl, VT, V1);
2801   }
2802
2803   return SDValue();
2804 }
2805
2806 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2807                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2808   switch(Opc) {
2809   default: llvm_unreachable("Unknown x86 shuffle node");
2810   case X86ISD::PSHUFD:
2811   case X86ISD::PSHUFHW:
2812   case X86ISD::PSHUFLW:
2813   case X86ISD::VPERMILPS:
2814   case X86ISD::VPERMILPSY:
2815   case X86ISD::VPERMILPD:
2816   case X86ISD::VPERMILPDY:
2817     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2818   }
2819
2820   return SDValue();
2821 }
2822
2823 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2824                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2825   switch(Opc) {
2826   default: llvm_unreachable("Unknown x86 shuffle node");
2827   case X86ISD::PALIGN:
2828   case X86ISD::SHUFPD:
2829   case X86ISD::SHUFPS:
2830   case X86ISD::VPERM2F128:
2831     return DAG.getNode(Opc, dl, VT, V1, V2,
2832                        DAG.getConstant(TargetMask, MVT::i8));
2833   }
2834   return SDValue();
2835 }
2836
2837 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2838                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2839   switch(Opc) {
2840   default: llvm_unreachable("Unknown x86 shuffle node");
2841   case X86ISD::MOVLHPS:
2842   case X86ISD::MOVLHPD:
2843   case X86ISD::MOVHLPS:
2844   case X86ISD::MOVLPS:
2845   case X86ISD::MOVLPD:
2846   case X86ISD::MOVSS:
2847   case X86ISD::MOVSD:
2848   case X86ISD::UNPCKLPS:
2849   case X86ISD::UNPCKLPD:
2850   case X86ISD::VUNPCKLPSY:
2851   case X86ISD::VUNPCKLPDY:
2852   case X86ISD::PUNPCKLWD:
2853   case X86ISD::PUNPCKLBW:
2854   case X86ISD::PUNPCKLDQ:
2855   case X86ISD::PUNPCKLQDQ:
2856   case X86ISD::UNPCKHPS:
2857   case X86ISD::UNPCKHPD:
2858   case X86ISD::VUNPCKHPSY:
2859   case X86ISD::VUNPCKHPDY:
2860   case X86ISD::PUNPCKHWD:
2861   case X86ISD::PUNPCKHBW:
2862   case X86ISD::PUNPCKHDQ:
2863   case X86ISD::PUNPCKHQDQ:
2864     return DAG.getNode(Opc, dl, VT, V1, V2);
2865   }
2866   return SDValue();
2867 }
2868
2869 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2870   MachineFunction &MF = DAG.getMachineFunction();
2871   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2872   int ReturnAddrIndex = FuncInfo->getRAIndex();
2873
2874   if (ReturnAddrIndex == 0) {
2875     // Set up a frame object for the return address.
2876     uint64_t SlotSize = TD->getPointerSize();
2877     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2878                                                            false);
2879     FuncInfo->setRAIndex(ReturnAddrIndex);
2880   }
2881
2882   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2883 }
2884
2885
2886 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2887                                        bool hasSymbolicDisplacement) {
2888   // Offset should fit into 32 bit immediate field.
2889   if (!isInt<32>(Offset))
2890     return false;
2891
2892   // If we don't have a symbolic displacement - we don't have any extra
2893   // restrictions.
2894   if (!hasSymbolicDisplacement)
2895     return true;
2896
2897   // FIXME: Some tweaks might be needed for medium code model.
2898   if (M != CodeModel::Small && M != CodeModel::Kernel)
2899     return false;
2900
2901   // For small code model we assume that latest object is 16MB before end of 31
2902   // bits boundary. We may also accept pretty large negative constants knowing
2903   // that all objects are in the positive half of address space.
2904   if (M == CodeModel::Small && Offset < 16*1024*1024)
2905     return true;
2906
2907   // For kernel code model we know that all object resist in the negative half
2908   // of 32bits address space. We may not accept negative offsets, since they may
2909   // be just off and we may accept pretty large positive ones.
2910   if (M == CodeModel::Kernel && Offset > 0)
2911     return true;
2912
2913   return false;
2914 }
2915
2916 /// isCalleePop - Determines whether the callee is required to pop its
2917 /// own arguments. Callee pop is necessary to support tail calls.
2918 bool X86::isCalleePop(CallingConv::ID CallingConv,
2919                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2920   if (IsVarArg)
2921     return false;
2922
2923   switch (CallingConv) {
2924   default:
2925     return false;
2926   case CallingConv::X86_StdCall:
2927     return !is64Bit;
2928   case CallingConv::X86_FastCall:
2929     return !is64Bit;
2930   case CallingConv::X86_ThisCall:
2931     return !is64Bit;
2932   case CallingConv::Fast:
2933     return TailCallOpt;
2934   case CallingConv::GHC:
2935     return TailCallOpt;
2936   }
2937 }
2938
2939 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2940 /// specific condition code, returning the condition code and the LHS/RHS of the
2941 /// comparison to make.
2942 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2943                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2944   if (!isFP) {
2945     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2946       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2947         // X > -1   -> X == 0, jump !sign.
2948         RHS = DAG.getConstant(0, RHS.getValueType());
2949         return X86::COND_NS;
2950       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2951         // X < 0   -> X == 0, jump on sign.
2952         return X86::COND_S;
2953       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2954         // X < 1   -> X <= 0
2955         RHS = DAG.getConstant(0, RHS.getValueType());
2956         return X86::COND_LE;
2957       }
2958     }
2959
2960     switch (SetCCOpcode) {
2961     default: llvm_unreachable("Invalid integer condition!");
2962     case ISD::SETEQ:  return X86::COND_E;
2963     case ISD::SETGT:  return X86::COND_G;
2964     case ISD::SETGE:  return X86::COND_GE;
2965     case ISD::SETLT:  return X86::COND_L;
2966     case ISD::SETLE:  return X86::COND_LE;
2967     case ISD::SETNE:  return X86::COND_NE;
2968     case ISD::SETULT: return X86::COND_B;
2969     case ISD::SETUGT: return X86::COND_A;
2970     case ISD::SETULE: return X86::COND_BE;
2971     case ISD::SETUGE: return X86::COND_AE;
2972     }
2973   }
2974
2975   // First determine if it is required or is profitable to flip the operands.
2976
2977   // If LHS is a foldable load, but RHS is not, flip the condition.
2978   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2979       !ISD::isNON_EXTLoad(RHS.getNode())) {
2980     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2981     std::swap(LHS, RHS);
2982   }
2983
2984   switch (SetCCOpcode) {
2985   default: break;
2986   case ISD::SETOLT:
2987   case ISD::SETOLE:
2988   case ISD::SETUGT:
2989   case ISD::SETUGE:
2990     std::swap(LHS, RHS);
2991     break;
2992   }
2993
2994   // On a floating point condition, the flags are set as follows:
2995   // ZF  PF  CF   op
2996   //  0 | 0 | 0 | X > Y
2997   //  0 | 0 | 1 | X < Y
2998   //  1 | 0 | 0 | X == Y
2999   //  1 | 1 | 1 | unordered
3000   switch (SetCCOpcode) {
3001   default: llvm_unreachable("Condcode should be pre-legalized away");
3002   case ISD::SETUEQ:
3003   case ISD::SETEQ:   return X86::COND_E;
3004   case ISD::SETOLT:              // flipped
3005   case ISD::SETOGT:
3006   case ISD::SETGT:   return X86::COND_A;
3007   case ISD::SETOLE:              // flipped
3008   case ISD::SETOGE:
3009   case ISD::SETGE:   return X86::COND_AE;
3010   case ISD::SETUGT:              // flipped
3011   case ISD::SETULT:
3012   case ISD::SETLT:   return X86::COND_B;
3013   case ISD::SETUGE:              // flipped
3014   case ISD::SETULE:
3015   case ISD::SETLE:   return X86::COND_BE;
3016   case ISD::SETONE:
3017   case ISD::SETNE:   return X86::COND_NE;
3018   case ISD::SETUO:   return X86::COND_P;
3019   case ISD::SETO:    return X86::COND_NP;
3020   case ISD::SETOEQ:
3021   case ISD::SETUNE:  return X86::COND_INVALID;
3022   }
3023 }
3024
3025 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3026 /// code. Current x86 isa includes the following FP cmov instructions:
3027 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3028 static bool hasFPCMov(unsigned X86CC) {
3029   switch (X86CC) {
3030   default:
3031     return false;
3032   case X86::COND_B:
3033   case X86::COND_BE:
3034   case X86::COND_E:
3035   case X86::COND_P:
3036   case X86::COND_A:
3037   case X86::COND_AE:
3038   case X86::COND_NE:
3039   case X86::COND_NP:
3040     return true;
3041   }
3042 }
3043
3044 /// isFPImmLegal - Returns true if the target can instruction select the
3045 /// specified FP immediate natively. If false, the legalizer will
3046 /// materialize the FP immediate as a load from a constant pool.
3047 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3048   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3049     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3050       return true;
3051   }
3052   return false;
3053 }
3054
3055 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3056 /// the specified range (L, H].
3057 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3058   return (Val < 0) || (Val >= Low && Val < Hi);
3059 }
3060
3061 /// isUndefOrInRange - Return true if every element in Mask, begining
3062 /// from position Pos and ending in Pos+Size, falls within the specified
3063 /// range (L, L+Pos]. or is undef.
3064 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3065                              int Pos, int Size, int Low, int Hi) {
3066   for (int i = Pos, e = Pos+Size; i != e; ++i)
3067     if (!isUndefOrInRange(Mask[i], Low, Hi))
3068       return false;
3069   return true;
3070 }
3071
3072 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3073 /// specified value.
3074 static bool isUndefOrEqual(int Val, int CmpVal) {
3075   if (Val < 0 || Val == CmpVal)
3076     return true;
3077   return false;
3078 }
3079
3080 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3081 /// from position Pos and ending in Pos+Size, falls within the specified
3082 /// sequential range (L, L+Pos]. or is undef.
3083 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3084                                        int Pos, int Size, int Low) {
3085   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3086     if (!isUndefOrEqual(Mask[i], Low))
3087       return false;
3088   return true;
3089 }
3090
3091 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3092 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3093 /// the second operand.
3094 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3095   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3096     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3097   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3098     return (Mask[0] < 2 && Mask[1] < 2);
3099   return false;
3100 }
3101
3102 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3103   SmallVector<int, 8> M;
3104   N->getMask(M);
3105   return ::isPSHUFDMask(M, N->getValueType(0));
3106 }
3107
3108 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3109 /// is suitable for input to PSHUFHW.
3110 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3111   if (VT != MVT::v8i16)
3112     return false;
3113
3114   // Lower quadword copied in order or undef.
3115   for (int i = 0; i != 4; ++i)
3116     if (Mask[i] >= 0 && Mask[i] != i)
3117       return false;
3118
3119   // Upper quadword shuffled.
3120   for (int i = 4; i != 8; ++i)
3121     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3122       return false;
3123
3124   return true;
3125 }
3126
3127 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3128   SmallVector<int, 8> M;
3129   N->getMask(M);
3130   return ::isPSHUFHWMask(M, N->getValueType(0));
3131 }
3132
3133 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3134 /// is suitable for input to PSHUFLW.
3135 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3136   if (VT != MVT::v8i16)
3137     return false;
3138
3139   // Upper quadword copied in order.
3140   for (int i = 4; i != 8; ++i)
3141     if (Mask[i] >= 0 && Mask[i] != i)
3142       return false;
3143
3144   // Lower quadword shuffled.
3145   for (int i = 0; i != 4; ++i)
3146     if (Mask[i] >= 4)
3147       return false;
3148
3149   return true;
3150 }
3151
3152 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3153   SmallVector<int, 8> M;
3154   N->getMask(M);
3155   return ::isPSHUFLWMask(M, N->getValueType(0));
3156 }
3157
3158 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3159 /// is suitable for input to PALIGNR.
3160 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3161                           bool hasSSSE3) {
3162   int i, e = VT.getVectorNumElements();
3163   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3164     return false;
3165
3166   // Do not handle v2i64 / v2f64 shuffles with palignr.
3167   if (e < 4 || !hasSSSE3)
3168     return false;
3169
3170   for (i = 0; i != e; ++i)
3171     if (Mask[i] >= 0)
3172       break;
3173
3174   // All undef, not a palignr.
3175   if (i == e)
3176     return false;
3177
3178   // Make sure we're shifting in the right direction.
3179   if (Mask[i] <= i)
3180     return false;
3181
3182   int s = Mask[i] - i;
3183
3184   // Check the rest of the elements to see if they are consecutive.
3185   for (++i; i != e; ++i) {
3186     int m = Mask[i];
3187     if (m >= 0 && m != s+i)
3188       return false;
3189   }
3190   return true;
3191 }
3192
3193 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3194 /// specifies a shuffle of elements that is suitable for input to 256-bit
3195 /// VSHUFPSY.
3196 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3197                           const X86Subtarget *Subtarget) {
3198   int NumElems = VT.getVectorNumElements();
3199
3200   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3201     return false;
3202
3203   if (NumElems != 8)
3204     return false;
3205
3206   // VSHUFPSY divides the resulting vector into 4 chunks.
3207   // The sources are also splitted into 4 chunks, and each destination
3208   // chunk must come from a different source chunk.
3209   //
3210   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3211   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3212   //
3213   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3214   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3215   //
3216   int QuarterSize = NumElems/4;
3217   int HalfSize = QuarterSize*2;
3218   for (int i = 0; i < QuarterSize; ++i)
3219     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3220       return false;
3221   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3222     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3223       return false;
3224
3225   // The mask of the second half must be the same as the first but with
3226   // the appropriate offsets. This works in the same way as VPERMILPS
3227   // works with masks.
3228   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3229     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3230       return false;
3231     int FstHalfIdx = i-HalfSize;
3232     if (Mask[FstHalfIdx] < 0)
3233       continue;
3234     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3235       return false;
3236   }
3237   for (int i = QuarterSize*3; i < NumElems; ++i) {
3238     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3239       return false;
3240     int FstHalfIdx = i-HalfSize;
3241     if (Mask[FstHalfIdx] < 0)
3242       continue;
3243     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3244       return false;
3245
3246   }
3247
3248   return true;
3249 }
3250
3251 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3252 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3253 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3254   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3255   EVT VT = SVOp->getValueType(0);
3256   int NumElems = VT.getVectorNumElements();
3257
3258   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3259          "Only supports v8i32 and v8f32 types");
3260
3261   int HalfSize = NumElems/2;
3262   unsigned Mask = 0;
3263   for (int i = 0; i != NumElems ; ++i) {
3264     if (SVOp->getMaskElt(i) < 0)
3265       continue;
3266     // The mask of the first half must be equal to the second one.
3267     unsigned Shamt = (i%HalfSize)*2;
3268     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3269     Mask |= Elt << Shamt;
3270   }
3271
3272   return Mask;
3273 }
3274
3275 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3276 /// specifies a shuffle of elements that is suitable for input to 256-bit
3277 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3278 /// version and the mask of the second half isn't binded with the first
3279 /// one.
3280 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3281                            const X86Subtarget *Subtarget) {
3282   int NumElems = VT.getVectorNumElements();
3283
3284   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3285     return false;
3286
3287   if (NumElems != 4)
3288     return false;
3289
3290   // VSHUFPSY divides the resulting vector into 4 chunks.
3291   // The sources are also splitted into 4 chunks, and each destination
3292   // chunk must come from a different source chunk.
3293   //
3294   //  SRC1 =>      X3       X2       X1       X0
3295   //  SRC2 =>      Y3       Y2       Y1       Y0
3296   //
3297   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3298   //
3299   int QuarterSize = NumElems/4;
3300   int HalfSize = QuarterSize*2;
3301   for (int i = 0; i < QuarterSize; ++i)
3302     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3303       return false;
3304   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3305     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3306       return false;
3307   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3308     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3309       return false;
3310   for (int i = QuarterSize*3; i < NumElems; ++i)
3311     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3312       return false;
3313
3314   return true;
3315 }
3316
3317 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3318 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3319 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3321   EVT VT = SVOp->getValueType(0);
3322   int NumElems = VT.getVectorNumElements();
3323
3324   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3325          "Only supports v4i64 and v4f64 types");
3326
3327   int HalfSize = NumElems/2;
3328   unsigned Mask = 0;
3329   for (int i = 0; i != NumElems ; ++i) {
3330     if (SVOp->getMaskElt(i) < 0)
3331       continue;
3332     int Elt = SVOp->getMaskElt(i) % HalfSize;
3333     Mask |= Elt << i;
3334   }
3335
3336   return Mask;
3337 }
3338
3339 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3340 /// specifies a shuffle of elements that is suitable for input to 128-bit
3341 /// SHUFPS and SHUFPD.
3342 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3343   int NumElems = VT.getVectorNumElements();
3344
3345   if (VT.getSizeInBits() != 128)
3346     return false;
3347
3348   if (NumElems != 2 && NumElems != 4)
3349     return false;
3350
3351   int Half = NumElems / 2;
3352   for (int i = 0; i < Half; ++i)
3353     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3354       return false;
3355   for (int i = Half; i < NumElems; ++i)
3356     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3357       return false;
3358
3359   return true;
3360 }
3361
3362 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3363   SmallVector<int, 8> M;
3364   N->getMask(M);
3365   return ::isSHUFPMask(M, N->getValueType(0));
3366 }
3367
3368 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3369 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3370 /// half elements to come from vector 1 (which would equal the dest.) and
3371 /// the upper half to come from vector 2.
3372 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3373   int NumElems = VT.getVectorNumElements();
3374
3375   if (NumElems != 2 && NumElems != 4)
3376     return false;
3377
3378   int Half = NumElems / 2;
3379   for (int i = 0; i < Half; ++i)
3380     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3381       return false;
3382   for (int i = Half; i < NumElems; ++i)
3383     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3384       return false;
3385   return true;
3386 }
3387
3388 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3389   SmallVector<int, 8> M;
3390   N->getMask(M);
3391   return isCommutedSHUFPMask(M, N->getValueType(0));
3392 }
3393
3394 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3395 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3396 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3397   EVT VT = N->getValueType(0);
3398   unsigned NumElems = VT.getVectorNumElements();
3399
3400   if (VT.getSizeInBits() != 128)
3401     return false;
3402
3403   if (NumElems != 4)
3404     return false;
3405
3406   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3407   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3408          isUndefOrEqual(N->getMaskElt(1), 7) &&
3409          isUndefOrEqual(N->getMaskElt(2), 2) &&
3410          isUndefOrEqual(N->getMaskElt(3), 3);
3411 }
3412
3413 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3414 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3415 /// <2, 3, 2, 3>
3416 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3417   EVT VT = N->getValueType(0);
3418   unsigned NumElems = VT.getVectorNumElements();
3419
3420   if (VT.getSizeInBits() != 128)
3421     return false;
3422
3423   if (NumElems != 4)
3424     return false;
3425
3426   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3427          isUndefOrEqual(N->getMaskElt(1), 3) &&
3428          isUndefOrEqual(N->getMaskElt(2), 2) &&
3429          isUndefOrEqual(N->getMaskElt(3), 3);
3430 }
3431
3432 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3433 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3434 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3435   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3436
3437   if (NumElems != 2 && NumElems != 4)
3438     return false;
3439
3440   for (unsigned i = 0; i < NumElems/2; ++i)
3441     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3442       return false;
3443
3444   for (unsigned i = NumElems/2; i < NumElems; ++i)
3445     if (!isUndefOrEqual(N->getMaskElt(i), i))
3446       return false;
3447
3448   return true;
3449 }
3450
3451 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3452 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3453 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3454   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3455
3456   if ((NumElems != 2 && NumElems != 4)
3457       || N->getValueType(0).getSizeInBits() > 128)
3458     return false;
3459
3460   for (unsigned i = 0; i < NumElems/2; ++i)
3461     if (!isUndefOrEqual(N->getMaskElt(i), i))
3462       return false;
3463
3464   for (unsigned i = 0; i < NumElems/2; ++i)
3465     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3466       return false;
3467
3468   return true;
3469 }
3470
3471 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3472 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3473 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3474                          bool V2IsSplat = false) {
3475   int NumElts = VT.getVectorNumElements();
3476
3477   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3478          "Unsupported vector type for unpckh");
3479
3480   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3481     return false;
3482
3483   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3484   // independently on 128-bit lanes.
3485   unsigned NumLanes = VT.getSizeInBits()/128;
3486   unsigned NumLaneElts = NumElts/NumLanes;
3487
3488   unsigned Start = 0;
3489   unsigned End = NumLaneElts;
3490   for (unsigned s = 0; s < NumLanes; ++s) {
3491     for (unsigned i = Start, j = s * NumLaneElts;
3492          i != End;
3493          i += 2, ++j) {
3494       int BitI  = Mask[i];
3495       int BitI1 = Mask[i+1];
3496       if (!isUndefOrEqual(BitI, j))
3497         return false;
3498       if (V2IsSplat) {
3499         if (!isUndefOrEqual(BitI1, NumElts))
3500           return false;
3501       } else {
3502         if (!isUndefOrEqual(BitI1, j + NumElts))
3503           return false;
3504       }
3505     }
3506     // Process the next 128 bits.
3507     Start += NumLaneElts;
3508     End += NumLaneElts;
3509   }
3510
3511   return true;
3512 }
3513
3514 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3515   SmallVector<int, 8> M;
3516   N->getMask(M);
3517   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3518 }
3519
3520 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3521 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3522 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3523                          bool V2IsSplat = false) {
3524   int NumElts = VT.getVectorNumElements();
3525
3526   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3527          "Unsupported vector type for unpckh");
3528
3529   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3530     return false;
3531
3532   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3533   // independently on 128-bit lanes.
3534   unsigned NumLanes = VT.getSizeInBits()/128;
3535   unsigned NumLaneElts = NumElts/NumLanes;
3536
3537   unsigned Start = 0;
3538   unsigned End = NumLaneElts;
3539   for (unsigned l = 0; l != NumLanes; ++l) {
3540     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3541                              i != End; i += 2, ++j) {
3542       int BitI  = Mask[i];
3543       int BitI1 = Mask[i+1];
3544       if (!isUndefOrEqual(BitI, j))
3545         return false;
3546       if (V2IsSplat) {
3547         if (isUndefOrEqual(BitI1, NumElts))
3548           return false;
3549       } else {
3550         if (!isUndefOrEqual(BitI1, j+NumElts))
3551           return false;
3552       }
3553     }
3554     // Process the next 128 bits.
3555     Start += NumLaneElts;
3556     End += NumLaneElts;
3557   }
3558   return true;
3559 }
3560
3561 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3562   SmallVector<int, 8> M;
3563   N->getMask(M);
3564   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3565 }
3566
3567 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3568 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3569 /// <0, 0, 1, 1>
3570 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3571   int NumElems = VT.getVectorNumElements();
3572   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3573     return false;
3574
3575   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3576   // FIXME: Need a better way to get rid of this, there's no latency difference
3577   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3578   // the former later. We should also remove the "_undef" special mask.
3579   if (NumElems == 4 && VT.getSizeInBits() == 256)
3580     return false;
3581
3582   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3583   // independently on 128-bit lanes.
3584   unsigned NumLanes = VT.getSizeInBits() / 128;
3585   unsigned NumLaneElts = NumElems / NumLanes;
3586
3587   for (unsigned s = 0; s < NumLanes; ++s) {
3588     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3589          i != NumLaneElts * (s + 1);
3590          i += 2, ++j) {
3591       int BitI  = Mask[i];
3592       int BitI1 = Mask[i+1];
3593
3594       if (!isUndefOrEqual(BitI, j))
3595         return false;
3596       if (!isUndefOrEqual(BitI1, j))
3597         return false;
3598     }
3599   }
3600
3601   return true;
3602 }
3603
3604 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3605   SmallVector<int, 8> M;
3606   N->getMask(M);
3607   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3608 }
3609
3610 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3611 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3612 /// <2, 2, 3, 3>
3613 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3614   int NumElems = VT.getVectorNumElements();
3615   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3616     return false;
3617
3618   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3619     int BitI  = Mask[i];
3620     int BitI1 = Mask[i+1];
3621     if (!isUndefOrEqual(BitI, j))
3622       return false;
3623     if (!isUndefOrEqual(BitI1, j))
3624       return false;
3625   }
3626   return true;
3627 }
3628
3629 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3630   SmallVector<int, 8> M;
3631   N->getMask(M);
3632   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3633 }
3634
3635 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3636 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3637 /// MOVSD, and MOVD, i.e. setting the lowest element.
3638 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3639   if (VT.getVectorElementType().getSizeInBits() < 32)
3640     return false;
3641
3642   int NumElts = VT.getVectorNumElements();
3643
3644   if (!isUndefOrEqual(Mask[0], NumElts))
3645     return false;
3646
3647   for (int i = 1; i < NumElts; ++i)
3648     if (!isUndefOrEqual(Mask[i], i))
3649       return false;
3650
3651   return true;
3652 }
3653
3654 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3655   SmallVector<int, 8> M;
3656   N->getMask(M);
3657   return ::isMOVLMask(M, N->getValueType(0));
3658 }
3659
3660 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3661 /// as permutations between 128-bit chunks or halves. As an example: this
3662 /// shuffle bellow:
3663 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3664 /// The first half comes from the second half of V1 and the second half from the
3665 /// the second half of V2.
3666 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3667                              const X86Subtarget *Subtarget) {
3668   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3669     return false;
3670
3671   // The shuffle result is divided into half A and half B. In total the two
3672   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3673   // B must come from C, D, E or F.
3674   int HalfSize = VT.getVectorNumElements()/2;
3675   bool MatchA = false, MatchB = false;
3676
3677   // Check if A comes from one of C, D, E, F.
3678   for (int Half = 0; Half < 4; ++Half) {
3679     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3680       MatchA = true;
3681       break;
3682     }
3683   }
3684
3685   // Check if B comes from one of C, D, E, F.
3686   for (int Half = 0; Half < 4; ++Half) {
3687     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3688       MatchB = true;
3689       break;
3690     }
3691   }
3692
3693   return MatchA && MatchB;
3694 }
3695
3696 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3697 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3698 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3699   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3700   EVT VT = SVOp->getValueType(0);
3701
3702   int HalfSize = VT.getVectorNumElements()/2;
3703
3704   int FstHalf = 0, SndHalf = 0;
3705   for (int i = 0; i < HalfSize; ++i) {
3706     if (SVOp->getMaskElt(i) > 0) {
3707       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3708       break;
3709     }
3710   }
3711   for (int i = HalfSize; i < HalfSize*2; ++i) {
3712     if (SVOp->getMaskElt(i) > 0) {
3713       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3714       break;
3715     }
3716   }
3717
3718   return (FstHalf | (SndHalf << 4));
3719 }
3720
3721 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3722 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3723 /// Note that VPERMIL mask matching is different depending whether theunderlying
3724 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3725 /// to the same elements of the low, but to the higher half of the source.
3726 /// In VPERMILPD the two lanes could be shuffled independently of each other
3727 /// with the same restriction that lanes can't be crossed.
3728 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3729                             const X86Subtarget *Subtarget) {
3730   int NumElts = VT.getVectorNumElements();
3731   int NumLanes = VT.getSizeInBits()/128;
3732
3733   if (!Subtarget->hasAVX())
3734     return false;
3735
3736   // Match any permutation of 128-bit vector with 64-bit types
3737   if (NumLanes == 1 && NumElts != 2)
3738     return false;
3739
3740   // Only match 256-bit with 32 types
3741   if (VT.getSizeInBits() == 256 && NumElts != 4)
3742     return false;
3743
3744   // The mask on the high lane is independent of the low. Both can match
3745   // any element in inside its own lane, but can't cross.
3746   int LaneSize = NumElts/NumLanes;
3747   for (int l = 0; l < NumLanes; ++l)
3748     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3749       int LaneStart = l*LaneSize;
3750       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3751         return false;
3752     }
3753
3754   return true;
3755 }
3756
3757 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3758 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3759 /// Note that VPERMIL mask matching is different depending whether theunderlying
3760 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3761 /// to the same elements of the low, but to the higher half of the source.
3762 /// In VPERMILPD the two lanes could be shuffled independently of each other
3763 /// with the same restriction that lanes can't be crossed.
3764 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3765                             const X86Subtarget *Subtarget) {
3766   unsigned NumElts = VT.getVectorNumElements();
3767   unsigned NumLanes = VT.getSizeInBits()/128;
3768
3769   if (!Subtarget->hasAVX())
3770     return false;
3771
3772   // Match any permutation of 128-bit vector with 32-bit types
3773   if (NumLanes == 1 && NumElts != 4)
3774     return false;
3775
3776   // Only match 256-bit with 32 types
3777   if (VT.getSizeInBits() == 256 && NumElts != 8)
3778     return false;
3779
3780   // The mask on the high lane should be the same as the low. Actually,
3781   // they can differ if any of the corresponding index in a lane is undef
3782   // and the other stays in range.
3783   int LaneSize = NumElts/NumLanes;
3784   for (int i = 0; i < LaneSize; ++i) {
3785     int HighElt = i+LaneSize;
3786     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3787     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3788
3789     if (!HighValid || !LowValid)
3790       return false;
3791     if (Mask[i] < 0 || Mask[HighElt] < 0)
3792       continue;
3793     if (Mask[HighElt]-Mask[i] != LaneSize)
3794       return false;
3795   }
3796
3797   return true;
3798 }
3799
3800 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3801 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3802 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3804   EVT VT = SVOp->getValueType(0);
3805
3806   int NumElts = VT.getVectorNumElements();
3807   int NumLanes = VT.getSizeInBits()/128;
3808   int LaneSize = NumElts/NumLanes;
3809
3810   // Although the mask is equal for both lanes do it twice to get the cases
3811   // where a mask will match because the same mask element is undef on the
3812   // first half but valid on the second. This would get pathological cases
3813   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3814   unsigned Mask = 0;
3815   for (int l = 0; l < NumLanes; ++l) {
3816     for (int i = 0; i < LaneSize; ++i) {
3817       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3818       if (MaskElt < 0)
3819         continue;
3820       if (MaskElt >= LaneSize)
3821         MaskElt -= LaneSize;
3822       Mask |= MaskElt << (i*2);
3823     }
3824   }
3825
3826   return Mask;
3827 }
3828
3829 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3830 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3831 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3833   EVT VT = SVOp->getValueType(0);
3834
3835   int NumElts = VT.getVectorNumElements();
3836   int NumLanes = VT.getSizeInBits()/128;
3837
3838   unsigned Mask = 0;
3839   int LaneSize = NumElts/NumLanes;
3840   for (int l = 0; l < NumLanes; ++l)
3841     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3842       int MaskElt = SVOp->getMaskElt(i);
3843       if (MaskElt < 0)
3844         continue;
3845       Mask |= (MaskElt-l*LaneSize) << i;
3846     }
3847
3848   return Mask;
3849 }
3850
3851 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3852 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3853 /// element of vector 2 and the other elements to come from vector 1 in order.
3854 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3855                                bool V2IsSplat = false, bool V2IsUndef = false) {
3856   int NumOps = VT.getVectorNumElements();
3857   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3858     return false;
3859
3860   if (!isUndefOrEqual(Mask[0], 0))
3861     return false;
3862
3863   for (int i = 1; i < NumOps; ++i)
3864     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3865           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3866           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3867       return false;
3868
3869   return true;
3870 }
3871
3872 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3873                            bool V2IsUndef = false) {
3874   SmallVector<int, 8> M;
3875   N->getMask(M);
3876   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3877 }
3878
3879 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3880 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3881 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3882 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3883                          const X86Subtarget *Subtarget) {
3884   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3885     return false;
3886
3887   // The second vector must be undef
3888   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3889     return false;
3890
3891   EVT VT = N->getValueType(0);
3892   unsigned NumElems = VT.getVectorNumElements();
3893
3894   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3895       (VT.getSizeInBits() == 256 && NumElems != 8))
3896     return false;
3897
3898   // "i+1" is the value the indexed mask element must have
3899   for (unsigned i = 0; i < NumElems; i += 2)
3900     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3901         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3902       return false;
3903
3904   return true;
3905 }
3906
3907 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3909 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3910 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3911                          const X86Subtarget *Subtarget) {
3912   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3913     return false;
3914
3915   // The second vector must be undef
3916   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3917     return false;
3918
3919   EVT VT = N->getValueType(0);
3920   unsigned NumElems = VT.getVectorNumElements();
3921
3922   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3923       (VT.getSizeInBits() == 256 && NumElems != 8))
3924     return false;
3925
3926   // "i" is the value the indexed mask element must have
3927   for (unsigned i = 0; i < NumElems; i += 2)
3928     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3929         !isUndefOrEqual(N->getMaskElt(i+1), i))
3930       return false;
3931
3932   return true;
3933 }
3934
3935 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to 256-bit
3937 /// version of MOVDDUP.
3938 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3939                            const X86Subtarget *Subtarget) {
3940   EVT VT = N->getValueType(0);
3941   int NumElts = VT.getVectorNumElements();
3942   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3943
3944   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3945       !V2IsUndef || NumElts != 4)
3946     return false;
3947
3948   for (int i = 0; i != NumElts/2; ++i)
3949     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3950       return false;
3951   for (int i = NumElts/2; i != NumElts; ++i)
3952     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3953       return false;
3954   return true;
3955 }
3956
3957 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3958 /// specifies a shuffle of elements that is suitable for input to 128-bit
3959 /// version of MOVDDUP.
3960 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3961   EVT VT = N->getValueType(0);
3962
3963   if (VT.getSizeInBits() != 128)
3964     return false;
3965
3966   int e = VT.getVectorNumElements() / 2;
3967   for (int i = 0; i < e; ++i)
3968     if (!isUndefOrEqual(N->getMaskElt(i), i))
3969       return false;
3970   for (int i = 0; i < e; ++i)
3971     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3972       return false;
3973   return true;
3974 }
3975
3976 /// isVEXTRACTF128Index - Return true if the specified
3977 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3978 /// suitable for input to VEXTRACTF128.
3979 bool X86::isVEXTRACTF128Index(SDNode *N) {
3980   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3981     return false;
3982
3983   // The index should be aligned on a 128-bit boundary.
3984   uint64_t Index =
3985     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3986
3987   unsigned VL = N->getValueType(0).getVectorNumElements();
3988   unsigned VBits = N->getValueType(0).getSizeInBits();
3989   unsigned ElSize = VBits / VL;
3990   bool Result = (Index * ElSize) % 128 == 0;
3991
3992   return Result;
3993 }
3994
3995 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3996 /// operand specifies a subvector insert that is suitable for input to
3997 /// VINSERTF128.
3998 bool X86::isVINSERTF128Index(SDNode *N) {
3999   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4000     return false;
4001
4002   // The index should be aligned on a 128-bit boundary.
4003   uint64_t Index =
4004     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4005
4006   unsigned VL = N->getValueType(0).getVectorNumElements();
4007   unsigned VBits = N->getValueType(0).getSizeInBits();
4008   unsigned ElSize = VBits / VL;
4009   bool Result = (Index * ElSize) % 128 == 0;
4010
4011   return Result;
4012 }
4013
4014 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4015 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4016 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4017   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4018   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4019
4020   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4021   unsigned Mask = 0;
4022   for (int i = 0; i < NumOperands; ++i) {
4023     int Val = SVOp->getMaskElt(NumOperands-i-1);
4024     if (Val < 0) Val = 0;
4025     if (Val >= NumOperands) Val -= NumOperands;
4026     Mask |= Val;
4027     if (i != NumOperands - 1)
4028       Mask <<= Shift;
4029   }
4030   return Mask;
4031 }
4032
4033 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4034 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4035 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4037   unsigned Mask = 0;
4038   // 8 nodes, but we only care about the last 4.
4039   for (unsigned i = 7; i >= 4; --i) {
4040     int Val = SVOp->getMaskElt(i);
4041     if (Val >= 0)
4042       Mask |= (Val - 4);
4043     if (i != 4)
4044       Mask <<= 2;
4045   }
4046   return Mask;
4047 }
4048
4049 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4050 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4051 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4053   unsigned Mask = 0;
4054   // 8 nodes, but we only care about the first 4.
4055   for (int i = 3; i >= 0; --i) {
4056     int Val = SVOp->getMaskElt(i);
4057     if (Val >= 0)
4058       Mask |= Val;
4059     if (i != 0)
4060       Mask <<= 2;
4061   }
4062   return Mask;
4063 }
4064
4065 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4067 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4069   EVT VVT = N->getValueType(0);
4070   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4071   int Val = 0;
4072
4073   unsigned i, e;
4074   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4075     Val = SVOp->getMaskElt(i);
4076     if (Val >= 0)
4077       break;
4078   }
4079   assert(Val - i > 0 && "PALIGNR imm should be positive");
4080   return (Val - i) * EltSize;
4081 }
4082
4083 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4084 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4085 /// instructions.
4086 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4087   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4088     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4089
4090   uint64_t Index =
4091     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4092
4093   EVT VecVT = N->getOperand(0).getValueType();
4094   EVT ElVT = VecVT.getVectorElementType();
4095
4096   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4097   return Index / NumElemsPerChunk;
4098 }
4099
4100 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4101 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4102 /// instructions.
4103 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4104   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4105     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4106
4107   uint64_t Index =
4108     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4109
4110   EVT VecVT = N->getValueType(0);
4111   EVT ElVT = VecVT.getVectorElementType();
4112
4113   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4114   return Index / NumElemsPerChunk;
4115 }
4116
4117 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4118 /// constant +0.0.
4119 bool X86::isZeroNode(SDValue Elt) {
4120   return ((isa<ConstantSDNode>(Elt) &&
4121            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4122           (isa<ConstantFPSDNode>(Elt) &&
4123            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4124 }
4125
4126 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4127 /// their permute mask.
4128 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4129                                     SelectionDAG &DAG) {
4130   EVT VT = SVOp->getValueType(0);
4131   unsigned NumElems = VT.getVectorNumElements();
4132   SmallVector<int, 8> MaskVec;
4133
4134   for (unsigned i = 0; i != NumElems; ++i) {
4135     int idx = SVOp->getMaskElt(i);
4136     if (idx < 0)
4137       MaskVec.push_back(idx);
4138     else if (idx < (int)NumElems)
4139       MaskVec.push_back(idx + NumElems);
4140     else
4141       MaskVec.push_back(idx - NumElems);
4142   }
4143   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4144                               SVOp->getOperand(0), &MaskVec[0]);
4145 }
4146
4147 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4148 /// the two vector operands have swapped position.
4149 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4150   unsigned NumElems = VT.getVectorNumElements();
4151   for (unsigned i = 0; i != NumElems; ++i) {
4152     int idx = Mask[i];
4153     if (idx < 0)
4154       continue;
4155     else if (idx < (int)NumElems)
4156       Mask[i] = idx + NumElems;
4157     else
4158       Mask[i] = idx - NumElems;
4159   }
4160 }
4161
4162 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4163 /// match movhlps. The lower half elements should come from upper half of
4164 /// V1 (and in order), and the upper half elements should come from the upper
4165 /// half of V2 (and in order).
4166 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4167   EVT VT = Op->getValueType(0);
4168   if (VT.getSizeInBits() != 128)
4169     return false;
4170   if (VT.getVectorNumElements() != 4)
4171     return false;
4172   for (unsigned i = 0, e = 2; i != e; ++i)
4173     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4174       return false;
4175   for (unsigned i = 2; i != 4; ++i)
4176     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4177       return false;
4178   return true;
4179 }
4180
4181 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4182 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4183 /// required.
4184 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4185   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4186     return false;
4187   N = N->getOperand(0).getNode();
4188   if (!ISD::isNON_EXTLoad(N))
4189     return false;
4190   if (LD)
4191     *LD = cast<LoadSDNode>(N);
4192   return true;
4193 }
4194
4195 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4196 /// match movlp{s|d}. The lower half elements should come from lower half of
4197 /// V1 (and in order), and the upper half elements should come from the upper
4198 /// half of V2 (and in order). And since V1 will become the source of the
4199 /// MOVLP, it must be either a vector load or a scalar load to vector.
4200 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4201                                ShuffleVectorSDNode *Op) {
4202   EVT VT = Op->getValueType(0);
4203   if (VT.getSizeInBits() != 128)
4204     return false;
4205
4206   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4207     return false;
4208   // Is V2 is a vector load, don't do this transformation. We will try to use
4209   // load folding shufps op.
4210   if (ISD::isNON_EXTLoad(V2))
4211     return false;
4212
4213   unsigned NumElems = VT.getVectorNumElements();
4214
4215   if (NumElems != 2 && NumElems != 4)
4216     return false;
4217   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4218     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4219       return false;
4220   for (unsigned i = NumElems/2; i != NumElems; ++i)
4221     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4222       return false;
4223   return true;
4224 }
4225
4226 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4227 /// all the same.
4228 static bool isSplatVector(SDNode *N) {
4229   if (N->getOpcode() != ISD::BUILD_VECTOR)
4230     return false;
4231
4232   SDValue SplatValue = N->getOperand(0);
4233   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4234     if (N->getOperand(i) != SplatValue)
4235       return false;
4236   return true;
4237 }
4238
4239 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4240 /// to an zero vector.
4241 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4242 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4243   SDValue V1 = N->getOperand(0);
4244   SDValue V2 = N->getOperand(1);
4245   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4246   for (unsigned i = 0; i != NumElems; ++i) {
4247     int Idx = N->getMaskElt(i);
4248     if (Idx >= (int)NumElems) {
4249       unsigned Opc = V2.getOpcode();
4250       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4251         continue;
4252       if (Opc != ISD::BUILD_VECTOR ||
4253           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4254         return false;
4255     } else if (Idx >= 0) {
4256       unsigned Opc = V1.getOpcode();
4257       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4258         continue;
4259       if (Opc != ISD::BUILD_VECTOR ||
4260           !X86::isZeroNode(V1.getOperand(Idx)))
4261         return false;
4262     }
4263   }
4264   return true;
4265 }
4266
4267 /// getZeroVector - Returns a vector of specified type with all zero elements.
4268 ///
4269 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4270                              DebugLoc dl) {
4271   assert(VT.isVector() && "Expected a vector type");
4272
4273   // Always build SSE zero vectors as <4 x i32> bitcasted
4274   // to their dest type. This ensures they get CSE'd.
4275   SDValue Vec;
4276   if (VT.getSizeInBits() == 128) {  // SSE
4277     if (HasSSE2) {  // SSE2
4278       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4279       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4280     } else { // SSE1
4281       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4282       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4283     }
4284   } else if (VT.getSizeInBits() == 256) { // AVX
4285     // 256-bit logic and arithmetic instructions in AVX are
4286     // all floating-point, no support for integer ops. Default
4287     // to emitting fp zeroed vectors then.
4288     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4289     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4290     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4291   }
4292   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4293 }
4294
4295 /// getOnesVector - Returns a vector of specified type with all bits set.
4296 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4297 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4298 /// original type, ensuring they get CSE'd.
4299 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4300   assert(VT.isVector() && "Expected a vector type");
4301   assert((VT.is128BitVector() || VT.is256BitVector())
4302          && "Expected a 128-bit or 256-bit vector type");
4303
4304   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4305   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4306                             Cst, Cst, Cst, Cst);
4307
4308   if (VT.is256BitVector()) {
4309     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4310                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4311     Vec = Insert128BitVector(InsV, Vec,
4312                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4313   }
4314
4315   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4316 }
4317
4318 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4319 /// that point to V2 points to its first element.
4320 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4321   EVT VT = SVOp->getValueType(0);
4322   unsigned NumElems = VT.getVectorNumElements();
4323
4324   bool Changed = false;
4325   SmallVector<int, 8> MaskVec;
4326   SVOp->getMask(MaskVec);
4327
4328   for (unsigned i = 0; i != NumElems; ++i) {
4329     if (MaskVec[i] > (int)NumElems) {
4330       MaskVec[i] = NumElems;
4331       Changed = true;
4332     }
4333   }
4334   if (Changed)
4335     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4336                                 SVOp->getOperand(1), &MaskVec[0]);
4337   return SDValue(SVOp, 0);
4338 }
4339
4340 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4341 /// operation of specified width.
4342 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4343                        SDValue V2) {
4344   unsigned NumElems = VT.getVectorNumElements();
4345   SmallVector<int, 8> Mask;
4346   Mask.push_back(NumElems);
4347   for (unsigned i = 1; i != NumElems; ++i)
4348     Mask.push_back(i);
4349   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4350 }
4351
4352 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4353 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4354                           SDValue V2) {
4355   unsigned NumElems = VT.getVectorNumElements();
4356   SmallVector<int, 8> Mask;
4357   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4358     Mask.push_back(i);
4359     Mask.push_back(i + NumElems);
4360   }
4361   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4362 }
4363
4364 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4365 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4366                           SDValue V2) {
4367   unsigned NumElems = VT.getVectorNumElements();
4368   unsigned Half = NumElems/2;
4369   SmallVector<int, 8> Mask;
4370   for (unsigned i = 0; i != Half; ++i) {
4371     Mask.push_back(i + Half);
4372     Mask.push_back(i + NumElems + Half);
4373   }
4374   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4375 }
4376
4377 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4378 // a generic shuffle instruction because the target has no such instructions.
4379 // Generate shuffles which repeat i16 and i8 several times until they can be
4380 // represented by v4f32 and then be manipulated by target suported shuffles.
4381 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4382   EVT VT = V.getValueType();
4383   int NumElems = VT.getVectorNumElements();
4384   DebugLoc dl = V.getDebugLoc();
4385
4386   while (NumElems > 4) {
4387     if (EltNo < NumElems/2) {
4388       V = getUnpackl(DAG, dl, VT, V, V);
4389     } else {
4390       V = getUnpackh(DAG, dl, VT, V, V);
4391       EltNo -= NumElems/2;
4392     }
4393     NumElems >>= 1;
4394   }
4395   return V;
4396 }
4397
4398 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4399 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4400   EVT VT = V.getValueType();
4401   DebugLoc dl = V.getDebugLoc();
4402   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4403          && "Vector size not supported");
4404
4405   if (VT.getSizeInBits() == 128) {
4406     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4407     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4408     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4409                              &SplatMask[0]);
4410   } else {
4411     // To use VPERMILPS to splat scalars, the second half of indicies must
4412     // refer to the higher part, which is a duplication of the lower one,
4413     // because VPERMILPS can only handle in-lane permutations.
4414     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4415                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4416
4417     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4418     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4419                              &SplatMask[0]);
4420   }
4421
4422   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4423 }
4424
4425 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4426 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4427   EVT SrcVT = SV->getValueType(0);
4428   SDValue V1 = SV->getOperand(0);
4429   DebugLoc dl = SV->getDebugLoc();
4430
4431   int EltNo = SV->getSplatIndex();
4432   int NumElems = SrcVT.getVectorNumElements();
4433   unsigned Size = SrcVT.getSizeInBits();
4434
4435   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4436           "Unknown how to promote splat for type");
4437
4438   // Extract the 128-bit part containing the splat element and update
4439   // the splat element index when it refers to the higher register.
4440   if (Size == 256) {
4441     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4442     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4443     if (Idx > 0)
4444       EltNo -= NumElems/2;
4445   }
4446
4447   // All i16 and i8 vector types can't be used directly by a generic shuffle
4448   // instruction because the target has no such instruction. Generate shuffles
4449   // which repeat i16 and i8 several times until they fit in i32, and then can
4450   // be manipulated by target suported shuffles.
4451   EVT EltVT = SrcVT.getVectorElementType();
4452   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4453     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4454
4455   // Recreate the 256-bit vector and place the same 128-bit vector
4456   // into the low and high part. This is necessary because we want
4457   // to use VPERM* to shuffle the vectors
4458   if (Size == 256) {
4459     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4460                          DAG.getConstant(0, MVT::i32), DAG, dl);
4461     V1 = Insert128BitVector(InsV, V1,
4462                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4463   }
4464
4465   return getLegalSplat(DAG, V1, EltNo);
4466 }
4467
4468 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4469 /// vector of zero or undef vector.  This produces a shuffle where the low
4470 /// element of V2 is swizzled into the zero/undef vector, landing at element
4471 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4472 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4473                                              bool isZero, bool HasSSE2,
4474                                              SelectionDAG &DAG) {
4475   EVT VT = V2.getValueType();
4476   SDValue V1 = isZero
4477     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4478   unsigned NumElems = VT.getVectorNumElements();
4479   SmallVector<int, 16> MaskVec;
4480   for (unsigned i = 0; i != NumElems; ++i)
4481     // If this is the insertion idx, put the low elt of V2 here.
4482     MaskVec.push_back(i == Idx ? NumElems : i);
4483   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4484 }
4485
4486 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4487 /// element of the result of the vector shuffle.
4488 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4489                                    unsigned Depth) {
4490   if (Depth == 6)
4491     return SDValue();  // Limit search depth.
4492
4493   SDValue V = SDValue(N, 0);
4494   EVT VT = V.getValueType();
4495   unsigned Opcode = V.getOpcode();
4496
4497   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4498   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4499     Index = SV->getMaskElt(Index);
4500
4501     if (Index < 0)
4502       return DAG.getUNDEF(VT.getVectorElementType());
4503
4504     int NumElems = VT.getVectorNumElements();
4505     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4506     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4507   }
4508
4509   // Recurse into target specific vector shuffles to find scalars.
4510   if (isTargetShuffle(Opcode)) {
4511     int NumElems = VT.getVectorNumElements();
4512     SmallVector<unsigned, 16> ShuffleMask;
4513     SDValue ImmN;
4514
4515     switch(Opcode) {
4516     case X86ISD::SHUFPS:
4517     case X86ISD::SHUFPD:
4518       ImmN = N->getOperand(N->getNumOperands()-1);
4519       DecodeSHUFPSMask(NumElems,
4520                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4521                        ShuffleMask);
4522       break;
4523     case X86ISD::PUNPCKHBW:
4524     case X86ISD::PUNPCKHWD:
4525     case X86ISD::PUNPCKHDQ:
4526     case X86ISD::PUNPCKHQDQ:
4527       DecodePUNPCKHMask(NumElems, ShuffleMask);
4528       break;
4529     case X86ISD::UNPCKHPS:
4530     case X86ISD::UNPCKHPD:
4531     case X86ISD::VUNPCKHPSY:
4532     case X86ISD::VUNPCKHPDY:
4533       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4534       break;
4535     case X86ISD::PUNPCKLBW:
4536     case X86ISD::PUNPCKLWD:
4537     case X86ISD::PUNPCKLDQ:
4538     case X86ISD::PUNPCKLQDQ:
4539       DecodePUNPCKLMask(VT, ShuffleMask);
4540       break;
4541     case X86ISD::UNPCKLPS:
4542     case X86ISD::UNPCKLPD:
4543     case X86ISD::VUNPCKLPSY:
4544     case X86ISD::VUNPCKLPDY:
4545       DecodeUNPCKLPMask(VT, ShuffleMask);
4546       break;
4547     case X86ISD::MOVHLPS:
4548       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4549       break;
4550     case X86ISD::MOVLHPS:
4551       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4552       break;
4553     case X86ISD::PSHUFD:
4554       ImmN = N->getOperand(N->getNumOperands()-1);
4555       DecodePSHUFMask(NumElems,
4556                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4557                       ShuffleMask);
4558       break;
4559     case X86ISD::PSHUFHW:
4560       ImmN = N->getOperand(N->getNumOperands()-1);
4561       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4562                         ShuffleMask);
4563       break;
4564     case X86ISD::PSHUFLW:
4565       ImmN = N->getOperand(N->getNumOperands()-1);
4566       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4567                         ShuffleMask);
4568       break;
4569     case X86ISD::MOVSS:
4570     case X86ISD::MOVSD: {
4571       // The index 0 always comes from the first element of the second source,
4572       // this is why MOVSS and MOVSD are used in the first place. The other
4573       // elements come from the other positions of the first source vector.
4574       unsigned OpNum = (Index == 0) ? 1 : 0;
4575       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4576                                  Depth+1);
4577     }
4578     case X86ISD::VPERMILPS:
4579       ImmN = N->getOperand(N->getNumOperands()-1);
4580       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4581                         ShuffleMask);
4582       break;
4583     case X86ISD::VPERMILPSY:
4584       ImmN = N->getOperand(N->getNumOperands()-1);
4585       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4586                         ShuffleMask);
4587       break;
4588     case X86ISD::VPERMILPD:
4589       ImmN = N->getOperand(N->getNumOperands()-1);
4590       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4591                         ShuffleMask);
4592       break;
4593     case X86ISD::VPERMILPDY:
4594       ImmN = N->getOperand(N->getNumOperands()-1);
4595       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4596                         ShuffleMask);
4597       break;
4598     case X86ISD::VPERM2F128:
4599       ImmN = N->getOperand(N->getNumOperands()-1);
4600       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4601                            ShuffleMask);
4602       break;
4603     default:
4604       assert("not implemented for target shuffle node");
4605       return SDValue();
4606     }
4607
4608     Index = ShuffleMask[Index];
4609     if (Index < 0)
4610       return DAG.getUNDEF(VT.getVectorElementType());
4611
4612     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4613     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4614                                Depth+1);
4615   }
4616
4617   // Actual nodes that may contain scalar elements
4618   if (Opcode == ISD::BITCAST) {
4619     V = V.getOperand(0);
4620     EVT SrcVT = V.getValueType();
4621     unsigned NumElems = VT.getVectorNumElements();
4622
4623     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4624       return SDValue();
4625   }
4626
4627   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4628     return (Index == 0) ? V.getOperand(0)
4629                           : DAG.getUNDEF(VT.getVectorElementType());
4630
4631   if (V.getOpcode() == ISD::BUILD_VECTOR)
4632     return V.getOperand(Index);
4633
4634   return SDValue();
4635 }
4636
4637 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4638 /// shuffle operation which come from a consecutively from a zero. The
4639 /// search can start in two different directions, from left or right.
4640 static
4641 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4642                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4643   int i = 0;
4644
4645   while (i < NumElems) {
4646     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4647     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4648     if (!(Elt.getNode() &&
4649          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4650       break;
4651     ++i;
4652   }
4653
4654   return i;
4655 }
4656
4657 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4658 /// MaskE correspond consecutively to elements from one of the vector operands,
4659 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4660 static
4661 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4662                               int OpIdx, int NumElems, unsigned &OpNum) {
4663   bool SeenV1 = false;
4664   bool SeenV2 = false;
4665
4666   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4667     int Idx = SVOp->getMaskElt(i);
4668     // Ignore undef indicies
4669     if (Idx < 0)
4670       continue;
4671
4672     if (Idx < NumElems)
4673       SeenV1 = true;
4674     else
4675       SeenV2 = true;
4676
4677     // Only accept consecutive elements from the same vector
4678     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4679       return false;
4680   }
4681
4682   OpNum = SeenV1 ? 0 : 1;
4683   return true;
4684 }
4685
4686 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4687 /// logical left shift of a vector.
4688 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4689                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4690   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4691   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4692               false /* check zeros from right */, DAG);
4693   unsigned OpSrc;
4694
4695   if (!NumZeros)
4696     return false;
4697
4698   // Considering the elements in the mask that are not consecutive zeros,
4699   // check if they consecutively come from only one of the source vectors.
4700   //
4701   //               V1 = {X, A, B, C}     0
4702   //                         \  \  \    /
4703   //   vector_shuffle V1, V2 <1, 2, 3, X>
4704   //
4705   if (!isShuffleMaskConsecutive(SVOp,
4706             0,                   // Mask Start Index
4707             NumElems-NumZeros-1, // Mask End Index
4708             NumZeros,            // Where to start looking in the src vector
4709             NumElems,            // Number of elements in vector
4710             OpSrc))              // Which source operand ?
4711     return false;
4712
4713   isLeft = false;
4714   ShAmt = NumZeros;
4715   ShVal = SVOp->getOperand(OpSrc);
4716   return true;
4717 }
4718
4719 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4720 /// logical left shift of a vector.
4721 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4722                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4723   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4724   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4725               true /* check zeros from left */, DAG);
4726   unsigned OpSrc;
4727
4728   if (!NumZeros)
4729     return false;
4730
4731   // Considering the elements in the mask that are not consecutive zeros,
4732   // check if they consecutively come from only one of the source vectors.
4733   //
4734   //                           0    { A, B, X, X } = V2
4735   //                          / \    /  /
4736   //   vector_shuffle V1, V2 <X, X, 4, 5>
4737   //
4738   if (!isShuffleMaskConsecutive(SVOp,
4739             NumZeros,     // Mask Start Index
4740             NumElems-1,   // Mask End Index
4741             0,            // Where to start looking in the src vector
4742             NumElems,     // Number of elements in vector
4743             OpSrc))       // Which source operand ?
4744     return false;
4745
4746   isLeft = true;
4747   ShAmt = NumZeros;
4748   ShVal = SVOp->getOperand(OpSrc);
4749   return true;
4750 }
4751
4752 /// isVectorShift - Returns true if the shuffle can be implemented as a
4753 /// logical left or right shift of a vector.
4754 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4755                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4756   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4757       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4758     return true;
4759
4760   return false;
4761 }
4762
4763 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4764 ///
4765 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4766                                        unsigned NumNonZero, unsigned NumZero,
4767                                        SelectionDAG &DAG,
4768                                        const TargetLowering &TLI) {
4769   if (NumNonZero > 8)
4770     return SDValue();
4771
4772   DebugLoc dl = Op.getDebugLoc();
4773   SDValue V(0, 0);
4774   bool First = true;
4775   for (unsigned i = 0; i < 16; ++i) {
4776     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4777     if (ThisIsNonZero && First) {
4778       if (NumZero)
4779         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4780       else
4781         V = DAG.getUNDEF(MVT::v8i16);
4782       First = false;
4783     }
4784
4785     if ((i & 1) != 0) {
4786       SDValue ThisElt(0, 0), LastElt(0, 0);
4787       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4788       if (LastIsNonZero) {
4789         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4790                               MVT::i16, Op.getOperand(i-1));
4791       }
4792       if (ThisIsNonZero) {
4793         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4794         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4795                               ThisElt, DAG.getConstant(8, MVT::i8));
4796         if (LastIsNonZero)
4797           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4798       } else
4799         ThisElt = LastElt;
4800
4801       if (ThisElt.getNode())
4802         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4803                         DAG.getIntPtrConstant(i/2));
4804     }
4805   }
4806
4807   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4808 }
4809
4810 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4811 ///
4812 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4813                                      unsigned NumNonZero, unsigned NumZero,
4814                                      SelectionDAG &DAG,
4815                                      const TargetLowering &TLI) {
4816   if (NumNonZero > 4)
4817     return SDValue();
4818
4819   DebugLoc dl = Op.getDebugLoc();
4820   SDValue V(0, 0);
4821   bool First = true;
4822   for (unsigned i = 0; i < 8; ++i) {
4823     bool isNonZero = (NonZeros & (1 << i)) != 0;
4824     if (isNonZero) {
4825       if (First) {
4826         if (NumZero)
4827           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4828         else
4829           V = DAG.getUNDEF(MVT::v8i16);
4830         First = false;
4831       }
4832       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4833                       MVT::v8i16, V, Op.getOperand(i),
4834                       DAG.getIntPtrConstant(i));
4835     }
4836   }
4837
4838   return V;
4839 }
4840
4841 /// getVShift - Return a vector logical shift node.
4842 ///
4843 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4844                          unsigned NumBits, SelectionDAG &DAG,
4845                          const TargetLowering &TLI, DebugLoc dl) {
4846   EVT ShVT = MVT::v2i64;
4847   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4848   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4849   return DAG.getNode(ISD::BITCAST, dl, VT,
4850                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4851                              DAG.getConstant(NumBits,
4852                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4853 }
4854
4855 SDValue
4856 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4857                                           SelectionDAG &DAG) const {
4858
4859   // Check if the scalar load can be widened into a vector load. And if
4860   // the address is "base + cst" see if the cst can be "absorbed" into
4861   // the shuffle mask.
4862   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4863     SDValue Ptr = LD->getBasePtr();
4864     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4865       return SDValue();
4866     EVT PVT = LD->getValueType(0);
4867     if (PVT != MVT::i32 && PVT != MVT::f32)
4868       return SDValue();
4869
4870     int FI = -1;
4871     int64_t Offset = 0;
4872     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4873       FI = FINode->getIndex();
4874       Offset = 0;
4875     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4876                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4877       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4878       Offset = Ptr.getConstantOperandVal(1);
4879       Ptr = Ptr.getOperand(0);
4880     } else {
4881       return SDValue();
4882     }
4883
4884     // FIXME: 256-bit vector instructions don't require a strict alignment,
4885     // improve this code to support it better.
4886     unsigned RequiredAlign = VT.getSizeInBits()/8;
4887     SDValue Chain = LD->getChain();
4888     // Make sure the stack object alignment is at least 16 or 32.
4889     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4890     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4891       if (MFI->isFixedObjectIndex(FI)) {
4892         // Can't change the alignment. FIXME: It's possible to compute
4893         // the exact stack offset and reference FI + adjust offset instead.
4894         // If someone *really* cares about this. That's the way to implement it.
4895         return SDValue();
4896       } else {
4897         MFI->setObjectAlignment(FI, RequiredAlign);
4898       }
4899     }
4900
4901     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4902     // Ptr + (Offset & ~15).
4903     if (Offset < 0)
4904       return SDValue();
4905     if ((Offset % RequiredAlign) & 3)
4906       return SDValue();
4907     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4908     if (StartOffset)
4909       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4910                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4911
4912     int EltNo = (Offset - StartOffset) >> 2;
4913     int NumElems = VT.getVectorNumElements();
4914
4915     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4916     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4917     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4918                              LD->getPointerInfo().getWithOffset(StartOffset),
4919                              false, false, 0);
4920
4921     // Canonicalize it to a v4i32 or v8i32 shuffle.
4922     SmallVector<int, 8> Mask;
4923     for (int i = 0; i < NumElems; ++i)
4924       Mask.push_back(EltNo);
4925
4926     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4927     return DAG.getNode(ISD::BITCAST, dl, NVT,
4928                        DAG.getVectorShuffle(CanonVT, dl, V1,
4929                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4930   }
4931
4932   return SDValue();
4933 }
4934
4935 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4936 /// vector of type 'VT', see if the elements can be replaced by a single large
4937 /// load which has the same value as a build_vector whose operands are 'elts'.
4938 ///
4939 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4940 ///
4941 /// FIXME: we'd also like to handle the case where the last elements are zero
4942 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4943 /// There's even a handy isZeroNode for that purpose.
4944 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4945                                         DebugLoc &DL, SelectionDAG &DAG) {
4946   EVT EltVT = VT.getVectorElementType();
4947   unsigned NumElems = Elts.size();
4948
4949   LoadSDNode *LDBase = NULL;
4950   unsigned LastLoadedElt = -1U;
4951
4952   // For each element in the initializer, see if we've found a load or an undef.
4953   // If we don't find an initial load element, or later load elements are
4954   // non-consecutive, bail out.
4955   for (unsigned i = 0; i < NumElems; ++i) {
4956     SDValue Elt = Elts[i];
4957
4958     if (!Elt.getNode() ||
4959         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4960       return SDValue();
4961     if (!LDBase) {
4962       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4963         return SDValue();
4964       LDBase = cast<LoadSDNode>(Elt.getNode());
4965       LastLoadedElt = i;
4966       continue;
4967     }
4968     if (Elt.getOpcode() == ISD::UNDEF)
4969       continue;
4970
4971     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4972     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4973       return SDValue();
4974     LastLoadedElt = i;
4975   }
4976
4977   // If we have found an entire vector of loads and undefs, then return a large
4978   // load of the entire vector width starting at the base pointer.  If we found
4979   // consecutive loads for the low half, generate a vzext_load node.
4980   if (LastLoadedElt == NumElems - 1) {
4981     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4982       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4983                          LDBase->getPointerInfo(),
4984                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4985     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4986                        LDBase->getPointerInfo(),
4987                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4988                        LDBase->getAlignment());
4989   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4990              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4991     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4992     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4993     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4994                                               Ops, 2, MVT::i32,
4995                                               LDBase->getMemOperand());
4996     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4997   }
4998   return SDValue();
4999 }
5000
5001 SDValue
5002 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5003   DebugLoc dl = Op.getDebugLoc();
5004
5005   EVT VT = Op.getValueType();
5006   EVT ExtVT = VT.getVectorElementType();
5007   unsigned NumElems = Op.getNumOperands();
5008
5009   // Vectors containing all zeros can be matched by pxor and xorps later
5010   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5011     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5012     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5013     if (Op.getValueType() == MVT::v4i32 ||
5014         Op.getValueType() == MVT::v8i32)
5015       return Op;
5016
5017     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
5018   }
5019
5020   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5021   // vectors or broken into v4i32 operations on 256-bit vectors.
5022   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5023     if (Op.getValueType() == MVT::v4i32)
5024       return Op;
5025
5026     return getOnesVector(Op.getValueType(), DAG, dl);
5027   }
5028
5029   unsigned EVTBits = ExtVT.getSizeInBits();
5030
5031   unsigned NumZero  = 0;
5032   unsigned NumNonZero = 0;
5033   unsigned NonZeros = 0;
5034   bool IsAllConstants = true;
5035   SmallSet<SDValue, 8> Values;
5036   for (unsigned i = 0; i < NumElems; ++i) {
5037     SDValue Elt = Op.getOperand(i);
5038     if (Elt.getOpcode() == ISD::UNDEF)
5039       continue;
5040     Values.insert(Elt);
5041     if (Elt.getOpcode() != ISD::Constant &&
5042         Elt.getOpcode() != ISD::ConstantFP)
5043       IsAllConstants = false;
5044     if (X86::isZeroNode(Elt))
5045       NumZero++;
5046     else {
5047       NonZeros |= (1 << i);
5048       NumNonZero++;
5049     }
5050   }
5051
5052   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5053   if (NumNonZero == 0)
5054     return DAG.getUNDEF(VT);
5055
5056   // Special case for single non-zero, non-undef, element.
5057   if (NumNonZero == 1) {
5058     unsigned Idx = CountTrailingZeros_32(NonZeros);
5059     SDValue Item = Op.getOperand(Idx);
5060
5061     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5062     // the value are obviously zero, truncate the value to i32 and do the
5063     // insertion that way.  Only do this if the value is non-constant or if the
5064     // value is a constant being inserted into element 0.  It is cheaper to do
5065     // a constant pool load than it is to do a movd + shuffle.
5066     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5067         (!IsAllConstants || Idx == 0)) {
5068       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5069         // Handle SSE only.
5070         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5071         EVT VecVT = MVT::v4i32;
5072         unsigned VecElts = 4;
5073
5074         // Truncate the value (which may itself be a constant) to i32, and
5075         // convert it to a vector with movd (S2V+shuffle to zero extend).
5076         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5077         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5078         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5079                                            Subtarget->hasSSE2(), DAG);
5080
5081         // Now we have our 32-bit value zero extended in the low element of
5082         // a vector.  If Idx != 0, swizzle it into place.
5083         if (Idx != 0) {
5084           SmallVector<int, 4> Mask;
5085           Mask.push_back(Idx);
5086           for (unsigned i = 1; i != VecElts; ++i)
5087             Mask.push_back(i);
5088           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5089                                       DAG.getUNDEF(Item.getValueType()),
5090                                       &Mask[0]);
5091         }
5092         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5093       }
5094     }
5095
5096     // If we have a constant or non-constant insertion into the low element of
5097     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5098     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5099     // depending on what the source datatype is.
5100     if (Idx == 0) {
5101       if (NumZero == 0) {
5102         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5103       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5104           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5105         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5106         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5107         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
5108                                            DAG);
5109       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5110         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5111         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5112         EVT MiddleVT = MVT::v4i32;
5113         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5114         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5115                                            Subtarget->hasSSE2(), DAG);
5116         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5117       }
5118     }
5119
5120     // Is it a vector logical left shift?
5121     if (NumElems == 2 && Idx == 1 &&
5122         X86::isZeroNode(Op.getOperand(0)) &&
5123         !X86::isZeroNode(Op.getOperand(1))) {
5124       unsigned NumBits = VT.getSizeInBits();
5125       return getVShift(true, VT,
5126                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5127                                    VT, Op.getOperand(1)),
5128                        NumBits/2, DAG, *this, dl);
5129     }
5130
5131     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5132       return SDValue();
5133
5134     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5135     // is a non-constant being inserted into an element other than the low one,
5136     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5137     // movd/movss) to move this into the low element, then shuffle it into
5138     // place.
5139     if (EVTBits == 32) {
5140       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5141
5142       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5143       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5144                                          Subtarget->hasSSE2(), DAG);
5145       SmallVector<int, 8> MaskVec;
5146       for (unsigned i = 0; i < NumElems; i++)
5147         MaskVec.push_back(i == Idx ? 0 : 1);
5148       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5149     }
5150   }
5151
5152   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5153   if (Values.size() == 1) {
5154     if (EVTBits == 32) {
5155       // Instead of a shuffle like this:
5156       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5157       // Check if it's possible to issue this instead.
5158       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5159       unsigned Idx = CountTrailingZeros_32(NonZeros);
5160       SDValue Item = Op.getOperand(Idx);
5161       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5162         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5163     }
5164     return SDValue();
5165   }
5166
5167   // A vector full of immediates; various special cases are already
5168   // handled, so this is best done with a single constant-pool load.
5169   if (IsAllConstants)
5170     return SDValue();
5171
5172   // For AVX-length vectors, build the individual 128-bit pieces and use
5173   // shuffles to put them in place.
5174   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5175     SmallVector<SDValue, 32> V;
5176     for (unsigned i = 0; i < NumElems; ++i)
5177       V.push_back(Op.getOperand(i));
5178
5179     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5180
5181     // Build both the lower and upper subvector.
5182     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5183     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5184                                 NumElems/2);
5185
5186     // Recreate the wider vector with the lower and upper part.
5187     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5188                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5189     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5190                               DAG, dl);
5191   }
5192
5193   // Let legalizer expand 2-wide build_vectors.
5194   if (EVTBits == 64) {
5195     if (NumNonZero == 1) {
5196       // One half is zero or undef.
5197       unsigned Idx = CountTrailingZeros_32(NonZeros);
5198       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5199                                  Op.getOperand(Idx));
5200       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5201                                          Subtarget->hasSSE2(), DAG);
5202     }
5203     return SDValue();
5204   }
5205
5206   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5207   if (EVTBits == 8 && NumElems == 16) {
5208     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5209                                         *this);
5210     if (V.getNode()) return V;
5211   }
5212
5213   if (EVTBits == 16 && NumElems == 8) {
5214     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5215                                       *this);
5216     if (V.getNode()) return V;
5217   }
5218
5219   // If element VT is == 32 bits, turn it into a number of shuffles.
5220   SmallVector<SDValue, 8> V;
5221   V.resize(NumElems);
5222   if (NumElems == 4 && NumZero > 0) {
5223     for (unsigned i = 0; i < 4; ++i) {
5224       bool isZero = !(NonZeros & (1 << i));
5225       if (isZero)
5226         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5227       else
5228         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5229     }
5230
5231     for (unsigned i = 0; i < 2; ++i) {
5232       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5233         default: break;
5234         case 0:
5235           V[i] = V[i*2];  // Must be a zero vector.
5236           break;
5237         case 1:
5238           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5239           break;
5240         case 2:
5241           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5242           break;
5243         case 3:
5244           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5245           break;
5246       }
5247     }
5248
5249     SmallVector<int, 8> MaskVec;
5250     bool Reverse = (NonZeros & 0x3) == 2;
5251     for (unsigned i = 0; i < 2; ++i)
5252       MaskVec.push_back(Reverse ? 1-i : i);
5253     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5254     for (unsigned i = 0; i < 2; ++i)
5255       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5256     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5257   }
5258
5259   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5260     // Check for a build vector of consecutive loads.
5261     for (unsigned i = 0; i < NumElems; ++i)
5262       V[i] = Op.getOperand(i);
5263
5264     // Check for elements which are consecutive loads.
5265     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5266     if (LD.getNode())
5267       return LD;
5268
5269     // For SSE 4.1, use insertps to put the high elements into the low element.
5270     if (getSubtarget()->hasSSE41()) {
5271       SDValue Result;
5272       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5273         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5274       else
5275         Result = DAG.getUNDEF(VT);
5276
5277       for (unsigned i = 1; i < NumElems; ++i) {
5278         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5279         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5280                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5281       }
5282       return Result;
5283     }
5284
5285     // Otherwise, expand into a number of unpckl*, start by extending each of
5286     // our (non-undef) elements to the full vector width with the element in the
5287     // bottom slot of the vector (which generates no code for SSE).
5288     for (unsigned i = 0; i < NumElems; ++i) {
5289       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5290         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5291       else
5292         V[i] = DAG.getUNDEF(VT);
5293     }
5294
5295     // Next, we iteratively mix elements, e.g. for v4f32:
5296     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5297     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5298     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5299     unsigned EltStride = NumElems >> 1;
5300     while (EltStride != 0) {
5301       for (unsigned i = 0; i < EltStride; ++i) {
5302         // If V[i+EltStride] is undef and this is the first round of mixing,
5303         // then it is safe to just drop this shuffle: V[i] is already in the
5304         // right place, the one element (since it's the first round) being
5305         // inserted as undef can be dropped.  This isn't safe for successive
5306         // rounds because they will permute elements within both vectors.
5307         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5308             EltStride == NumElems/2)
5309           continue;
5310
5311         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5312       }
5313       EltStride >>= 1;
5314     }
5315     return V[0];
5316   }
5317   return SDValue();
5318 }
5319
5320 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5321 // them in a MMX register.  This is better than doing a stack convert.
5322 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5323   DebugLoc dl = Op.getDebugLoc();
5324   EVT ResVT = Op.getValueType();
5325
5326   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5327          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5328   int Mask[2];
5329   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5330   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5331   InVec = Op.getOperand(1);
5332   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5333     unsigned NumElts = ResVT.getVectorNumElements();
5334     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5335     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5336                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5337   } else {
5338     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5339     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5340     Mask[0] = 0; Mask[1] = 2;
5341     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5342   }
5343   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5344 }
5345
5346 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5347 // to create 256-bit vectors from two other 128-bit ones.
5348 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5349   DebugLoc dl = Op.getDebugLoc();
5350   EVT ResVT = Op.getValueType();
5351
5352   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5353
5354   SDValue V1 = Op.getOperand(0);
5355   SDValue V2 = Op.getOperand(1);
5356   unsigned NumElems = ResVT.getVectorNumElements();
5357
5358   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5359                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5360   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5361                             DAG, dl);
5362 }
5363
5364 SDValue
5365 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5366   EVT ResVT = Op.getValueType();
5367
5368   assert(Op.getNumOperands() == 2);
5369   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5370          "Unsupported CONCAT_VECTORS for value type");
5371
5372   // We support concatenate two MMX registers and place them in a MMX register.
5373   // This is better than doing a stack convert.
5374   if (ResVT.is128BitVector())
5375     return LowerMMXCONCAT_VECTORS(Op, DAG);
5376
5377   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5378   // from two other 128-bit ones.
5379   return LowerAVXCONCAT_VECTORS(Op, DAG);
5380 }
5381
5382 // v8i16 shuffles - Prefer shuffles in the following order:
5383 // 1. [all]   pshuflw, pshufhw, optional move
5384 // 2. [ssse3] 1 x pshufb
5385 // 3. [ssse3] 2 x pshufb + 1 x por
5386 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5387 SDValue
5388 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5389                                             SelectionDAG &DAG) const {
5390   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5391   SDValue V1 = SVOp->getOperand(0);
5392   SDValue V2 = SVOp->getOperand(1);
5393   DebugLoc dl = SVOp->getDebugLoc();
5394   SmallVector<int, 8> MaskVals;
5395
5396   // Determine if more than 1 of the words in each of the low and high quadwords
5397   // of the result come from the same quadword of one of the two inputs.  Undef
5398   // mask values count as coming from any quadword, for better codegen.
5399   SmallVector<unsigned, 4> LoQuad(4);
5400   SmallVector<unsigned, 4> HiQuad(4);
5401   BitVector InputQuads(4);
5402   for (unsigned i = 0; i < 8; ++i) {
5403     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5404     int EltIdx = SVOp->getMaskElt(i);
5405     MaskVals.push_back(EltIdx);
5406     if (EltIdx < 0) {
5407       ++Quad[0];
5408       ++Quad[1];
5409       ++Quad[2];
5410       ++Quad[3];
5411       continue;
5412     }
5413     ++Quad[EltIdx / 4];
5414     InputQuads.set(EltIdx / 4);
5415   }
5416
5417   int BestLoQuad = -1;
5418   unsigned MaxQuad = 1;
5419   for (unsigned i = 0; i < 4; ++i) {
5420     if (LoQuad[i] > MaxQuad) {
5421       BestLoQuad = i;
5422       MaxQuad = LoQuad[i];
5423     }
5424   }
5425
5426   int BestHiQuad = -1;
5427   MaxQuad = 1;
5428   for (unsigned i = 0; i < 4; ++i) {
5429     if (HiQuad[i] > MaxQuad) {
5430       BestHiQuad = i;
5431       MaxQuad = HiQuad[i];
5432     }
5433   }
5434
5435   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5436   // of the two input vectors, shuffle them into one input vector so only a
5437   // single pshufb instruction is necessary. If There are more than 2 input
5438   // quads, disable the next transformation since it does not help SSSE3.
5439   bool V1Used = InputQuads[0] || InputQuads[1];
5440   bool V2Used = InputQuads[2] || InputQuads[3];
5441   if (Subtarget->hasSSSE3()) {
5442     if (InputQuads.count() == 2 && V1Used && V2Used) {
5443       BestLoQuad = InputQuads.find_first();
5444       BestHiQuad = InputQuads.find_next(BestLoQuad);
5445     }
5446     if (InputQuads.count() > 2) {
5447       BestLoQuad = -1;
5448       BestHiQuad = -1;
5449     }
5450   }
5451
5452   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5453   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5454   // words from all 4 input quadwords.
5455   SDValue NewV;
5456   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5457     SmallVector<int, 8> MaskV;
5458     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5459     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5460     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5461                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5462                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5463     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5464
5465     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5466     // source words for the shuffle, to aid later transformations.
5467     bool AllWordsInNewV = true;
5468     bool InOrder[2] = { true, true };
5469     for (unsigned i = 0; i != 8; ++i) {
5470       int idx = MaskVals[i];
5471       if (idx != (int)i)
5472         InOrder[i/4] = false;
5473       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5474         continue;
5475       AllWordsInNewV = false;
5476       break;
5477     }
5478
5479     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5480     if (AllWordsInNewV) {
5481       for (int i = 0; i != 8; ++i) {
5482         int idx = MaskVals[i];
5483         if (idx < 0)
5484           continue;
5485         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5486         if ((idx != i) && idx < 4)
5487           pshufhw = false;
5488         if ((idx != i) && idx > 3)
5489           pshuflw = false;
5490       }
5491       V1 = NewV;
5492       V2Used = false;
5493       BestLoQuad = 0;
5494       BestHiQuad = 1;
5495     }
5496
5497     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5498     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5499     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5500       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5501       unsigned TargetMask = 0;
5502       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5503                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5504       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5505                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5506       V1 = NewV.getOperand(0);
5507       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5508     }
5509   }
5510
5511   // If we have SSSE3, and all words of the result are from 1 input vector,
5512   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5513   // is present, fall back to case 4.
5514   if (Subtarget->hasSSSE3()) {
5515     SmallVector<SDValue,16> pshufbMask;
5516
5517     // If we have elements from both input vectors, set the high bit of the
5518     // shuffle mask element to zero out elements that come from V2 in the V1
5519     // mask, and elements that come from V1 in the V2 mask, so that the two
5520     // results can be OR'd together.
5521     bool TwoInputs = V1Used && V2Used;
5522     for (unsigned i = 0; i != 8; ++i) {
5523       int EltIdx = MaskVals[i] * 2;
5524       if (TwoInputs && (EltIdx >= 16)) {
5525         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5526         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5527         continue;
5528       }
5529       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5530       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5531     }
5532     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5533     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5534                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5535                                  MVT::v16i8, &pshufbMask[0], 16));
5536     if (!TwoInputs)
5537       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5538
5539     // Calculate the shuffle mask for the second input, shuffle it, and
5540     // OR it with the first shuffled input.
5541     pshufbMask.clear();
5542     for (unsigned i = 0; i != 8; ++i) {
5543       int EltIdx = MaskVals[i] * 2;
5544       if (EltIdx < 16) {
5545         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5546         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5547         continue;
5548       }
5549       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5550       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5551     }
5552     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5553     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5554                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5555                                  MVT::v16i8, &pshufbMask[0], 16));
5556     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5557     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5558   }
5559
5560   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5561   // and update MaskVals with new element order.
5562   BitVector InOrder(8);
5563   if (BestLoQuad >= 0) {
5564     SmallVector<int, 8> MaskV;
5565     for (int i = 0; i != 4; ++i) {
5566       int idx = MaskVals[i];
5567       if (idx < 0) {
5568         MaskV.push_back(-1);
5569         InOrder.set(i);
5570       } else if ((idx / 4) == BestLoQuad) {
5571         MaskV.push_back(idx & 3);
5572         InOrder.set(i);
5573       } else {
5574         MaskV.push_back(-1);
5575       }
5576     }
5577     for (unsigned i = 4; i != 8; ++i)
5578       MaskV.push_back(i);
5579     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5580                                 &MaskV[0]);
5581
5582     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5583       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5584                                NewV.getOperand(0),
5585                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5586                                DAG);
5587   }
5588
5589   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5590   // and update MaskVals with the new element order.
5591   if (BestHiQuad >= 0) {
5592     SmallVector<int, 8> MaskV;
5593     for (unsigned i = 0; i != 4; ++i)
5594       MaskV.push_back(i);
5595     for (unsigned i = 4; i != 8; ++i) {
5596       int idx = MaskVals[i];
5597       if (idx < 0) {
5598         MaskV.push_back(-1);
5599         InOrder.set(i);
5600       } else if ((idx / 4) == BestHiQuad) {
5601         MaskV.push_back((idx & 3) + 4);
5602         InOrder.set(i);
5603       } else {
5604         MaskV.push_back(-1);
5605       }
5606     }
5607     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5608                                 &MaskV[0]);
5609
5610     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5611       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5612                               NewV.getOperand(0),
5613                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5614                               DAG);
5615   }
5616
5617   // In case BestHi & BestLo were both -1, which means each quadword has a word
5618   // from each of the four input quadwords, calculate the InOrder bitvector now
5619   // before falling through to the insert/extract cleanup.
5620   if (BestLoQuad == -1 && BestHiQuad == -1) {
5621     NewV = V1;
5622     for (int i = 0; i != 8; ++i)
5623       if (MaskVals[i] < 0 || MaskVals[i] == i)
5624         InOrder.set(i);
5625   }
5626
5627   // The other elements are put in the right place using pextrw and pinsrw.
5628   for (unsigned i = 0; i != 8; ++i) {
5629     if (InOrder[i])
5630       continue;
5631     int EltIdx = MaskVals[i];
5632     if (EltIdx < 0)
5633       continue;
5634     SDValue ExtOp = (EltIdx < 8)
5635     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5636                   DAG.getIntPtrConstant(EltIdx))
5637     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5638                   DAG.getIntPtrConstant(EltIdx - 8));
5639     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5640                        DAG.getIntPtrConstant(i));
5641   }
5642   return NewV;
5643 }
5644
5645 // v16i8 shuffles - Prefer shuffles in the following order:
5646 // 1. [ssse3] 1 x pshufb
5647 // 2. [ssse3] 2 x pshufb + 1 x por
5648 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5649 static
5650 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5651                                  SelectionDAG &DAG,
5652                                  const X86TargetLowering &TLI) {
5653   SDValue V1 = SVOp->getOperand(0);
5654   SDValue V2 = SVOp->getOperand(1);
5655   DebugLoc dl = SVOp->getDebugLoc();
5656   SmallVector<int, 16> MaskVals;
5657   SVOp->getMask(MaskVals);
5658
5659   // If we have SSSE3, case 1 is generated when all result bytes come from
5660   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5661   // present, fall back to case 3.
5662   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5663   bool V1Only = true;
5664   bool V2Only = true;
5665   for (unsigned i = 0; i < 16; ++i) {
5666     int EltIdx = MaskVals[i];
5667     if (EltIdx < 0)
5668       continue;
5669     if (EltIdx < 16)
5670       V2Only = false;
5671     else
5672       V1Only = false;
5673   }
5674
5675   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5676   if (TLI.getSubtarget()->hasSSSE3()) {
5677     SmallVector<SDValue,16> pshufbMask;
5678
5679     // If all result elements are from one input vector, then only translate
5680     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5681     //
5682     // Otherwise, we have elements from both input vectors, and must zero out
5683     // elements that come from V2 in the first mask, and V1 in the second mask
5684     // so that we can OR them together.
5685     bool TwoInputs = !(V1Only || V2Only);
5686     for (unsigned i = 0; i != 16; ++i) {
5687       int EltIdx = MaskVals[i];
5688       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5689         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5690         continue;
5691       }
5692       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5693     }
5694     // If all the elements are from V2, assign it to V1 and return after
5695     // building the first pshufb.
5696     if (V2Only)
5697       V1 = V2;
5698     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5699                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5700                                  MVT::v16i8, &pshufbMask[0], 16));
5701     if (!TwoInputs)
5702       return V1;
5703
5704     // Calculate the shuffle mask for the second input, shuffle it, and
5705     // OR it with the first shuffled input.
5706     pshufbMask.clear();
5707     for (unsigned i = 0; i != 16; ++i) {
5708       int EltIdx = MaskVals[i];
5709       if (EltIdx < 16) {
5710         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5711         continue;
5712       }
5713       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5714     }
5715     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5716                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5717                                  MVT::v16i8, &pshufbMask[0], 16));
5718     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5719   }
5720
5721   // No SSSE3 - Calculate in place words and then fix all out of place words
5722   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5723   // the 16 different words that comprise the two doublequadword input vectors.
5724   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5725   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5726   SDValue NewV = V2Only ? V2 : V1;
5727   for (int i = 0; i != 8; ++i) {
5728     int Elt0 = MaskVals[i*2];
5729     int Elt1 = MaskVals[i*2+1];
5730
5731     // This word of the result is all undef, skip it.
5732     if (Elt0 < 0 && Elt1 < 0)
5733       continue;
5734
5735     // This word of the result is already in the correct place, skip it.
5736     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5737       continue;
5738     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5739       continue;
5740
5741     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5742     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5743     SDValue InsElt;
5744
5745     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5746     // using a single extract together, load it and store it.
5747     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5748       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5749                            DAG.getIntPtrConstant(Elt1 / 2));
5750       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5751                         DAG.getIntPtrConstant(i));
5752       continue;
5753     }
5754
5755     // If Elt1 is defined, extract it from the appropriate source.  If the
5756     // source byte is not also odd, shift the extracted word left 8 bits
5757     // otherwise clear the bottom 8 bits if we need to do an or.
5758     if (Elt1 >= 0) {
5759       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5760                            DAG.getIntPtrConstant(Elt1 / 2));
5761       if ((Elt1 & 1) == 0)
5762         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5763                              DAG.getConstant(8,
5764                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5765       else if (Elt0 >= 0)
5766         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5767                              DAG.getConstant(0xFF00, MVT::i16));
5768     }
5769     // If Elt0 is defined, extract it from the appropriate source.  If the
5770     // source byte is not also even, shift the extracted word right 8 bits. If
5771     // Elt1 was also defined, OR the extracted values together before
5772     // inserting them in the result.
5773     if (Elt0 >= 0) {
5774       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5775                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5776       if ((Elt0 & 1) != 0)
5777         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5778                               DAG.getConstant(8,
5779                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5780       else if (Elt1 >= 0)
5781         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5782                              DAG.getConstant(0x00FF, MVT::i16));
5783       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5784                          : InsElt0;
5785     }
5786     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5787                        DAG.getIntPtrConstant(i));
5788   }
5789   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5790 }
5791
5792 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5793 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5794 /// done when every pair / quad of shuffle mask elements point to elements in
5795 /// the right sequence. e.g.
5796 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5797 static
5798 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5799                                  SelectionDAG &DAG, DebugLoc dl) {
5800   EVT VT = SVOp->getValueType(0);
5801   SDValue V1 = SVOp->getOperand(0);
5802   SDValue V2 = SVOp->getOperand(1);
5803   unsigned NumElems = VT.getVectorNumElements();
5804   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5805   EVT NewVT;
5806   switch (VT.getSimpleVT().SimpleTy) {
5807   default: assert(false && "Unexpected!");
5808   case MVT::v4f32: NewVT = MVT::v2f64; break;
5809   case MVT::v4i32: NewVT = MVT::v2i64; break;
5810   case MVT::v8i16: NewVT = MVT::v4i32; break;
5811   case MVT::v16i8: NewVT = MVT::v4i32; break;
5812   }
5813
5814   int Scale = NumElems / NewWidth;
5815   SmallVector<int, 8> MaskVec;
5816   for (unsigned i = 0; i < NumElems; i += Scale) {
5817     int StartIdx = -1;
5818     for (int j = 0; j < Scale; ++j) {
5819       int EltIdx = SVOp->getMaskElt(i+j);
5820       if (EltIdx < 0)
5821         continue;
5822       if (StartIdx == -1)
5823         StartIdx = EltIdx - (EltIdx % Scale);
5824       if (EltIdx != StartIdx + j)
5825         return SDValue();
5826     }
5827     if (StartIdx == -1)
5828       MaskVec.push_back(-1);
5829     else
5830       MaskVec.push_back(StartIdx / Scale);
5831   }
5832
5833   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5834   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5835   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5836 }
5837
5838 /// getVZextMovL - Return a zero-extending vector move low node.
5839 ///
5840 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5841                             SDValue SrcOp, SelectionDAG &DAG,
5842                             const X86Subtarget *Subtarget, DebugLoc dl) {
5843   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5844     LoadSDNode *LD = NULL;
5845     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5846       LD = dyn_cast<LoadSDNode>(SrcOp);
5847     if (!LD) {
5848       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5849       // instead.
5850       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5851       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5852           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5853           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5854           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5855         // PR2108
5856         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5857         return DAG.getNode(ISD::BITCAST, dl, VT,
5858                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5859                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5860                                                    OpVT,
5861                                                    SrcOp.getOperand(0)
5862                                                           .getOperand(0))));
5863       }
5864     }
5865   }
5866
5867   return DAG.getNode(ISD::BITCAST, dl, VT,
5868                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5869                                  DAG.getNode(ISD::BITCAST, dl,
5870                                              OpVT, SrcOp)));
5871 }
5872
5873 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5874 /// shuffle node referes to only one lane in the sources.
5875 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5876   EVT VT = SVOp->getValueType(0);
5877   int NumElems = VT.getVectorNumElements();
5878   int HalfSize = NumElems/2;
5879   SmallVector<int, 16> M;
5880   SVOp->getMask(M);
5881   bool MatchA = false, MatchB = false;
5882
5883   for (int l = 0; l < NumElems*2; l += HalfSize) {
5884     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5885       MatchA = true;
5886       break;
5887     }
5888   }
5889
5890   for (int l = 0; l < NumElems*2; l += HalfSize) {
5891     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5892       MatchB = true;
5893       break;
5894     }
5895   }
5896
5897   return MatchA && MatchB;
5898 }
5899
5900 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5901 /// which could not be matched by any known target speficic shuffle
5902 static SDValue
5903 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5904   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5905     // If each half of a vector shuffle node referes to only one lane in the
5906     // source vectors, extract each used 128-bit lane and shuffle them using
5907     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5908     // the work to the legalizer.
5909     DebugLoc dl = SVOp->getDebugLoc();
5910     EVT VT = SVOp->getValueType(0);
5911     int NumElems = VT.getVectorNumElements();
5912     int HalfSize = NumElems/2;
5913
5914     // Extract the reference for each half
5915     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5916     int FstVecOpNum = 0, SndVecOpNum = 0;
5917     for (int i = 0; i < HalfSize; ++i) {
5918       int Elt = SVOp->getMaskElt(i);
5919       if (SVOp->getMaskElt(i) < 0)
5920         continue;
5921       FstVecOpNum = Elt/NumElems;
5922       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5923       break;
5924     }
5925     for (int i = HalfSize; i < NumElems; ++i) {
5926       int Elt = SVOp->getMaskElt(i);
5927       if (SVOp->getMaskElt(i) < 0)
5928         continue;
5929       SndVecOpNum = Elt/NumElems;
5930       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5931       break;
5932     }
5933
5934     // Extract the subvectors
5935     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5936                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5937     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5938                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5939
5940     // Generate 128-bit shuffles
5941     SmallVector<int, 16> MaskV1, MaskV2;
5942     for (int i = 0; i < HalfSize; ++i) {
5943       int Elt = SVOp->getMaskElt(i);
5944       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5945     }
5946     for (int i = HalfSize; i < NumElems; ++i) {
5947       int Elt = SVOp->getMaskElt(i);
5948       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5949     }
5950
5951     EVT NVT = V1.getValueType();
5952     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5953     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5954
5955     // Concatenate the result back
5956     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5957                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5958     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5959                               DAG, dl);
5960   }
5961
5962   return SDValue();
5963 }
5964
5965 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5966 /// 4 elements, and match them with several different shuffle types.
5967 static SDValue
5968 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5969   SDValue V1 = SVOp->getOperand(0);
5970   SDValue V2 = SVOp->getOperand(1);
5971   DebugLoc dl = SVOp->getDebugLoc();
5972   EVT VT = SVOp->getValueType(0);
5973
5974   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5975
5976   SmallVector<std::pair<int, int>, 8> Locs;
5977   Locs.resize(4);
5978   SmallVector<int, 8> Mask1(4U, -1);
5979   SmallVector<int, 8> PermMask;
5980   SVOp->getMask(PermMask);
5981
5982   unsigned NumHi = 0;
5983   unsigned NumLo = 0;
5984   for (unsigned i = 0; i != 4; ++i) {
5985     int Idx = PermMask[i];
5986     if (Idx < 0) {
5987       Locs[i] = std::make_pair(-1, -1);
5988     } else {
5989       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5990       if (Idx < 4) {
5991         Locs[i] = std::make_pair(0, NumLo);
5992         Mask1[NumLo] = Idx;
5993         NumLo++;
5994       } else {
5995         Locs[i] = std::make_pair(1, NumHi);
5996         if (2+NumHi < 4)
5997           Mask1[2+NumHi] = Idx;
5998         NumHi++;
5999       }
6000     }
6001   }
6002
6003   if (NumLo <= 2 && NumHi <= 2) {
6004     // If no more than two elements come from either vector. This can be
6005     // implemented with two shuffles. First shuffle gather the elements.
6006     // The second shuffle, which takes the first shuffle as both of its
6007     // vector operands, put the elements into the right order.
6008     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6009
6010     SmallVector<int, 8> Mask2(4U, -1);
6011
6012     for (unsigned i = 0; i != 4; ++i) {
6013       if (Locs[i].first == -1)
6014         continue;
6015       else {
6016         unsigned Idx = (i < 2) ? 0 : 4;
6017         Idx += Locs[i].first * 2 + Locs[i].second;
6018         Mask2[i] = Idx;
6019       }
6020     }
6021
6022     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6023   } else if (NumLo == 3 || NumHi == 3) {
6024     // Otherwise, we must have three elements from one vector, call it X, and
6025     // one element from the other, call it Y.  First, use a shufps to build an
6026     // intermediate vector with the one element from Y and the element from X
6027     // that will be in the same half in the final destination (the indexes don't
6028     // matter). Then, use a shufps to build the final vector, taking the half
6029     // containing the element from Y from the intermediate, and the other half
6030     // from X.
6031     if (NumHi == 3) {
6032       // Normalize it so the 3 elements come from V1.
6033       CommuteVectorShuffleMask(PermMask, VT);
6034       std::swap(V1, V2);
6035     }
6036
6037     // Find the element from V2.
6038     unsigned HiIndex;
6039     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6040       int Val = PermMask[HiIndex];
6041       if (Val < 0)
6042         continue;
6043       if (Val >= 4)
6044         break;
6045     }
6046
6047     Mask1[0] = PermMask[HiIndex];
6048     Mask1[1] = -1;
6049     Mask1[2] = PermMask[HiIndex^1];
6050     Mask1[3] = -1;
6051     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6052
6053     if (HiIndex >= 2) {
6054       Mask1[0] = PermMask[0];
6055       Mask1[1] = PermMask[1];
6056       Mask1[2] = HiIndex & 1 ? 6 : 4;
6057       Mask1[3] = HiIndex & 1 ? 4 : 6;
6058       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6059     } else {
6060       Mask1[0] = HiIndex & 1 ? 2 : 0;
6061       Mask1[1] = HiIndex & 1 ? 0 : 2;
6062       Mask1[2] = PermMask[2];
6063       Mask1[3] = PermMask[3];
6064       if (Mask1[2] >= 0)
6065         Mask1[2] += 4;
6066       if (Mask1[3] >= 0)
6067         Mask1[3] += 4;
6068       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6069     }
6070   }
6071
6072   // Break it into (shuffle shuffle_hi, shuffle_lo).
6073   Locs.clear();
6074   Locs.resize(4);
6075   SmallVector<int,8> LoMask(4U, -1);
6076   SmallVector<int,8> HiMask(4U, -1);
6077
6078   SmallVector<int,8> *MaskPtr = &LoMask;
6079   unsigned MaskIdx = 0;
6080   unsigned LoIdx = 0;
6081   unsigned HiIdx = 2;
6082   for (unsigned i = 0; i != 4; ++i) {
6083     if (i == 2) {
6084       MaskPtr = &HiMask;
6085       MaskIdx = 1;
6086       LoIdx = 0;
6087       HiIdx = 2;
6088     }
6089     int Idx = PermMask[i];
6090     if (Idx < 0) {
6091       Locs[i] = std::make_pair(-1, -1);
6092     } else if (Idx < 4) {
6093       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6094       (*MaskPtr)[LoIdx] = Idx;
6095       LoIdx++;
6096     } else {
6097       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6098       (*MaskPtr)[HiIdx] = Idx;
6099       HiIdx++;
6100     }
6101   }
6102
6103   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6104   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6105   SmallVector<int, 8> MaskOps;
6106   for (unsigned i = 0; i != 4; ++i) {
6107     if (Locs[i].first == -1) {
6108       MaskOps.push_back(-1);
6109     } else {
6110       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6111       MaskOps.push_back(Idx);
6112     }
6113   }
6114   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6115 }
6116
6117 static bool MayFoldVectorLoad(SDValue V) {
6118   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6119     V = V.getOperand(0);
6120   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6121     V = V.getOperand(0);
6122   if (MayFoldLoad(V))
6123     return true;
6124   return false;
6125 }
6126
6127 // FIXME: the version above should always be used. Since there's
6128 // a bug where several vector shuffles can't be folded because the
6129 // DAG is not updated during lowering and a node claims to have two
6130 // uses while it only has one, use this version, and let isel match
6131 // another instruction if the load really happens to have more than
6132 // one use. Remove this version after this bug get fixed.
6133 // rdar://8434668, PR8156
6134 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6135   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6136     V = V.getOperand(0);
6137   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6138     V = V.getOperand(0);
6139   if (ISD::isNormalLoad(V.getNode()))
6140     return true;
6141   return false;
6142 }
6143
6144 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6145 /// a vector extract, and if both can be later optimized into a single load.
6146 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6147 /// here because otherwise a target specific shuffle node is going to be
6148 /// emitted for this shuffle, and the optimization not done.
6149 /// FIXME: This is probably not the best approach, but fix the problem
6150 /// until the right path is decided.
6151 static
6152 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6153                                          const TargetLowering &TLI) {
6154   EVT VT = V.getValueType();
6155   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6156
6157   // Be sure that the vector shuffle is present in a pattern like this:
6158   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6159   if (!V.hasOneUse())
6160     return false;
6161
6162   SDNode *N = *V.getNode()->use_begin();
6163   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6164     return false;
6165
6166   SDValue EltNo = N->getOperand(1);
6167   if (!isa<ConstantSDNode>(EltNo))
6168     return false;
6169
6170   // If the bit convert changed the number of elements, it is unsafe
6171   // to examine the mask.
6172   bool HasShuffleIntoBitcast = false;
6173   if (V.getOpcode() == ISD::BITCAST) {
6174     EVT SrcVT = V.getOperand(0).getValueType();
6175     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6176       return false;
6177     V = V.getOperand(0);
6178     HasShuffleIntoBitcast = true;
6179   }
6180
6181   // Select the input vector, guarding against out of range extract vector.
6182   unsigned NumElems = VT.getVectorNumElements();
6183   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6184   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6185   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6186
6187   // Skip one more bit_convert if necessary
6188   if (V.getOpcode() == ISD::BITCAST)
6189     V = V.getOperand(0);
6190
6191   if (ISD::isNormalLoad(V.getNode())) {
6192     // Is the original load suitable?
6193     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6194
6195     // FIXME: avoid the multi-use bug that is preventing lots of
6196     // of foldings to be detected, this is still wrong of course, but
6197     // give the temporary desired behavior, and if it happens that
6198     // the load has real more uses, during isel it will not fold, and
6199     // will generate poor code.
6200     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6201       return false;
6202
6203     if (!HasShuffleIntoBitcast)
6204       return true;
6205
6206     // If there's a bitcast before the shuffle, check if the load type and
6207     // alignment is valid.
6208     unsigned Align = LN0->getAlignment();
6209     unsigned NewAlign =
6210       TLI.getTargetData()->getABITypeAlignment(
6211                                     VT.getTypeForEVT(*DAG.getContext()));
6212
6213     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6214       return false;
6215   }
6216
6217   return true;
6218 }
6219
6220 static
6221 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6222   EVT VT = Op.getValueType();
6223
6224   // Canonizalize to v2f64.
6225   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6226   return DAG.getNode(ISD::BITCAST, dl, VT,
6227                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6228                                           V1, DAG));
6229 }
6230
6231 static
6232 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6233                         bool HasSSE2) {
6234   SDValue V1 = Op.getOperand(0);
6235   SDValue V2 = Op.getOperand(1);
6236   EVT VT = Op.getValueType();
6237
6238   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6239
6240   if (HasSSE2 && VT == MVT::v2f64)
6241     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6242
6243   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6244   return DAG.getNode(ISD::BITCAST, dl, VT,
6245                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6246                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6247                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6248 }
6249
6250 static
6251 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6252   SDValue V1 = Op.getOperand(0);
6253   SDValue V2 = Op.getOperand(1);
6254   EVT VT = Op.getValueType();
6255
6256   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6257          "unsupported shuffle type");
6258
6259   if (V2.getOpcode() == ISD::UNDEF)
6260     V2 = V1;
6261
6262   // v4i32 or v4f32
6263   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6264 }
6265
6266 static inline unsigned getSHUFPOpcode(EVT VT) {
6267   switch(VT.getSimpleVT().SimpleTy) {
6268   case MVT::v8i32: // Use fp unit for int unpack.
6269   case MVT::v8f32:
6270   case MVT::v4i32: // Use fp unit for int unpack.
6271   case MVT::v4f32: return X86ISD::SHUFPS;
6272   case MVT::v4i64: // Use fp unit for int unpack.
6273   case MVT::v4f64:
6274   case MVT::v2i64: // Use fp unit for int unpack.
6275   case MVT::v2f64: return X86ISD::SHUFPD;
6276   default:
6277     llvm_unreachable("Unknown type for shufp*");
6278   }
6279   return 0;
6280 }
6281
6282 static
6283 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6284   SDValue V1 = Op.getOperand(0);
6285   SDValue V2 = Op.getOperand(1);
6286   EVT VT = Op.getValueType();
6287   unsigned NumElems = VT.getVectorNumElements();
6288
6289   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6290   // operand of these instructions is only memory, so check if there's a
6291   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6292   // same masks.
6293   bool CanFoldLoad = false;
6294
6295   // Trivial case, when V2 comes from a load.
6296   if (MayFoldVectorLoad(V2))
6297     CanFoldLoad = true;
6298
6299   // When V1 is a load, it can be folded later into a store in isel, example:
6300   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6301   //    turns into:
6302   //  (MOVLPSmr addr:$src1, VR128:$src2)
6303   // So, recognize this potential and also use MOVLPS or MOVLPD
6304   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6305     CanFoldLoad = true;
6306
6307   // Both of them can't be memory operations though.
6308   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6309     CanFoldLoad = false;
6310
6311   if (CanFoldLoad) {
6312     if (HasSSE2 && NumElems == 2)
6313       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6314
6315     if (NumElems == 4)
6316       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6317   }
6318
6319   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6320   // movl and movlp will both match v2i64, but v2i64 is never matched by
6321   // movl earlier because we make it strict to avoid messing with the movlp load
6322   // folding logic (see the code above getMOVLP call). Match it here then,
6323   // this is horrible, but will stay like this until we move all shuffle
6324   // matching to x86 specific nodes. Note that for the 1st condition all
6325   // types are matched with movsd.
6326   if (HasSSE2) {
6327     if (NumElems == 2)
6328       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6329     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6330   }
6331
6332   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6333
6334   // Invert the operand order and use SHUFPS to match it.
6335   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6336                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6337 }
6338
6339 static inline unsigned getUNPCKLOpcode(EVT VT) {
6340   switch(VT.getSimpleVT().SimpleTy) {
6341   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6342   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6343   case MVT::v4f32: return X86ISD::UNPCKLPS;
6344   case MVT::v2f64: return X86ISD::UNPCKLPD;
6345   case MVT::v8i32: // Use fp unit for int unpack.
6346   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6347   case MVT::v4i64: // Use fp unit for int unpack.
6348   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6349   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6350   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6351   default:
6352     llvm_unreachable("Unknown type for unpckl");
6353   }
6354   return 0;
6355 }
6356
6357 static inline unsigned getUNPCKHOpcode(EVT VT) {
6358   switch(VT.getSimpleVT().SimpleTy) {
6359   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6360   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6361   case MVT::v4f32: return X86ISD::UNPCKHPS;
6362   case MVT::v2f64: return X86ISD::UNPCKHPD;
6363   case MVT::v8i32: // Use fp unit for int unpack.
6364   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6365   case MVT::v4i64: // Use fp unit for int unpack.
6366   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6367   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6368   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6369   default:
6370     llvm_unreachable("Unknown type for unpckh");
6371   }
6372   return 0;
6373 }
6374
6375 static inline unsigned getVPERMILOpcode(EVT VT) {
6376   switch(VT.getSimpleVT().SimpleTy) {
6377   case MVT::v4i32:
6378   case MVT::v4f32: return X86ISD::VPERMILPS;
6379   case MVT::v2i64:
6380   case MVT::v2f64: return X86ISD::VPERMILPD;
6381   case MVT::v8i32:
6382   case MVT::v8f32: return X86ISD::VPERMILPSY;
6383   case MVT::v4i64:
6384   case MVT::v4f64: return X86ISD::VPERMILPDY;
6385   default:
6386     llvm_unreachable("Unknown type for vpermil");
6387   }
6388   return 0;
6389 }
6390
6391 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6392 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6393 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6394 static bool isVectorBroadcast(SDValue &Op) {
6395   EVT VT = Op.getValueType();
6396   bool Is256 = VT.getSizeInBits() == 256;
6397
6398   assert((VT.getSizeInBits() == 128 || Is256) &&
6399          "Unsupported type for vbroadcast node");
6400
6401   SDValue V = Op;
6402   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6403     V = V.getOperand(0);
6404
6405   if (Is256 && !(V.hasOneUse() &&
6406                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6407                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6408     return false;
6409
6410   if (Is256)
6411     V = V.getOperand(1);
6412   if (V.hasOneUse() && V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6413     return false;
6414
6415   // Check the source scalar_to_vector type. 256-bit broadcasts are
6416   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6417   // for 32-bit scalars.
6418   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6419   if (ScalarSize != 32 && ScalarSize != 64)
6420     return false;
6421   if (!Is256 && ScalarSize == 64)
6422     return false;
6423
6424   V = V.getOperand(0);
6425   if (!MayFoldLoad(V))
6426     return false;
6427
6428   // Return the load node
6429   Op = V;
6430   return true;
6431 }
6432
6433 static
6434 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6435                                const TargetLowering &TLI,
6436                                const X86Subtarget *Subtarget) {
6437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6438   EVT VT = Op.getValueType();
6439   DebugLoc dl = Op.getDebugLoc();
6440   SDValue V1 = Op.getOperand(0);
6441   SDValue V2 = Op.getOperand(1);
6442
6443   if (isZeroShuffle(SVOp))
6444     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6445
6446   // Handle splat operations
6447   if (SVOp->isSplat()) {
6448     unsigned NumElem = VT.getVectorNumElements();
6449     int Size = VT.getSizeInBits();
6450     // Special case, this is the only place now where it's allowed to return
6451     // a vector_shuffle operation without using a target specific node, because
6452     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6453     // this be moved to DAGCombine instead?
6454     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6455       return Op;
6456
6457     // Use vbroadcast whenever the splat comes from a foldable load
6458     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6459       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6460
6461     // Handle splats by matching through known shuffle masks
6462     if ((Size == 128 && NumElem <= 4) ||
6463         (Size == 256 && NumElem < 8))
6464       return SDValue();
6465
6466     // All remaning splats are promoted to target supported vector shuffles.
6467     return PromoteSplat(SVOp, DAG);
6468   }
6469
6470   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6471   // do it!
6472   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6473     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6474     if (NewOp.getNode())
6475       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6476   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6477     // FIXME: Figure out a cleaner way to do this.
6478     // Try to make use of movq to zero out the top part.
6479     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6480       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6481       if (NewOp.getNode()) {
6482         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6483           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6484                               DAG, Subtarget, dl);
6485       }
6486     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6487       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6488       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6489         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6490                             DAG, Subtarget, dl);
6491     }
6492   }
6493   return SDValue();
6494 }
6495
6496 SDValue
6497 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6498   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6499   SDValue V1 = Op.getOperand(0);
6500   SDValue V2 = Op.getOperand(1);
6501   EVT VT = Op.getValueType();
6502   DebugLoc dl = Op.getDebugLoc();
6503   unsigned NumElems = VT.getVectorNumElements();
6504   bool isMMX = VT.getSizeInBits() == 64;
6505   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6506   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6507   bool V1IsSplat = false;
6508   bool V2IsSplat = false;
6509   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6510   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6511   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6512   MachineFunction &MF = DAG.getMachineFunction();
6513   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6514
6515   // Shuffle operations on MMX not supported.
6516   if (isMMX)
6517     return Op;
6518
6519   // Vector shuffle lowering takes 3 steps:
6520   //
6521   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6522   //    narrowing and commutation of operands should be handled.
6523   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6524   //    shuffle nodes.
6525   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6526   //    so the shuffle can be broken into other shuffles and the legalizer can
6527   //    try the lowering again.
6528   //
6529   // The general ideia is that no vector_shuffle operation should be left to
6530   // be matched during isel, all of them must be converted to a target specific
6531   // node here.
6532
6533   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6534   // narrowing and commutation of operands should be handled. The actual code
6535   // doesn't include all of those, work in progress...
6536   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6537   if (NewOp.getNode())
6538     return NewOp;
6539
6540   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6541   // unpckh_undef). Only use pshufd if speed is more important than size.
6542   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6543     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6544   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6545     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6546
6547   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6548       RelaxedMayFoldVectorLoad(V1))
6549     return getMOVDDup(Op, dl, V1, DAG);
6550
6551   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6552     return getMOVHighToLow(Op, dl, DAG);
6553
6554   // Use to match splats
6555   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6556       (VT == MVT::v2f64 || VT == MVT::v2i64))
6557     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6558
6559   if (X86::isPSHUFDMask(SVOp)) {
6560     // The actual implementation will match the mask in the if above and then
6561     // during isel it can match several different instructions, not only pshufd
6562     // as its name says, sad but true, emulate the behavior for now...
6563     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6564         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6565
6566     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6567
6568     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6569       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6570
6571     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6572                                 TargetMask, DAG);
6573   }
6574
6575   // Check if this can be converted into a logical shift.
6576   bool isLeft = false;
6577   unsigned ShAmt = 0;
6578   SDValue ShVal;
6579   bool isShift = getSubtarget()->hasSSE2() &&
6580     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6581   if (isShift && ShVal.hasOneUse()) {
6582     // If the shifted value has multiple uses, it may be cheaper to use
6583     // v_set0 + movlhps or movhlps, etc.
6584     EVT EltVT = VT.getVectorElementType();
6585     ShAmt *= EltVT.getSizeInBits();
6586     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6587   }
6588
6589   if (X86::isMOVLMask(SVOp)) {
6590     if (V1IsUndef)
6591       return V2;
6592     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6593       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6594     if (!X86::isMOVLPMask(SVOp)) {
6595       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6596         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6597
6598       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6599         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6600     }
6601   }
6602
6603   // FIXME: fold these into legal mask.
6604   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6605     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6606
6607   if (X86::isMOVHLPSMask(SVOp))
6608     return getMOVHighToLow(Op, dl, DAG);
6609
6610   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6611     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6612
6613   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6614     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6615
6616   if (X86::isMOVLPMask(SVOp))
6617     return getMOVLP(Op, dl, DAG, HasSSE2);
6618
6619   if (ShouldXformToMOVHLPS(SVOp) ||
6620       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6621     return CommuteVectorShuffle(SVOp, DAG);
6622
6623   if (isShift) {
6624     // No better options. Use a vshl / vsrl.
6625     EVT EltVT = VT.getVectorElementType();
6626     ShAmt *= EltVT.getSizeInBits();
6627     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6628   }
6629
6630   bool Commuted = false;
6631   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6632   // 1,1,1,1 -> v8i16 though.
6633   V1IsSplat = isSplatVector(V1.getNode());
6634   V2IsSplat = isSplatVector(V2.getNode());
6635
6636   // Canonicalize the splat or undef, if present, to be on the RHS.
6637   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6638     Op = CommuteVectorShuffle(SVOp, DAG);
6639     SVOp = cast<ShuffleVectorSDNode>(Op);
6640     V1 = SVOp->getOperand(0);
6641     V2 = SVOp->getOperand(1);
6642     std::swap(V1IsSplat, V2IsSplat);
6643     std::swap(V1IsUndef, V2IsUndef);
6644     Commuted = true;
6645   }
6646
6647   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6648     // Shuffling low element of v1 into undef, just return v1.
6649     if (V2IsUndef)
6650       return V1;
6651     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6652     // the instruction selector will not match, so get a canonical MOVL with
6653     // swapped operands to undo the commute.
6654     return getMOVL(DAG, dl, VT, V2, V1);
6655   }
6656
6657   if (X86::isUNPCKLMask(SVOp))
6658     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6659
6660   if (X86::isUNPCKHMask(SVOp))
6661     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6662
6663   if (V2IsSplat) {
6664     // Normalize mask so all entries that point to V2 points to its first
6665     // element then try to match unpck{h|l} again. If match, return a
6666     // new vector_shuffle with the corrected mask.
6667     SDValue NewMask = NormalizeMask(SVOp, DAG);
6668     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6669     if (NSVOp != SVOp) {
6670       if (X86::isUNPCKLMask(NSVOp, true)) {
6671         return NewMask;
6672       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6673         return NewMask;
6674       }
6675     }
6676   }
6677
6678   if (Commuted) {
6679     // Commute is back and try unpck* again.
6680     // FIXME: this seems wrong.
6681     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6682     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6683
6684     if (X86::isUNPCKLMask(NewSVOp))
6685       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6686
6687     if (X86::isUNPCKHMask(NewSVOp))
6688       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6689   }
6690
6691   // Normalize the node to match x86 shuffle ops if needed
6692   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6693     return CommuteVectorShuffle(SVOp, DAG);
6694
6695   // The checks below are all present in isShuffleMaskLegal, but they are
6696   // inlined here right now to enable us to directly emit target specific
6697   // nodes, and remove one by one until they don't return Op anymore.
6698   SmallVector<int, 16> M;
6699   SVOp->getMask(M);
6700
6701   if (isPALIGNRMask(M, VT, HasSSSE3))
6702     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6703                                 X86::getShufflePALIGNRImmediate(SVOp),
6704                                 DAG);
6705
6706   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6707       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6708     if (VT == MVT::v2f64)
6709       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6710     if (VT == MVT::v2i64)
6711       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6712   }
6713
6714   if (isPSHUFHWMask(M, VT))
6715     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6716                                 X86::getShufflePSHUFHWImmediate(SVOp),
6717                                 DAG);
6718
6719   if (isPSHUFLWMask(M, VT))
6720     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6721                                 X86::getShufflePSHUFLWImmediate(SVOp),
6722                                 DAG);
6723
6724   if (isSHUFPMask(M, VT))
6725     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6726                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6727
6728   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6729     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6730   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6731     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6732
6733   //===--------------------------------------------------------------------===//
6734   // Generate target specific nodes for 128 or 256-bit shuffles only
6735   // supported in the AVX instruction set.
6736   //
6737
6738   // Handle VMOVDDUPY permutations
6739   if (isMOVDDUPYMask(SVOp, Subtarget))
6740     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6741
6742   // Handle VPERMILPS* permutations
6743   if (isVPERMILPSMask(M, VT, Subtarget))
6744     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6745                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6746
6747   // Handle VPERMILPD* permutations
6748   if (isVPERMILPDMask(M, VT, Subtarget))
6749     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6750                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6751
6752   // Handle VPERM2F128 permutations
6753   if (isVPERM2F128Mask(M, VT, Subtarget))
6754     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6755                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6756
6757   // Handle VSHUFPSY permutations
6758   if (isVSHUFPSYMask(M, VT, Subtarget))
6759     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6760                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6761
6762   // Handle VSHUFPDY permutations
6763   if (isVSHUFPDYMask(M, VT, Subtarget))
6764     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6765                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6766
6767   //===--------------------------------------------------------------------===//
6768   // Since no target specific shuffle was selected for this generic one,
6769   // lower it into other known shuffles. FIXME: this isn't true yet, but
6770   // this is the plan.
6771   //
6772
6773   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6774   if (VT == MVT::v8i16) {
6775     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6776     if (NewOp.getNode())
6777       return NewOp;
6778   }
6779
6780   if (VT == MVT::v16i8) {
6781     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6782     if (NewOp.getNode())
6783       return NewOp;
6784   }
6785
6786   // Handle all 128-bit wide vectors with 4 elements, and match them with
6787   // several different shuffle types.
6788   if (NumElems == 4 && VT.getSizeInBits() == 128)
6789     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6790
6791   // Handle general 256-bit shuffles
6792   if (VT.is256BitVector())
6793     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6794
6795   return SDValue();
6796 }
6797
6798 SDValue
6799 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6800                                                 SelectionDAG &DAG) const {
6801   EVT VT = Op.getValueType();
6802   DebugLoc dl = Op.getDebugLoc();
6803
6804   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6805     return SDValue();
6806
6807   if (VT.getSizeInBits() == 8) {
6808     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6809                                     Op.getOperand(0), Op.getOperand(1));
6810     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6811                                     DAG.getValueType(VT));
6812     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6813   } else if (VT.getSizeInBits() == 16) {
6814     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6815     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6816     if (Idx == 0)
6817       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6818                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6819                                      DAG.getNode(ISD::BITCAST, dl,
6820                                                  MVT::v4i32,
6821                                                  Op.getOperand(0)),
6822                                      Op.getOperand(1)));
6823     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6824                                     Op.getOperand(0), Op.getOperand(1));
6825     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6826                                     DAG.getValueType(VT));
6827     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6828   } else if (VT == MVT::f32) {
6829     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6830     // the result back to FR32 register. It's only worth matching if the
6831     // result has a single use which is a store or a bitcast to i32.  And in
6832     // the case of a store, it's not worth it if the index is a constant 0,
6833     // because a MOVSSmr can be used instead, which is smaller and faster.
6834     if (!Op.hasOneUse())
6835       return SDValue();
6836     SDNode *User = *Op.getNode()->use_begin();
6837     if ((User->getOpcode() != ISD::STORE ||
6838          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6839           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6840         (User->getOpcode() != ISD::BITCAST ||
6841          User->getValueType(0) != MVT::i32))
6842       return SDValue();
6843     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6844                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6845                                               Op.getOperand(0)),
6846                                               Op.getOperand(1));
6847     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6848   } else if (VT == MVT::i32) {
6849     // ExtractPS works with constant index.
6850     if (isa<ConstantSDNode>(Op.getOperand(1)))
6851       return Op;
6852   }
6853   return SDValue();
6854 }
6855
6856
6857 SDValue
6858 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6859                                            SelectionDAG &DAG) const {
6860   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6861     return SDValue();
6862
6863   SDValue Vec = Op.getOperand(0);
6864   EVT VecVT = Vec.getValueType();
6865
6866   // If this is a 256-bit vector result, first extract the 128-bit vector and
6867   // then extract the element from the 128-bit vector.
6868   if (VecVT.getSizeInBits() == 256) {
6869     DebugLoc dl = Op.getNode()->getDebugLoc();
6870     unsigned NumElems = VecVT.getVectorNumElements();
6871     SDValue Idx = Op.getOperand(1);
6872     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6873
6874     // Get the 128-bit vector.
6875     bool Upper = IdxVal >= NumElems/2;
6876     Vec = Extract128BitVector(Vec,
6877                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6878
6879     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6880                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6881   }
6882
6883   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6884
6885   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6886     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6887     if (Res.getNode())
6888       return Res;
6889   }
6890
6891   EVT VT = Op.getValueType();
6892   DebugLoc dl = Op.getDebugLoc();
6893   // TODO: handle v16i8.
6894   if (VT.getSizeInBits() == 16) {
6895     SDValue Vec = Op.getOperand(0);
6896     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6897     if (Idx == 0)
6898       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6899                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6900                                      DAG.getNode(ISD::BITCAST, dl,
6901                                                  MVT::v4i32, Vec),
6902                                      Op.getOperand(1)));
6903     // Transform it so it match pextrw which produces a 32-bit result.
6904     EVT EltVT = MVT::i32;
6905     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6906                                     Op.getOperand(0), Op.getOperand(1));
6907     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6908                                     DAG.getValueType(VT));
6909     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6910   } else if (VT.getSizeInBits() == 32) {
6911     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6912     if (Idx == 0)
6913       return Op;
6914
6915     // SHUFPS the element to the lowest double word, then movss.
6916     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6917     EVT VVT = Op.getOperand(0).getValueType();
6918     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6919                                        DAG.getUNDEF(VVT), Mask);
6920     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6921                        DAG.getIntPtrConstant(0));
6922   } else if (VT.getSizeInBits() == 64) {
6923     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6924     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6925     //        to match extract_elt for f64.
6926     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6927     if (Idx == 0)
6928       return Op;
6929
6930     // UNPCKHPD the element to the lowest double word, then movsd.
6931     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6932     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6933     int Mask[2] = { 1, -1 };
6934     EVT VVT = Op.getOperand(0).getValueType();
6935     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6936                                        DAG.getUNDEF(VVT), Mask);
6937     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6938                        DAG.getIntPtrConstant(0));
6939   }
6940
6941   return SDValue();
6942 }
6943
6944 SDValue
6945 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6946                                                SelectionDAG &DAG) const {
6947   EVT VT = Op.getValueType();
6948   EVT EltVT = VT.getVectorElementType();
6949   DebugLoc dl = Op.getDebugLoc();
6950
6951   SDValue N0 = Op.getOperand(0);
6952   SDValue N1 = Op.getOperand(1);
6953   SDValue N2 = Op.getOperand(2);
6954
6955   if (VT.getSizeInBits() == 256)
6956     return SDValue();
6957
6958   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6959       isa<ConstantSDNode>(N2)) {
6960     unsigned Opc;
6961     if (VT == MVT::v8i16)
6962       Opc = X86ISD::PINSRW;
6963     else if (VT == MVT::v16i8)
6964       Opc = X86ISD::PINSRB;
6965     else
6966       Opc = X86ISD::PINSRB;
6967
6968     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6969     // argument.
6970     if (N1.getValueType() != MVT::i32)
6971       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6972     if (N2.getValueType() != MVT::i32)
6973       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6974     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6975   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6976     // Bits [7:6] of the constant are the source select.  This will always be
6977     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6978     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6979     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6980     // Bits [5:4] of the constant are the destination select.  This is the
6981     //  value of the incoming immediate.
6982     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6983     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6984     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6985     // Create this as a scalar to vector..
6986     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6987     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6988   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6989     // PINSR* works with constant index.
6990     return Op;
6991   }
6992   return SDValue();
6993 }
6994
6995 SDValue
6996 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6997   EVT VT = Op.getValueType();
6998   EVT EltVT = VT.getVectorElementType();
6999
7000   DebugLoc dl = Op.getDebugLoc();
7001   SDValue N0 = Op.getOperand(0);
7002   SDValue N1 = Op.getOperand(1);
7003   SDValue N2 = Op.getOperand(2);
7004
7005   // If this is a 256-bit vector result, first extract the 128-bit vector,
7006   // insert the element into the extracted half and then place it back.
7007   if (VT.getSizeInBits() == 256) {
7008     if (!isa<ConstantSDNode>(N2))
7009       return SDValue();
7010
7011     // Get the desired 128-bit vector half.
7012     unsigned NumElems = VT.getVectorNumElements();
7013     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7014     bool Upper = IdxVal >= NumElems/2;
7015     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7016     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7017
7018     // Insert the element into the desired half.
7019     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7020                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7021
7022     // Insert the changed part back to the 256-bit vector
7023     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7024   }
7025
7026   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7027     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7028
7029   if (EltVT == MVT::i8)
7030     return SDValue();
7031
7032   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7033     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7034     // as its second argument.
7035     if (N1.getValueType() != MVT::i32)
7036       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7037     if (N2.getValueType() != MVT::i32)
7038       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7039     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7040   }
7041   return SDValue();
7042 }
7043
7044 SDValue
7045 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7046   LLVMContext *Context = DAG.getContext();
7047   DebugLoc dl = Op.getDebugLoc();
7048   EVT OpVT = Op.getValueType();
7049
7050   // If this is a 256-bit vector result, first insert into a 128-bit
7051   // vector and then insert into the 256-bit vector.
7052   if (OpVT.getSizeInBits() > 128) {
7053     // Insert into a 128-bit vector.
7054     EVT VT128 = EVT::getVectorVT(*Context,
7055                                  OpVT.getVectorElementType(),
7056                                  OpVT.getVectorNumElements() / 2);
7057
7058     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7059
7060     // Insert the 128-bit vector.
7061     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7062                               DAG.getConstant(0, MVT::i32),
7063                               DAG, dl);
7064   }
7065
7066   if (Op.getValueType() == MVT::v1i64 &&
7067       Op.getOperand(0).getValueType() == MVT::i64)
7068     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7069
7070   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7071   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7072          "Expected an SSE type!");
7073   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7074                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7075 }
7076
7077 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7078 // a simple subregister reference or explicit instructions to grab
7079 // upper bits of a vector.
7080 SDValue
7081 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7082   if (Subtarget->hasAVX()) {
7083     DebugLoc dl = Op.getNode()->getDebugLoc();
7084     SDValue Vec = Op.getNode()->getOperand(0);
7085     SDValue Idx = Op.getNode()->getOperand(1);
7086
7087     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7088         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7089         return Extract128BitVector(Vec, Idx, DAG, dl);
7090     }
7091   }
7092   return SDValue();
7093 }
7094
7095 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7096 // simple superregister reference or explicit instructions to insert
7097 // the upper bits of a vector.
7098 SDValue
7099 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7100   if (Subtarget->hasAVX()) {
7101     DebugLoc dl = Op.getNode()->getDebugLoc();
7102     SDValue Vec = Op.getNode()->getOperand(0);
7103     SDValue SubVec = Op.getNode()->getOperand(1);
7104     SDValue Idx = Op.getNode()->getOperand(2);
7105
7106     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7107         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7108       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7109     }
7110   }
7111   return SDValue();
7112 }
7113
7114 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7115 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7116 // one of the above mentioned nodes. It has to be wrapped because otherwise
7117 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7118 // be used to form addressing mode. These wrapped nodes will be selected
7119 // into MOV32ri.
7120 SDValue
7121 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7122   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7123
7124   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7125   // global base reg.
7126   unsigned char OpFlag = 0;
7127   unsigned WrapperKind = X86ISD::Wrapper;
7128   CodeModel::Model M = getTargetMachine().getCodeModel();
7129
7130   if (Subtarget->isPICStyleRIPRel() &&
7131       (M == CodeModel::Small || M == CodeModel::Kernel))
7132     WrapperKind = X86ISD::WrapperRIP;
7133   else if (Subtarget->isPICStyleGOT())
7134     OpFlag = X86II::MO_GOTOFF;
7135   else if (Subtarget->isPICStyleStubPIC())
7136     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7137
7138   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7139                                              CP->getAlignment(),
7140                                              CP->getOffset(), OpFlag);
7141   DebugLoc DL = CP->getDebugLoc();
7142   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7143   // With PIC, the address is actually $g + Offset.
7144   if (OpFlag) {
7145     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7146                          DAG.getNode(X86ISD::GlobalBaseReg,
7147                                      DebugLoc(), getPointerTy()),
7148                          Result);
7149   }
7150
7151   return Result;
7152 }
7153
7154 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7155   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7156
7157   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7158   // global base reg.
7159   unsigned char OpFlag = 0;
7160   unsigned WrapperKind = X86ISD::Wrapper;
7161   CodeModel::Model M = getTargetMachine().getCodeModel();
7162
7163   if (Subtarget->isPICStyleRIPRel() &&
7164       (M == CodeModel::Small || M == CodeModel::Kernel))
7165     WrapperKind = X86ISD::WrapperRIP;
7166   else if (Subtarget->isPICStyleGOT())
7167     OpFlag = X86II::MO_GOTOFF;
7168   else if (Subtarget->isPICStyleStubPIC())
7169     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7170
7171   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7172                                           OpFlag);
7173   DebugLoc DL = JT->getDebugLoc();
7174   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7175
7176   // With PIC, the address is actually $g + Offset.
7177   if (OpFlag)
7178     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7179                          DAG.getNode(X86ISD::GlobalBaseReg,
7180                                      DebugLoc(), getPointerTy()),
7181                          Result);
7182
7183   return Result;
7184 }
7185
7186 SDValue
7187 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7188   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7189
7190   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7191   // global base reg.
7192   unsigned char OpFlag = 0;
7193   unsigned WrapperKind = X86ISD::Wrapper;
7194   CodeModel::Model M = getTargetMachine().getCodeModel();
7195
7196   if (Subtarget->isPICStyleRIPRel() &&
7197       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7198     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7199       OpFlag = X86II::MO_GOTPCREL;
7200     WrapperKind = X86ISD::WrapperRIP;
7201   } else if (Subtarget->isPICStyleGOT()) {
7202     OpFlag = X86II::MO_GOT;
7203   } else if (Subtarget->isPICStyleStubPIC()) {
7204     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7205   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7206     OpFlag = X86II::MO_DARWIN_NONLAZY;
7207   }
7208
7209   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7210
7211   DebugLoc DL = Op.getDebugLoc();
7212   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7213
7214
7215   // With PIC, the address is actually $g + Offset.
7216   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7217       !Subtarget->is64Bit()) {
7218     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7219                          DAG.getNode(X86ISD::GlobalBaseReg,
7220                                      DebugLoc(), getPointerTy()),
7221                          Result);
7222   }
7223
7224   // For symbols that require a load from a stub to get the address, emit the
7225   // load.
7226   if (isGlobalStubReference(OpFlag))
7227     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7228                          MachinePointerInfo::getGOT(), false, false, 0);
7229
7230   return Result;
7231 }
7232
7233 SDValue
7234 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7235   // Create the TargetBlockAddressAddress node.
7236   unsigned char OpFlags =
7237     Subtarget->ClassifyBlockAddressReference();
7238   CodeModel::Model M = getTargetMachine().getCodeModel();
7239   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7240   DebugLoc dl = Op.getDebugLoc();
7241   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7242                                        /*isTarget=*/true, OpFlags);
7243
7244   if (Subtarget->isPICStyleRIPRel() &&
7245       (M == CodeModel::Small || M == CodeModel::Kernel))
7246     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7247   else
7248     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7249
7250   // With PIC, the address is actually $g + Offset.
7251   if (isGlobalRelativeToPICBase(OpFlags)) {
7252     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7253                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7254                          Result);
7255   }
7256
7257   return Result;
7258 }
7259
7260 SDValue
7261 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7262                                       int64_t Offset,
7263                                       SelectionDAG &DAG) const {
7264   // Create the TargetGlobalAddress node, folding in the constant
7265   // offset if it is legal.
7266   unsigned char OpFlags =
7267     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7268   CodeModel::Model M = getTargetMachine().getCodeModel();
7269   SDValue Result;
7270   if (OpFlags == X86II::MO_NO_FLAG &&
7271       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7272     // A direct static reference to a global.
7273     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7274     Offset = 0;
7275   } else {
7276     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7277   }
7278
7279   if (Subtarget->isPICStyleRIPRel() &&
7280       (M == CodeModel::Small || M == CodeModel::Kernel))
7281     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7282   else
7283     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7284
7285   // With PIC, the address is actually $g + Offset.
7286   if (isGlobalRelativeToPICBase(OpFlags)) {
7287     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7288                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7289                          Result);
7290   }
7291
7292   // For globals that require a load from a stub to get the address, emit the
7293   // load.
7294   if (isGlobalStubReference(OpFlags))
7295     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7296                          MachinePointerInfo::getGOT(), false, false, 0);
7297
7298   // If there was a non-zero offset that we didn't fold, create an explicit
7299   // addition for it.
7300   if (Offset != 0)
7301     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7302                          DAG.getConstant(Offset, getPointerTy()));
7303
7304   return Result;
7305 }
7306
7307 SDValue
7308 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7309   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7310   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7311   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7312 }
7313
7314 static SDValue
7315 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7316            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7317            unsigned char OperandFlags) {
7318   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7319   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7320   DebugLoc dl = GA->getDebugLoc();
7321   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7322                                            GA->getValueType(0),
7323                                            GA->getOffset(),
7324                                            OperandFlags);
7325   if (InFlag) {
7326     SDValue Ops[] = { Chain,  TGA, *InFlag };
7327     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7328   } else {
7329     SDValue Ops[]  = { Chain, TGA };
7330     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7331   }
7332
7333   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7334   MFI->setAdjustsStack(true);
7335
7336   SDValue Flag = Chain.getValue(1);
7337   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7338 }
7339
7340 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7341 static SDValue
7342 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7343                                 const EVT PtrVT) {
7344   SDValue InFlag;
7345   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7346   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7347                                      DAG.getNode(X86ISD::GlobalBaseReg,
7348                                                  DebugLoc(), PtrVT), InFlag);
7349   InFlag = Chain.getValue(1);
7350
7351   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7352 }
7353
7354 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7355 static SDValue
7356 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7357                                 const EVT PtrVT) {
7358   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7359                     X86::RAX, X86II::MO_TLSGD);
7360 }
7361
7362 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7363 // "local exec" model.
7364 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7365                                    const EVT PtrVT, TLSModel::Model model,
7366                                    bool is64Bit) {
7367   DebugLoc dl = GA->getDebugLoc();
7368
7369   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7370   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7371                                                          is64Bit ? 257 : 256));
7372
7373   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7374                                       DAG.getIntPtrConstant(0),
7375                                       MachinePointerInfo(Ptr), false, false, 0);
7376
7377   unsigned char OperandFlags = 0;
7378   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7379   // initialexec.
7380   unsigned WrapperKind = X86ISD::Wrapper;
7381   if (model == TLSModel::LocalExec) {
7382     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7383   } else if (is64Bit) {
7384     assert(model == TLSModel::InitialExec);
7385     OperandFlags = X86II::MO_GOTTPOFF;
7386     WrapperKind = X86ISD::WrapperRIP;
7387   } else {
7388     assert(model == TLSModel::InitialExec);
7389     OperandFlags = X86II::MO_INDNTPOFF;
7390   }
7391
7392   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7393   // exec)
7394   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7395                                            GA->getValueType(0),
7396                                            GA->getOffset(), OperandFlags);
7397   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7398
7399   if (model == TLSModel::InitialExec)
7400     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7401                          MachinePointerInfo::getGOT(), false, false, 0);
7402
7403   // The address of the thread local variable is the add of the thread
7404   // pointer with the offset of the variable.
7405   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7406 }
7407
7408 SDValue
7409 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7410
7411   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7412   const GlobalValue *GV = GA->getGlobal();
7413
7414   if (Subtarget->isTargetELF()) {
7415     // TODO: implement the "local dynamic" model
7416     // TODO: implement the "initial exec"model for pic executables
7417
7418     // If GV is an alias then use the aliasee for determining
7419     // thread-localness.
7420     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7421       GV = GA->resolveAliasedGlobal(false);
7422
7423     TLSModel::Model model
7424       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7425
7426     switch (model) {
7427       case TLSModel::GeneralDynamic:
7428       case TLSModel::LocalDynamic: // not implemented
7429         if (Subtarget->is64Bit())
7430           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7431         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7432
7433       case TLSModel::InitialExec:
7434       case TLSModel::LocalExec:
7435         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7436                                    Subtarget->is64Bit());
7437     }
7438   } else if (Subtarget->isTargetDarwin()) {
7439     // Darwin only has one model of TLS.  Lower to that.
7440     unsigned char OpFlag = 0;
7441     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7442                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7443
7444     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7445     // global base reg.
7446     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7447                   !Subtarget->is64Bit();
7448     if (PIC32)
7449       OpFlag = X86II::MO_TLVP_PIC_BASE;
7450     else
7451       OpFlag = X86II::MO_TLVP;
7452     DebugLoc DL = Op.getDebugLoc();
7453     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7454                                                 GA->getValueType(0),
7455                                                 GA->getOffset(), OpFlag);
7456     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7457
7458     // With PIC32, the address is actually $g + Offset.
7459     if (PIC32)
7460       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461                            DAG.getNode(X86ISD::GlobalBaseReg,
7462                                        DebugLoc(), getPointerTy()),
7463                            Offset);
7464
7465     // Lowering the machine isd will make sure everything is in the right
7466     // location.
7467     SDValue Chain = DAG.getEntryNode();
7468     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7469     SDValue Args[] = { Chain, Offset };
7470     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7471
7472     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7473     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7474     MFI->setAdjustsStack(true);
7475
7476     // And our return value (tls address) is in the standard call return value
7477     // location.
7478     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7479     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7480   }
7481
7482   assert(false &&
7483          "TLS not implemented for this target.");
7484
7485   llvm_unreachable("Unreachable");
7486   return SDValue();
7487 }
7488
7489
7490 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7491 /// take a 2 x i32 value to shift plus a shift amount.
7492 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7493   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7494   EVT VT = Op.getValueType();
7495   unsigned VTBits = VT.getSizeInBits();
7496   DebugLoc dl = Op.getDebugLoc();
7497   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7498   SDValue ShOpLo = Op.getOperand(0);
7499   SDValue ShOpHi = Op.getOperand(1);
7500   SDValue ShAmt  = Op.getOperand(2);
7501   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7502                                      DAG.getConstant(VTBits - 1, MVT::i8))
7503                        : DAG.getConstant(0, VT);
7504
7505   SDValue Tmp2, Tmp3;
7506   if (Op.getOpcode() == ISD::SHL_PARTS) {
7507     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7508     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7509   } else {
7510     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7511     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7512   }
7513
7514   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7515                                 DAG.getConstant(VTBits, MVT::i8));
7516   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7517                              AndNode, DAG.getConstant(0, MVT::i8));
7518
7519   SDValue Hi, Lo;
7520   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7521   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7522   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7523
7524   if (Op.getOpcode() == ISD::SHL_PARTS) {
7525     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7526     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7527   } else {
7528     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7529     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7530   }
7531
7532   SDValue Ops[2] = { Lo, Hi };
7533   return DAG.getMergeValues(Ops, 2, dl);
7534 }
7535
7536 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7537                                            SelectionDAG &DAG) const {
7538   EVT SrcVT = Op.getOperand(0).getValueType();
7539
7540   if (SrcVT.isVector())
7541     return SDValue();
7542
7543   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7544          "Unknown SINT_TO_FP to lower!");
7545
7546   // These are really Legal; return the operand so the caller accepts it as
7547   // Legal.
7548   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7549     return Op;
7550   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7551       Subtarget->is64Bit()) {
7552     return Op;
7553   }
7554
7555   DebugLoc dl = Op.getDebugLoc();
7556   unsigned Size = SrcVT.getSizeInBits()/8;
7557   MachineFunction &MF = DAG.getMachineFunction();
7558   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7559   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7560   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7561                                StackSlot,
7562                                MachinePointerInfo::getFixedStack(SSFI),
7563                                false, false, 0);
7564   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7565 }
7566
7567 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7568                                      SDValue StackSlot,
7569                                      SelectionDAG &DAG) const {
7570   // Build the FILD
7571   DebugLoc DL = Op.getDebugLoc();
7572   SDVTList Tys;
7573   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7574   if (useSSE)
7575     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7576   else
7577     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7578
7579   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7580
7581   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7582   MachineMemOperand *MMO;
7583   if (FI) {
7584     int SSFI = FI->getIndex();
7585     MMO =
7586       DAG.getMachineFunction()
7587       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7588                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7589   } else {
7590     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7591     StackSlot = StackSlot.getOperand(1);
7592   }
7593   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7594   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7595                                            X86ISD::FILD, DL,
7596                                            Tys, Ops, array_lengthof(Ops),
7597                                            SrcVT, MMO);
7598
7599   if (useSSE) {
7600     Chain = Result.getValue(1);
7601     SDValue InFlag = Result.getValue(2);
7602
7603     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7604     // shouldn't be necessary except that RFP cannot be live across
7605     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7606     MachineFunction &MF = DAG.getMachineFunction();
7607     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7608     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7609     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7610     Tys = DAG.getVTList(MVT::Other);
7611     SDValue Ops[] = {
7612       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7613     };
7614     MachineMemOperand *MMO =
7615       DAG.getMachineFunction()
7616       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7617                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7618
7619     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7620                                     Ops, array_lengthof(Ops),
7621                                     Op.getValueType(), MMO);
7622     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7623                          MachinePointerInfo::getFixedStack(SSFI),
7624                          false, false, 0);
7625   }
7626
7627   return Result;
7628 }
7629
7630 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7631 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7632                                                SelectionDAG &DAG) const {
7633   // This algorithm is not obvious. Here it is in C code, more or less:
7634   /*
7635     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7636       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7637       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7638
7639       // Copy ints to xmm registers.
7640       __m128i xh = _mm_cvtsi32_si128( hi );
7641       __m128i xl = _mm_cvtsi32_si128( lo );
7642
7643       // Combine into low half of a single xmm register.
7644       __m128i x = _mm_unpacklo_epi32( xh, xl );
7645       __m128d d;
7646       double sd;
7647
7648       // Merge in appropriate exponents to give the integer bits the right
7649       // magnitude.
7650       x = _mm_unpacklo_epi32( x, exp );
7651
7652       // Subtract away the biases to deal with the IEEE-754 double precision
7653       // implicit 1.
7654       d = _mm_sub_pd( (__m128d) x, bias );
7655
7656       // All conversions up to here are exact. The correctly rounded result is
7657       // calculated using the current rounding mode using the following
7658       // horizontal add.
7659       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7660       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7661                                 // store doesn't really need to be here (except
7662                                 // maybe to zero the other double)
7663       return sd;
7664     }
7665   */
7666
7667   DebugLoc dl = Op.getDebugLoc();
7668   LLVMContext *Context = DAG.getContext();
7669
7670   // Build some magic constants.
7671   std::vector<Constant*> CV0;
7672   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7673   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7674   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7675   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7676   Constant *C0 = ConstantVector::get(CV0);
7677   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7678
7679   std::vector<Constant*> CV1;
7680   CV1.push_back(
7681     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7682   CV1.push_back(
7683     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7684   Constant *C1 = ConstantVector::get(CV1);
7685   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7686
7687   SDValue XR1 = 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(1)));
7691   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7692                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7693                                         Op.getOperand(0),
7694                                         DAG.getIntPtrConstant(0)));
7695   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7696   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7697                               MachinePointerInfo::getConstantPool(),
7698                               false, false, 16);
7699   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7700   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7701   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7702                               MachinePointerInfo::getConstantPool(),
7703                               false, false, 16);
7704   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7705
7706   // Add the halves; easiest way is to swap them into another reg first.
7707   int ShufMask[2] = { 1, -1 };
7708   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7709                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7710   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7711   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7712                      DAG.getIntPtrConstant(0));
7713 }
7714
7715 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7716 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7717                                                SelectionDAG &DAG) const {
7718   DebugLoc dl = Op.getDebugLoc();
7719   // FP constant to bias correct the final result.
7720   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7721                                    MVT::f64);
7722
7723   // Load the 32-bit value into an XMM register.
7724   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7725                              Op.getOperand(0));
7726
7727   // Zero out the upper parts of the register.
7728   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasSSE2(), DAG);
7729
7730   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7731                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7732                      DAG.getIntPtrConstant(0));
7733
7734   // Or the load with the bias.
7735   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7736                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7737                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7738                                                    MVT::v2f64, Load)),
7739                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7740                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7741                                                    MVT::v2f64, Bias)));
7742   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7743                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7744                    DAG.getIntPtrConstant(0));
7745
7746   // Subtract the bias.
7747   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7748
7749   // Handle final rounding.
7750   EVT DestVT = Op.getValueType();
7751
7752   if (DestVT.bitsLT(MVT::f64)) {
7753     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7754                        DAG.getIntPtrConstant(0));
7755   } else if (DestVT.bitsGT(MVT::f64)) {
7756     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7757   }
7758
7759   // Handle final rounding.
7760   return Sub;
7761 }
7762
7763 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7764                                            SelectionDAG &DAG) const {
7765   SDValue N0 = Op.getOperand(0);
7766   DebugLoc dl = Op.getDebugLoc();
7767
7768   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7769   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7770   // the optimization here.
7771   if (DAG.SignBitIsZero(N0))
7772     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7773
7774   EVT SrcVT = N0.getValueType();
7775   EVT DstVT = Op.getValueType();
7776   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7777     return LowerUINT_TO_FP_i64(Op, DAG);
7778   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7779     return LowerUINT_TO_FP_i32(Op, DAG);
7780
7781   // Make a 64-bit buffer, and use it to build an FILD.
7782   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7783   if (SrcVT == MVT::i32) {
7784     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7785     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7786                                      getPointerTy(), StackSlot, WordOff);
7787     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7788                                   StackSlot, MachinePointerInfo(),
7789                                   false, false, 0);
7790     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7791                                   OffsetSlot, MachinePointerInfo(),
7792                                   false, false, 0);
7793     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7794     return Fild;
7795   }
7796
7797   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7798   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7799                                 StackSlot, MachinePointerInfo(),
7800                                false, false, 0);
7801   // For i64 source, we need to add the appropriate power of 2 if the input
7802   // was negative.  This is the same as the optimization in
7803   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7804   // we must be careful to do the computation in x87 extended precision, not
7805   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7806   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7807   MachineMemOperand *MMO =
7808     DAG.getMachineFunction()
7809     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7810                           MachineMemOperand::MOLoad, 8, 8);
7811
7812   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7813   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7814   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7815                                          MVT::i64, MMO);
7816
7817   APInt FF(32, 0x5F800000ULL);
7818
7819   // Check whether the sign bit is set.
7820   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7821                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7822                                  ISD::SETLT);
7823
7824   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7825   SDValue FudgePtr = DAG.getConstantPool(
7826                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7827                                          getPointerTy());
7828
7829   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7830   SDValue Zero = DAG.getIntPtrConstant(0);
7831   SDValue Four = DAG.getIntPtrConstant(4);
7832   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7833                                Zero, Four);
7834   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7835
7836   // Load the value out, extending it from f32 to f80.
7837   // FIXME: Avoid the extend by constructing the right constant pool?
7838   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7839                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7840                                  MVT::f32, false, false, 4);
7841   // Extend everything to 80 bits to force it to be done on x87.
7842   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7843   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7844 }
7845
7846 std::pair<SDValue,SDValue> X86TargetLowering::
7847 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7848   DebugLoc DL = Op.getDebugLoc();
7849
7850   EVT DstTy = Op.getValueType();
7851
7852   if (!IsSigned) {
7853     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7854     DstTy = MVT::i64;
7855   }
7856
7857   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7858          DstTy.getSimpleVT() >= MVT::i16 &&
7859          "Unknown FP_TO_SINT to lower!");
7860
7861   // These are really Legal.
7862   if (DstTy == MVT::i32 &&
7863       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7864     return std::make_pair(SDValue(), SDValue());
7865   if (Subtarget->is64Bit() &&
7866       DstTy == MVT::i64 &&
7867       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7868     return std::make_pair(SDValue(), SDValue());
7869
7870   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7871   // stack slot.
7872   MachineFunction &MF = DAG.getMachineFunction();
7873   unsigned MemSize = DstTy.getSizeInBits()/8;
7874   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7875   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7876
7877
7878
7879   unsigned Opc;
7880   switch (DstTy.getSimpleVT().SimpleTy) {
7881   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7882   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7883   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7884   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7885   }
7886
7887   SDValue Chain = DAG.getEntryNode();
7888   SDValue Value = Op.getOperand(0);
7889   EVT TheVT = Op.getOperand(0).getValueType();
7890   if (isScalarFPTypeInSSEReg(TheVT)) {
7891     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7892     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7893                          MachinePointerInfo::getFixedStack(SSFI),
7894                          false, false, 0);
7895     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7896     SDValue Ops[] = {
7897       Chain, StackSlot, DAG.getValueType(TheVT)
7898     };
7899
7900     MachineMemOperand *MMO =
7901       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7902                               MachineMemOperand::MOLoad, MemSize, MemSize);
7903     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7904                                     DstTy, MMO);
7905     Chain = Value.getValue(1);
7906     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7907     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7908   }
7909
7910   MachineMemOperand *MMO =
7911     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7912                             MachineMemOperand::MOStore, MemSize, MemSize);
7913
7914   // Build the FP_TO_INT*_IN_MEM
7915   SDValue Ops[] = { Chain, Value, StackSlot };
7916   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7917                                          Ops, 3, DstTy, MMO);
7918
7919   return std::make_pair(FIST, StackSlot);
7920 }
7921
7922 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7923                                            SelectionDAG &DAG) const {
7924   if (Op.getValueType().isVector())
7925     return SDValue();
7926
7927   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7928   SDValue FIST = Vals.first, StackSlot = Vals.second;
7929   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7930   if (FIST.getNode() == 0) return Op;
7931
7932   // Load the result.
7933   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7934                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7935 }
7936
7937 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7938                                            SelectionDAG &DAG) const {
7939   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7940   SDValue FIST = Vals.first, StackSlot = Vals.second;
7941   assert(FIST.getNode() && "Unexpected failure");
7942
7943   // Load the result.
7944   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7945                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7946 }
7947
7948 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7949                                      SelectionDAG &DAG) const {
7950   LLVMContext *Context = DAG.getContext();
7951   DebugLoc dl = Op.getDebugLoc();
7952   EVT VT = Op.getValueType();
7953   EVT EltVT = VT;
7954   if (VT.isVector())
7955     EltVT = VT.getVectorElementType();
7956   std::vector<Constant*> CV;
7957   if (EltVT == MVT::f64) {
7958     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7959     CV.push_back(C);
7960     CV.push_back(C);
7961   } else {
7962     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7963     CV.push_back(C);
7964     CV.push_back(C);
7965     CV.push_back(C);
7966     CV.push_back(C);
7967   }
7968   Constant *C = ConstantVector::get(CV);
7969   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7970   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7971                              MachinePointerInfo::getConstantPool(),
7972                              false, false, 16);
7973   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7974 }
7975
7976 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7977   LLVMContext *Context = DAG.getContext();
7978   DebugLoc dl = Op.getDebugLoc();
7979   EVT VT = Op.getValueType();
7980   EVT EltVT = VT;
7981   if (VT.isVector())
7982     EltVT = VT.getVectorElementType();
7983   std::vector<Constant*> CV;
7984   if (EltVT == MVT::f64) {
7985     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7986     CV.push_back(C);
7987     CV.push_back(C);
7988   } else {
7989     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7990     CV.push_back(C);
7991     CV.push_back(C);
7992     CV.push_back(C);
7993     CV.push_back(C);
7994   }
7995   Constant *C = ConstantVector::get(CV);
7996   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7997   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7998                              MachinePointerInfo::getConstantPool(),
7999                              false, false, 16);
8000   if (VT.isVector()) {
8001     return DAG.getNode(ISD::BITCAST, dl, VT,
8002                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8003                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8004                                 Op.getOperand(0)),
8005                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8006   } else {
8007     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8008   }
8009 }
8010
8011 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8012   LLVMContext *Context = DAG.getContext();
8013   SDValue Op0 = Op.getOperand(0);
8014   SDValue Op1 = Op.getOperand(1);
8015   DebugLoc dl = Op.getDebugLoc();
8016   EVT VT = Op.getValueType();
8017   EVT SrcVT = Op1.getValueType();
8018
8019   // If second operand is smaller, extend it first.
8020   if (SrcVT.bitsLT(VT)) {
8021     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8022     SrcVT = VT;
8023   }
8024   // And if it is bigger, shrink it first.
8025   if (SrcVT.bitsGT(VT)) {
8026     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8027     SrcVT = VT;
8028   }
8029
8030   // At this point the operands and the result should have the same
8031   // type, and that won't be f80 since that is not custom lowered.
8032
8033   // First get the sign bit of second operand.
8034   std::vector<Constant*> CV;
8035   if (SrcVT == MVT::f64) {
8036     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8037     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8038   } else {
8039     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8040     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8041     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8042     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8043   }
8044   Constant *C = ConstantVector::get(CV);
8045   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8046   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8047                               MachinePointerInfo::getConstantPool(),
8048                               false, false, 16);
8049   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8050
8051   // Shift sign bit right or left if the two operands have different types.
8052   if (SrcVT.bitsGT(VT)) {
8053     // Op0 is MVT::f32, Op1 is MVT::f64.
8054     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8055     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8056                           DAG.getConstant(32, MVT::i32));
8057     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8058     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8059                           DAG.getIntPtrConstant(0));
8060   }
8061
8062   // Clear first operand sign bit.
8063   CV.clear();
8064   if (VT == MVT::f64) {
8065     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8066     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8067   } else {
8068     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8069     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8070     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8071     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8072   }
8073   C = ConstantVector::get(CV);
8074   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8075   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8076                               MachinePointerInfo::getConstantPool(),
8077                               false, false, 16);
8078   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8079
8080   // Or the value with the sign bit.
8081   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8082 }
8083
8084 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8085   SDValue N0 = Op.getOperand(0);
8086   DebugLoc dl = Op.getDebugLoc();
8087   EVT VT = Op.getValueType();
8088
8089   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8090   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8091                                   DAG.getConstant(1, VT));
8092   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8093 }
8094
8095 /// Emit nodes that will be selected as "test Op0,Op0", or something
8096 /// equivalent.
8097 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8098                                     SelectionDAG &DAG) const {
8099   DebugLoc dl = Op.getDebugLoc();
8100
8101   // CF and OF aren't always set the way we want. Determine which
8102   // of these we need.
8103   bool NeedCF = false;
8104   bool NeedOF = false;
8105   switch (X86CC) {
8106   default: break;
8107   case X86::COND_A: case X86::COND_AE:
8108   case X86::COND_B: case X86::COND_BE:
8109     NeedCF = true;
8110     break;
8111   case X86::COND_G: case X86::COND_GE:
8112   case X86::COND_L: case X86::COND_LE:
8113   case X86::COND_O: case X86::COND_NO:
8114     NeedOF = true;
8115     break;
8116   }
8117
8118   // See if we can use the EFLAGS value from the operand instead of
8119   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8120   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8121   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8122     // Emit a CMP with 0, which is the TEST pattern.
8123     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8124                        DAG.getConstant(0, Op.getValueType()));
8125
8126   unsigned Opcode = 0;
8127   unsigned NumOperands = 0;
8128   switch (Op.getNode()->getOpcode()) {
8129   case ISD::ADD:
8130     // Due to an isel shortcoming, be conservative if this add is likely to be
8131     // selected as part of a load-modify-store instruction. When the root node
8132     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8133     // uses of other nodes in the match, such as the ADD in this case. This
8134     // leads to the ADD being left around and reselected, with the result being
8135     // two adds in the output.  Alas, even if none our users are stores, that
8136     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8137     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8138     // climbing the DAG back to the root, and it doesn't seem to be worth the
8139     // effort.
8140     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8141            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8142       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8143         goto default_case;
8144
8145     if (ConstantSDNode *C =
8146         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8147       // An add of one will be selected as an INC.
8148       if (C->getAPIntValue() == 1) {
8149         Opcode = X86ISD::INC;
8150         NumOperands = 1;
8151         break;
8152       }
8153
8154       // An add of negative one (subtract of one) will be selected as a DEC.
8155       if (C->getAPIntValue().isAllOnesValue()) {
8156         Opcode = X86ISD::DEC;
8157         NumOperands = 1;
8158         break;
8159       }
8160     }
8161
8162     // Otherwise use a regular EFLAGS-setting add.
8163     Opcode = X86ISD::ADD;
8164     NumOperands = 2;
8165     break;
8166   case ISD::AND: {
8167     // If the primary and result isn't used, don't bother using X86ISD::AND,
8168     // because a TEST instruction will be better.
8169     bool NonFlagUse = false;
8170     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8171            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8172       SDNode *User = *UI;
8173       unsigned UOpNo = UI.getOperandNo();
8174       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8175         // Look pass truncate.
8176         UOpNo = User->use_begin().getOperandNo();
8177         User = *User->use_begin();
8178       }
8179
8180       if (User->getOpcode() != ISD::BRCOND &&
8181           User->getOpcode() != ISD::SETCC &&
8182           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8183         NonFlagUse = true;
8184         break;
8185       }
8186     }
8187
8188     if (!NonFlagUse)
8189       break;
8190   }
8191     // FALL THROUGH
8192   case ISD::SUB:
8193   case ISD::OR:
8194   case ISD::XOR:
8195     // Due to the ISEL shortcoming noted above, be conservative if this op is
8196     // likely to be selected as part of a load-modify-store instruction.
8197     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8198            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8199       if (UI->getOpcode() == ISD::STORE)
8200         goto default_case;
8201
8202     // Otherwise use a regular EFLAGS-setting instruction.
8203     switch (Op.getNode()->getOpcode()) {
8204     default: llvm_unreachable("unexpected operator!");
8205     case ISD::SUB: Opcode = X86ISD::SUB; break;
8206     case ISD::OR:  Opcode = X86ISD::OR;  break;
8207     case ISD::XOR: Opcode = X86ISD::XOR; break;
8208     case ISD::AND: Opcode = X86ISD::AND; break;
8209     }
8210
8211     NumOperands = 2;
8212     break;
8213   case X86ISD::ADD:
8214   case X86ISD::SUB:
8215   case X86ISD::INC:
8216   case X86ISD::DEC:
8217   case X86ISD::OR:
8218   case X86ISD::XOR:
8219   case X86ISD::AND:
8220     return SDValue(Op.getNode(), 1);
8221   default:
8222   default_case:
8223     break;
8224   }
8225
8226   if (Opcode == 0)
8227     // Emit a CMP with 0, which is the TEST pattern.
8228     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8229                        DAG.getConstant(0, Op.getValueType()));
8230
8231   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8232   SmallVector<SDValue, 4> Ops;
8233   for (unsigned i = 0; i != NumOperands; ++i)
8234     Ops.push_back(Op.getOperand(i));
8235
8236   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8237   DAG.ReplaceAllUsesWith(Op, New);
8238   return SDValue(New.getNode(), 1);
8239 }
8240
8241 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8242 /// equivalent.
8243 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8244                                    SelectionDAG &DAG) const {
8245   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8246     if (C->getAPIntValue() == 0)
8247       return EmitTest(Op0, X86CC, DAG);
8248
8249   DebugLoc dl = Op0.getDebugLoc();
8250   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8251 }
8252
8253 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8254 /// if it's possible.
8255 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8256                                      DebugLoc dl, SelectionDAG &DAG) const {
8257   SDValue Op0 = And.getOperand(0);
8258   SDValue Op1 = And.getOperand(1);
8259   if (Op0.getOpcode() == ISD::TRUNCATE)
8260     Op0 = Op0.getOperand(0);
8261   if (Op1.getOpcode() == ISD::TRUNCATE)
8262     Op1 = Op1.getOperand(0);
8263
8264   SDValue LHS, RHS;
8265   if (Op1.getOpcode() == ISD::SHL)
8266     std::swap(Op0, Op1);
8267   if (Op0.getOpcode() == ISD::SHL) {
8268     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8269       if (And00C->getZExtValue() == 1) {
8270         // If we looked past a truncate, check that it's only truncating away
8271         // known zeros.
8272         unsigned BitWidth = Op0.getValueSizeInBits();
8273         unsigned AndBitWidth = And.getValueSizeInBits();
8274         if (BitWidth > AndBitWidth) {
8275           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8276           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8277           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8278             return SDValue();
8279         }
8280         LHS = Op1;
8281         RHS = Op0.getOperand(1);
8282       }
8283   } else if (Op1.getOpcode() == ISD::Constant) {
8284     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8285     SDValue AndLHS = Op0;
8286     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8287       LHS = AndLHS.getOperand(0);
8288       RHS = AndLHS.getOperand(1);
8289     }
8290   }
8291
8292   if (LHS.getNode()) {
8293     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8294     // instruction.  Since the shift amount is in-range-or-undefined, we know
8295     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8296     // the encoding for the i16 version is larger than the i32 version.
8297     // Also promote i16 to i32 for performance / code size reason.
8298     if (LHS.getValueType() == MVT::i8 ||
8299         LHS.getValueType() == MVT::i16)
8300       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8301
8302     // If the operand types disagree, extend the shift amount to match.  Since
8303     // BT ignores high bits (like shifts) we can use anyextend.
8304     if (LHS.getValueType() != RHS.getValueType())
8305       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8306
8307     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8308     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8309     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8310                        DAG.getConstant(Cond, MVT::i8), BT);
8311   }
8312
8313   return SDValue();
8314 }
8315
8316 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8317   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8318   SDValue Op0 = Op.getOperand(0);
8319   SDValue Op1 = Op.getOperand(1);
8320   DebugLoc dl = Op.getDebugLoc();
8321   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8322
8323   // Optimize to BT if possible.
8324   // Lower (X & (1 << N)) == 0 to BT(X, N).
8325   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8326   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8327   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8328       Op1.getOpcode() == ISD::Constant &&
8329       cast<ConstantSDNode>(Op1)->isNullValue() &&
8330       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8331     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8332     if (NewSetCC.getNode())
8333       return NewSetCC;
8334   }
8335
8336   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8337   // these.
8338   if (Op1.getOpcode() == ISD::Constant &&
8339       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8340        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8341       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8342
8343     // If the input is a setcc, then reuse the input setcc or use a new one with
8344     // the inverted condition.
8345     if (Op0.getOpcode() == X86ISD::SETCC) {
8346       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8347       bool Invert = (CC == ISD::SETNE) ^
8348         cast<ConstantSDNode>(Op1)->isNullValue();
8349       if (!Invert) return Op0;
8350
8351       CCode = X86::GetOppositeBranchCondition(CCode);
8352       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8353                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8354     }
8355   }
8356
8357   bool isFP = Op1.getValueType().isFloatingPoint();
8358   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8359   if (X86CC == X86::COND_INVALID)
8360     return SDValue();
8361
8362   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8363   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8364                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8365 }
8366
8367 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8368 // ones, and then concatenate the result back.
8369 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8370   EVT VT = Op.getValueType();
8371
8372   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::VSETCC &&
8373          "Unsupported value type for operation");
8374
8375   int NumElems = VT.getVectorNumElements();
8376   DebugLoc dl = Op.getDebugLoc();
8377   SDValue CC = Op.getOperand(2);
8378   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8379   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8380
8381   // Extract the LHS vectors
8382   SDValue LHS = Op.getOperand(0);
8383   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8384   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8385
8386   // Extract the RHS vectors
8387   SDValue RHS = Op.getOperand(1);
8388   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8389   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8390
8391   // Issue the operation on the smaller types and concatenate the result back
8392   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8393   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8394   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8395                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8396                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8397 }
8398
8399
8400 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8401   SDValue Cond;
8402   SDValue Op0 = Op.getOperand(0);
8403   SDValue Op1 = Op.getOperand(1);
8404   SDValue CC = Op.getOperand(2);
8405   EVT VT = Op.getValueType();
8406   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8407   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8408   DebugLoc dl = Op.getDebugLoc();
8409
8410   if (isFP) {
8411     unsigned SSECC = 8;
8412     EVT EltVT = Op0.getValueType().getVectorElementType();
8413     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8414
8415     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8416     bool Swap = false;
8417
8418     switch (SetCCOpcode) {
8419     default: break;
8420     case ISD::SETOEQ:
8421     case ISD::SETEQ:  SSECC = 0; break;
8422     case ISD::SETOGT:
8423     case ISD::SETGT: Swap = true; // Fallthrough
8424     case ISD::SETLT:
8425     case ISD::SETOLT: SSECC = 1; break;
8426     case ISD::SETOGE:
8427     case ISD::SETGE: Swap = true; // Fallthrough
8428     case ISD::SETLE:
8429     case ISD::SETOLE: SSECC = 2; break;
8430     case ISD::SETUO:  SSECC = 3; break;
8431     case ISD::SETUNE:
8432     case ISD::SETNE:  SSECC = 4; break;
8433     case ISD::SETULE: Swap = true;
8434     case ISD::SETUGE: SSECC = 5; break;
8435     case ISD::SETULT: Swap = true;
8436     case ISD::SETUGT: SSECC = 6; break;
8437     case ISD::SETO:   SSECC = 7; break;
8438     }
8439     if (Swap)
8440       std::swap(Op0, Op1);
8441
8442     // In the two special cases we can't handle, emit two comparisons.
8443     if (SSECC == 8) {
8444       if (SetCCOpcode == ISD::SETUEQ) {
8445         SDValue UNORD, EQ;
8446         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8447         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8448         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8449       }
8450       else if (SetCCOpcode == ISD::SETONE) {
8451         SDValue ORD, NEQ;
8452         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8453         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8454         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8455       }
8456       llvm_unreachable("Illegal FP comparison");
8457     }
8458     // Handle all other FP comparisons here.
8459     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8460   }
8461
8462   // Break 256-bit integer vector compare into smaller ones.
8463   if (!isFP && VT.getSizeInBits() == 256)
8464     return Lower256IntVETCC(Op, DAG);
8465
8466   // We are handling one of the integer comparisons here.  Since SSE only has
8467   // GT and EQ comparisons for integer, swapping operands and multiple
8468   // operations may be required for some comparisons.
8469   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8470   bool Swap = false, Invert = false, FlipSigns = false;
8471
8472   switch (VT.getSimpleVT().SimpleTy) {
8473   default: break;
8474   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8475   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8476   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8477   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8478   }
8479
8480   switch (SetCCOpcode) {
8481   default: break;
8482   case ISD::SETNE:  Invert = true;
8483   case ISD::SETEQ:  Opc = EQOpc; break;
8484   case ISD::SETLT:  Swap = true;
8485   case ISD::SETGT:  Opc = GTOpc; break;
8486   case ISD::SETGE:  Swap = true;
8487   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8488   case ISD::SETULT: Swap = true;
8489   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8490   case ISD::SETUGE: Swap = true;
8491   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8492   }
8493   if (Swap)
8494     std::swap(Op0, Op1);
8495
8496   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8497   // bits of the inputs before performing those operations.
8498   if (FlipSigns) {
8499     EVT EltVT = VT.getVectorElementType();
8500     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8501                                       EltVT);
8502     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8503     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8504                                     SignBits.size());
8505     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8506     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8507   }
8508
8509   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8510
8511   // If the logical-not of the result is required, perform that now.
8512   if (Invert)
8513     Result = DAG.getNOT(dl, Result, VT);
8514
8515   return Result;
8516 }
8517
8518 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8519 static bool isX86LogicalCmp(SDValue Op) {
8520   unsigned Opc = Op.getNode()->getOpcode();
8521   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8522     return true;
8523   if (Op.getResNo() == 1 &&
8524       (Opc == X86ISD::ADD ||
8525        Opc == X86ISD::SUB ||
8526        Opc == X86ISD::ADC ||
8527        Opc == X86ISD::SBB ||
8528        Opc == X86ISD::SMUL ||
8529        Opc == X86ISD::UMUL ||
8530        Opc == X86ISD::INC ||
8531        Opc == X86ISD::DEC ||
8532        Opc == X86ISD::OR ||
8533        Opc == X86ISD::XOR ||
8534        Opc == X86ISD::AND))
8535     return true;
8536
8537   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8538     return true;
8539
8540   return false;
8541 }
8542
8543 static bool isZero(SDValue V) {
8544   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8545   return C && C->isNullValue();
8546 }
8547
8548 static bool isAllOnes(SDValue V) {
8549   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8550   return C && C->isAllOnesValue();
8551 }
8552
8553 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8554   bool addTest = true;
8555   SDValue Cond  = Op.getOperand(0);
8556   SDValue Op1 = Op.getOperand(1);
8557   SDValue Op2 = Op.getOperand(2);
8558   DebugLoc DL = Op.getDebugLoc();
8559   SDValue CC;
8560
8561   if (Cond.getOpcode() == ISD::SETCC) {
8562     SDValue NewCond = LowerSETCC(Cond, DAG);
8563     if (NewCond.getNode())
8564       Cond = NewCond;
8565   }
8566
8567   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8568   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8569   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8570   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8571   if (Cond.getOpcode() == X86ISD::SETCC &&
8572       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8573       isZero(Cond.getOperand(1).getOperand(1))) {
8574     SDValue Cmp = Cond.getOperand(1);
8575
8576     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8577
8578     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8579         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8580       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8581
8582       SDValue CmpOp0 = Cmp.getOperand(0);
8583       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8584                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8585
8586       SDValue Res =   // Res = 0 or -1.
8587         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8588                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8589
8590       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8591         Res = DAG.getNOT(DL, Res, Res.getValueType());
8592
8593       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8594       if (N2C == 0 || !N2C->isNullValue())
8595         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8596       return Res;
8597     }
8598   }
8599
8600   // Look past (and (setcc_carry (cmp ...)), 1).
8601   if (Cond.getOpcode() == ISD::AND &&
8602       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8603     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8604     if (C && C->getAPIntValue() == 1)
8605       Cond = Cond.getOperand(0);
8606   }
8607
8608   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8609   // setting operand in place of the X86ISD::SETCC.
8610   if (Cond.getOpcode() == X86ISD::SETCC ||
8611       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8612     CC = Cond.getOperand(0);
8613
8614     SDValue Cmp = Cond.getOperand(1);
8615     unsigned Opc = Cmp.getOpcode();
8616     EVT VT = Op.getValueType();
8617
8618     bool IllegalFPCMov = false;
8619     if (VT.isFloatingPoint() && !VT.isVector() &&
8620         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8621       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8622
8623     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8624         Opc == X86ISD::BT) { // FIXME
8625       Cond = Cmp;
8626       addTest = false;
8627     }
8628   }
8629
8630   if (addTest) {
8631     // Look pass the truncate.
8632     if (Cond.getOpcode() == ISD::TRUNCATE)
8633       Cond = Cond.getOperand(0);
8634
8635     // We know the result of AND is compared against zero. Try to match
8636     // it to BT.
8637     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8638       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8639       if (NewSetCC.getNode()) {
8640         CC = NewSetCC.getOperand(0);
8641         Cond = NewSetCC.getOperand(1);
8642         addTest = false;
8643       }
8644     }
8645   }
8646
8647   if (addTest) {
8648     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8649     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8650   }
8651
8652   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8653   // a <  b ?  0 : -1 -> RES = setcc_carry
8654   // a >= b ? -1 :  0 -> RES = setcc_carry
8655   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8656   if (Cond.getOpcode() == X86ISD::CMP) {
8657     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8658
8659     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8660         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8661       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8662                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8663       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8664         return DAG.getNOT(DL, Res, Res.getValueType());
8665       return Res;
8666     }
8667   }
8668
8669   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8670   // condition is true.
8671   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8672   SDValue Ops[] = { Op2, Op1, CC, Cond };
8673   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8674 }
8675
8676 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8677 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8678 // from the AND / OR.
8679 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8680   Opc = Op.getOpcode();
8681   if (Opc != ISD::OR && Opc != ISD::AND)
8682     return false;
8683   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8684           Op.getOperand(0).hasOneUse() &&
8685           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8686           Op.getOperand(1).hasOneUse());
8687 }
8688
8689 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8690 // 1 and that the SETCC node has a single use.
8691 static bool isXor1OfSetCC(SDValue Op) {
8692   if (Op.getOpcode() != ISD::XOR)
8693     return false;
8694   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8695   if (N1C && N1C->getAPIntValue() == 1) {
8696     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8697       Op.getOperand(0).hasOneUse();
8698   }
8699   return false;
8700 }
8701
8702 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8703   bool addTest = true;
8704   SDValue Chain = Op.getOperand(0);
8705   SDValue Cond  = Op.getOperand(1);
8706   SDValue Dest  = Op.getOperand(2);
8707   DebugLoc dl = Op.getDebugLoc();
8708   SDValue CC;
8709
8710   if (Cond.getOpcode() == ISD::SETCC) {
8711     SDValue NewCond = LowerSETCC(Cond, DAG);
8712     if (NewCond.getNode())
8713       Cond = NewCond;
8714   }
8715 #if 0
8716   // FIXME: LowerXALUO doesn't handle these!!
8717   else if (Cond.getOpcode() == X86ISD::ADD  ||
8718            Cond.getOpcode() == X86ISD::SUB  ||
8719            Cond.getOpcode() == X86ISD::SMUL ||
8720            Cond.getOpcode() == X86ISD::UMUL)
8721     Cond = LowerXALUO(Cond, DAG);
8722 #endif
8723
8724   // Look pass (and (setcc_carry (cmp ...)), 1).
8725   if (Cond.getOpcode() == ISD::AND &&
8726       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8727     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8728     if (C && C->getAPIntValue() == 1)
8729       Cond = Cond.getOperand(0);
8730   }
8731
8732   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8733   // setting operand in place of the X86ISD::SETCC.
8734   if (Cond.getOpcode() == X86ISD::SETCC ||
8735       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8736     CC = Cond.getOperand(0);
8737
8738     SDValue Cmp = Cond.getOperand(1);
8739     unsigned Opc = Cmp.getOpcode();
8740     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8741     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8742       Cond = Cmp;
8743       addTest = false;
8744     } else {
8745       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8746       default: break;
8747       case X86::COND_O:
8748       case X86::COND_B:
8749         // These can only come from an arithmetic instruction with overflow,
8750         // e.g. SADDO, UADDO.
8751         Cond = Cond.getNode()->getOperand(1);
8752         addTest = false;
8753         break;
8754       }
8755     }
8756   } else {
8757     unsigned CondOpc;
8758     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8759       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8760       if (CondOpc == ISD::OR) {
8761         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8762         // two branches instead of an explicit OR instruction with a
8763         // separate test.
8764         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8765             isX86LogicalCmp(Cmp)) {
8766           CC = Cond.getOperand(0).getOperand(0);
8767           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8768                               Chain, Dest, CC, Cmp);
8769           CC = Cond.getOperand(1).getOperand(0);
8770           Cond = Cmp;
8771           addTest = false;
8772         }
8773       } else { // ISD::AND
8774         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8775         // two branches instead of an explicit AND instruction with a
8776         // separate test. However, we only do this if this block doesn't
8777         // have a fall-through edge, because this requires an explicit
8778         // jmp when the condition is false.
8779         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8780             isX86LogicalCmp(Cmp) &&
8781             Op.getNode()->hasOneUse()) {
8782           X86::CondCode CCode =
8783             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8784           CCode = X86::GetOppositeBranchCondition(CCode);
8785           CC = DAG.getConstant(CCode, MVT::i8);
8786           SDNode *User = *Op.getNode()->use_begin();
8787           // Look for an unconditional branch following this conditional branch.
8788           // We need this because we need to reverse the successors in order
8789           // to implement FCMP_OEQ.
8790           if (User->getOpcode() == ISD::BR) {
8791             SDValue FalseBB = User->getOperand(1);
8792             SDNode *NewBR =
8793               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8794             assert(NewBR == User);
8795             (void)NewBR;
8796             Dest = FalseBB;
8797
8798             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8799                                 Chain, Dest, CC, Cmp);
8800             X86::CondCode CCode =
8801               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8802             CCode = X86::GetOppositeBranchCondition(CCode);
8803             CC = DAG.getConstant(CCode, MVT::i8);
8804             Cond = Cmp;
8805             addTest = false;
8806           }
8807         }
8808       }
8809     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8810       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8811       // It should be transformed during dag combiner except when the condition
8812       // is set by a arithmetics with overflow node.
8813       X86::CondCode CCode =
8814         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8815       CCode = X86::GetOppositeBranchCondition(CCode);
8816       CC = DAG.getConstant(CCode, MVT::i8);
8817       Cond = Cond.getOperand(0).getOperand(1);
8818       addTest = false;
8819     }
8820   }
8821
8822   if (addTest) {
8823     // Look pass the truncate.
8824     if (Cond.getOpcode() == ISD::TRUNCATE)
8825       Cond = Cond.getOperand(0);
8826
8827     // We know the result of AND is compared against zero. Try to match
8828     // it to BT.
8829     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8830       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8831       if (NewSetCC.getNode()) {
8832         CC = NewSetCC.getOperand(0);
8833         Cond = NewSetCC.getOperand(1);
8834         addTest = false;
8835       }
8836     }
8837   }
8838
8839   if (addTest) {
8840     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8841     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8842   }
8843   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8844                      Chain, Dest, CC, Cond);
8845 }
8846
8847
8848 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8849 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8850 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8851 // that the guard pages used by the OS virtual memory manager are allocated in
8852 // correct sequence.
8853 SDValue
8854 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8855                                            SelectionDAG &DAG) const {
8856   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8857           EnableSegmentedStacks) &&
8858          "This should be used only on Windows targets or when segmented stacks "
8859          "are being used.");
8860   assert(!Subtarget->isTargetEnvMacho());
8861   DebugLoc dl = Op.getDebugLoc();
8862
8863   // Get the inputs.
8864   SDValue Chain = Op.getOperand(0);
8865   SDValue Size  = Op.getOperand(1);
8866   // FIXME: Ensure alignment here
8867
8868   bool Is64Bit = Subtarget->is64Bit();
8869   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8870
8871   if (EnableSegmentedStacks) {
8872     MachineFunction &MF = DAG.getMachineFunction();
8873     MachineRegisterInfo &MRI = MF.getRegInfo();
8874
8875     if (Is64Bit) {
8876       // The 64 bit implementation of segmented stacks needs to clobber both r10
8877       // r11. This makes it impossible to use it along with nested paramenters.
8878       const Function *F = MF.getFunction();
8879
8880       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8881            I != E; I++)
8882         if (I->hasNestAttr())
8883           report_fatal_error("Cannot use segmented stacks with functions that "
8884                              "have nested arguments.");
8885     }
8886
8887     const TargetRegisterClass *AddrRegClass =
8888       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8889     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8890     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8891     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8892                                 DAG.getRegister(Vreg, SPTy));
8893     SDValue Ops1[2] = { Value, Chain };
8894     return DAG.getMergeValues(Ops1, 2, dl);
8895   } else {
8896     SDValue Flag;
8897     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8898
8899     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8900     Flag = Chain.getValue(1);
8901     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8902
8903     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8904     Flag = Chain.getValue(1);
8905
8906     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8907
8908     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8909     return DAG.getMergeValues(Ops1, 2, dl);
8910   }
8911 }
8912
8913 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8914   MachineFunction &MF = DAG.getMachineFunction();
8915   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8916
8917   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8918   DebugLoc DL = Op.getDebugLoc();
8919
8920   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8921     // vastart just stores the address of the VarArgsFrameIndex slot into the
8922     // memory location argument.
8923     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8924                                    getPointerTy());
8925     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8926                         MachinePointerInfo(SV), false, false, 0);
8927   }
8928
8929   // __va_list_tag:
8930   //   gp_offset         (0 - 6 * 8)
8931   //   fp_offset         (48 - 48 + 8 * 16)
8932   //   overflow_arg_area (point to parameters coming in memory).
8933   //   reg_save_area
8934   SmallVector<SDValue, 8> MemOps;
8935   SDValue FIN = Op.getOperand(1);
8936   // Store gp_offset
8937   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8938                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8939                                                MVT::i32),
8940                                FIN, MachinePointerInfo(SV), false, false, 0);
8941   MemOps.push_back(Store);
8942
8943   // Store fp_offset
8944   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8945                     FIN, DAG.getIntPtrConstant(4));
8946   Store = DAG.getStore(Op.getOperand(0), DL,
8947                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8948                                        MVT::i32),
8949                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8950   MemOps.push_back(Store);
8951
8952   // Store ptr to overflow_arg_area
8953   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8954                     FIN, DAG.getIntPtrConstant(4));
8955   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8956                                     getPointerTy());
8957   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8958                        MachinePointerInfo(SV, 8),
8959                        false, false, 0);
8960   MemOps.push_back(Store);
8961
8962   // Store ptr to reg_save_area.
8963   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8964                     FIN, DAG.getIntPtrConstant(8));
8965   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8966                                     getPointerTy());
8967   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8968                        MachinePointerInfo(SV, 16), false, false, 0);
8969   MemOps.push_back(Store);
8970   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8971                      &MemOps[0], MemOps.size());
8972 }
8973
8974 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8975   assert(Subtarget->is64Bit() &&
8976          "LowerVAARG only handles 64-bit va_arg!");
8977   assert((Subtarget->isTargetLinux() ||
8978           Subtarget->isTargetDarwin()) &&
8979           "Unhandled target in LowerVAARG");
8980   assert(Op.getNode()->getNumOperands() == 4);
8981   SDValue Chain = Op.getOperand(0);
8982   SDValue SrcPtr = Op.getOperand(1);
8983   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8984   unsigned Align = Op.getConstantOperandVal(3);
8985   DebugLoc dl = Op.getDebugLoc();
8986
8987   EVT ArgVT = Op.getNode()->getValueType(0);
8988   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8989   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8990   uint8_t ArgMode;
8991
8992   // Decide which area this value should be read from.
8993   // TODO: Implement the AMD64 ABI in its entirety. This simple
8994   // selection mechanism works only for the basic types.
8995   if (ArgVT == MVT::f80) {
8996     llvm_unreachable("va_arg for f80 not yet implemented");
8997   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8998     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8999   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9000     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9001   } else {
9002     llvm_unreachable("Unhandled argument type in LowerVAARG");
9003   }
9004
9005   if (ArgMode == 2) {
9006     // Sanity Check: Make sure using fp_offset makes sense.
9007     assert(!UseSoftFloat &&
9008            !(DAG.getMachineFunction()
9009                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9010            Subtarget->hasXMM());
9011   }
9012
9013   // Insert VAARG_64 node into the DAG
9014   // VAARG_64 returns two values: Variable Argument Address, Chain
9015   SmallVector<SDValue, 11> InstOps;
9016   InstOps.push_back(Chain);
9017   InstOps.push_back(SrcPtr);
9018   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9019   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9020   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9021   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9022   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9023                                           VTs, &InstOps[0], InstOps.size(),
9024                                           MVT::i64,
9025                                           MachinePointerInfo(SV),
9026                                           /*Align=*/0,
9027                                           /*Volatile=*/false,
9028                                           /*ReadMem=*/true,
9029                                           /*WriteMem=*/true);
9030   Chain = VAARG.getValue(1);
9031
9032   // Load the next argument and return it
9033   return DAG.getLoad(ArgVT, dl,
9034                      Chain,
9035                      VAARG,
9036                      MachinePointerInfo(),
9037                      false, false, 0);
9038 }
9039
9040 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9041   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9042   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9043   SDValue Chain = Op.getOperand(0);
9044   SDValue DstPtr = Op.getOperand(1);
9045   SDValue SrcPtr = Op.getOperand(2);
9046   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9047   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9048   DebugLoc DL = Op.getDebugLoc();
9049
9050   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9051                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9052                        false,
9053                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9054 }
9055
9056 SDValue
9057 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9058   DebugLoc dl = Op.getDebugLoc();
9059   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9060   switch (IntNo) {
9061   default: return SDValue();    // Don't custom lower most intrinsics.
9062   // Comparison intrinsics.
9063   case Intrinsic::x86_sse_comieq_ss:
9064   case Intrinsic::x86_sse_comilt_ss:
9065   case Intrinsic::x86_sse_comile_ss:
9066   case Intrinsic::x86_sse_comigt_ss:
9067   case Intrinsic::x86_sse_comige_ss:
9068   case Intrinsic::x86_sse_comineq_ss:
9069   case Intrinsic::x86_sse_ucomieq_ss:
9070   case Intrinsic::x86_sse_ucomilt_ss:
9071   case Intrinsic::x86_sse_ucomile_ss:
9072   case Intrinsic::x86_sse_ucomigt_ss:
9073   case Intrinsic::x86_sse_ucomige_ss:
9074   case Intrinsic::x86_sse_ucomineq_ss:
9075   case Intrinsic::x86_sse2_comieq_sd:
9076   case Intrinsic::x86_sse2_comilt_sd:
9077   case Intrinsic::x86_sse2_comile_sd:
9078   case Intrinsic::x86_sse2_comigt_sd:
9079   case Intrinsic::x86_sse2_comige_sd:
9080   case Intrinsic::x86_sse2_comineq_sd:
9081   case Intrinsic::x86_sse2_ucomieq_sd:
9082   case Intrinsic::x86_sse2_ucomilt_sd:
9083   case Intrinsic::x86_sse2_ucomile_sd:
9084   case Intrinsic::x86_sse2_ucomigt_sd:
9085   case Intrinsic::x86_sse2_ucomige_sd:
9086   case Intrinsic::x86_sse2_ucomineq_sd: {
9087     unsigned Opc = 0;
9088     ISD::CondCode CC = ISD::SETCC_INVALID;
9089     switch (IntNo) {
9090     default: break;
9091     case Intrinsic::x86_sse_comieq_ss:
9092     case Intrinsic::x86_sse2_comieq_sd:
9093       Opc = X86ISD::COMI;
9094       CC = ISD::SETEQ;
9095       break;
9096     case Intrinsic::x86_sse_comilt_ss:
9097     case Intrinsic::x86_sse2_comilt_sd:
9098       Opc = X86ISD::COMI;
9099       CC = ISD::SETLT;
9100       break;
9101     case Intrinsic::x86_sse_comile_ss:
9102     case Intrinsic::x86_sse2_comile_sd:
9103       Opc = X86ISD::COMI;
9104       CC = ISD::SETLE;
9105       break;
9106     case Intrinsic::x86_sse_comigt_ss:
9107     case Intrinsic::x86_sse2_comigt_sd:
9108       Opc = X86ISD::COMI;
9109       CC = ISD::SETGT;
9110       break;
9111     case Intrinsic::x86_sse_comige_ss:
9112     case Intrinsic::x86_sse2_comige_sd:
9113       Opc = X86ISD::COMI;
9114       CC = ISD::SETGE;
9115       break;
9116     case Intrinsic::x86_sse_comineq_ss:
9117     case Intrinsic::x86_sse2_comineq_sd:
9118       Opc = X86ISD::COMI;
9119       CC = ISD::SETNE;
9120       break;
9121     case Intrinsic::x86_sse_ucomieq_ss:
9122     case Intrinsic::x86_sse2_ucomieq_sd:
9123       Opc = X86ISD::UCOMI;
9124       CC = ISD::SETEQ;
9125       break;
9126     case Intrinsic::x86_sse_ucomilt_ss:
9127     case Intrinsic::x86_sse2_ucomilt_sd:
9128       Opc = X86ISD::UCOMI;
9129       CC = ISD::SETLT;
9130       break;
9131     case Intrinsic::x86_sse_ucomile_ss:
9132     case Intrinsic::x86_sse2_ucomile_sd:
9133       Opc = X86ISD::UCOMI;
9134       CC = ISD::SETLE;
9135       break;
9136     case Intrinsic::x86_sse_ucomigt_ss:
9137     case Intrinsic::x86_sse2_ucomigt_sd:
9138       Opc = X86ISD::UCOMI;
9139       CC = ISD::SETGT;
9140       break;
9141     case Intrinsic::x86_sse_ucomige_ss:
9142     case Intrinsic::x86_sse2_ucomige_sd:
9143       Opc = X86ISD::UCOMI;
9144       CC = ISD::SETGE;
9145       break;
9146     case Intrinsic::x86_sse_ucomineq_ss:
9147     case Intrinsic::x86_sse2_ucomineq_sd:
9148       Opc = X86ISD::UCOMI;
9149       CC = ISD::SETNE;
9150       break;
9151     }
9152
9153     SDValue LHS = Op.getOperand(1);
9154     SDValue RHS = Op.getOperand(2);
9155     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9156     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9157     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9158     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9159                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9160     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9161   }
9162   // ptest and testp intrinsics. The intrinsic these come from are designed to
9163   // return an integer value, not just an instruction so lower it to the ptest
9164   // or testp pattern and a setcc for the result.
9165   case Intrinsic::x86_sse41_ptestz:
9166   case Intrinsic::x86_sse41_ptestc:
9167   case Intrinsic::x86_sse41_ptestnzc:
9168   case Intrinsic::x86_avx_ptestz_256:
9169   case Intrinsic::x86_avx_ptestc_256:
9170   case Intrinsic::x86_avx_ptestnzc_256:
9171   case Intrinsic::x86_avx_vtestz_ps:
9172   case Intrinsic::x86_avx_vtestc_ps:
9173   case Intrinsic::x86_avx_vtestnzc_ps:
9174   case Intrinsic::x86_avx_vtestz_pd:
9175   case Intrinsic::x86_avx_vtestc_pd:
9176   case Intrinsic::x86_avx_vtestnzc_pd:
9177   case Intrinsic::x86_avx_vtestz_ps_256:
9178   case Intrinsic::x86_avx_vtestc_ps_256:
9179   case Intrinsic::x86_avx_vtestnzc_ps_256:
9180   case Intrinsic::x86_avx_vtestz_pd_256:
9181   case Intrinsic::x86_avx_vtestc_pd_256:
9182   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9183     bool IsTestPacked = false;
9184     unsigned X86CC = 0;
9185     switch (IntNo) {
9186     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9187     case Intrinsic::x86_avx_vtestz_ps:
9188     case Intrinsic::x86_avx_vtestz_pd:
9189     case Intrinsic::x86_avx_vtestz_ps_256:
9190     case Intrinsic::x86_avx_vtestz_pd_256:
9191       IsTestPacked = true; // Fallthrough
9192     case Intrinsic::x86_sse41_ptestz:
9193     case Intrinsic::x86_avx_ptestz_256:
9194       // ZF = 1
9195       X86CC = X86::COND_E;
9196       break;
9197     case Intrinsic::x86_avx_vtestc_ps:
9198     case Intrinsic::x86_avx_vtestc_pd:
9199     case Intrinsic::x86_avx_vtestc_ps_256:
9200     case Intrinsic::x86_avx_vtestc_pd_256:
9201       IsTestPacked = true; // Fallthrough
9202     case Intrinsic::x86_sse41_ptestc:
9203     case Intrinsic::x86_avx_ptestc_256:
9204       // CF = 1
9205       X86CC = X86::COND_B;
9206       break;
9207     case Intrinsic::x86_avx_vtestnzc_ps:
9208     case Intrinsic::x86_avx_vtestnzc_pd:
9209     case Intrinsic::x86_avx_vtestnzc_ps_256:
9210     case Intrinsic::x86_avx_vtestnzc_pd_256:
9211       IsTestPacked = true; // Fallthrough
9212     case Intrinsic::x86_sse41_ptestnzc:
9213     case Intrinsic::x86_avx_ptestnzc_256:
9214       // ZF and CF = 0
9215       X86CC = X86::COND_A;
9216       break;
9217     }
9218
9219     SDValue LHS = Op.getOperand(1);
9220     SDValue RHS = Op.getOperand(2);
9221     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9222     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9223     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9224     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9225     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9226   }
9227
9228   // Fix vector shift instructions where the last operand is a non-immediate
9229   // i32 value.
9230   case Intrinsic::x86_sse2_pslli_w:
9231   case Intrinsic::x86_sse2_pslli_d:
9232   case Intrinsic::x86_sse2_pslli_q:
9233   case Intrinsic::x86_sse2_psrli_w:
9234   case Intrinsic::x86_sse2_psrli_d:
9235   case Intrinsic::x86_sse2_psrli_q:
9236   case Intrinsic::x86_sse2_psrai_w:
9237   case Intrinsic::x86_sse2_psrai_d:
9238   case Intrinsic::x86_mmx_pslli_w:
9239   case Intrinsic::x86_mmx_pslli_d:
9240   case Intrinsic::x86_mmx_pslli_q:
9241   case Intrinsic::x86_mmx_psrli_w:
9242   case Intrinsic::x86_mmx_psrli_d:
9243   case Intrinsic::x86_mmx_psrli_q:
9244   case Intrinsic::x86_mmx_psrai_w:
9245   case Intrinsic::x86_mmx_psrai_d: {
9246     SDValue ShAmt = Op.getOperand(2);
9247     if (isa<ConstantSDNode>(ShAmt))
9248       return SDValue();
9249
9250     unsigned NewIntNo = 0;
9251     EVT ShAmtVT = MVT::v4i32;
9252     switch (IntNo) {
9253     case Intrinsic::x86_sse2_pslli_w:
9254       NewIntNo = Intrinsic::x86_sse2_psll_w;
9255       break;
9256     case Intrinsic::x86_sse2_pslli_d:
9257       NewIntNo = Intrinsic::x86_sse2_psll_d;
9258       break;
9259     case Intrinsic::x86_sse2_pslli_q:
9260       NewIntNo = Intrinsic::x86_sse2_psll_q;
9261       break;
9262     case Intrinsic::x86_sse2_psrli_w:
9263       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9264       break;
9265     case Intrinsic::x86_sse2_psrli_d:
9266       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9267       break;
9268     case Intrinsic::x86_sse2_psrli_q:
9269       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9270       break;
9271     case Intrinsic::x86_sse2_psrai_w:
9272       NewIntNo = Intrinsic::x86_sse2_psra_w;
9273       break;
9274     case Intrinsic::x86_sse2_psrai_d:
9275       NewIntNo = Intrinsic::x86_sse2_psra_d;
9276       break;
9277     default: {
9278       ShAmtVT = MVT::v2i32;
9279       switch (IntNo) {
9280       case Intrinsic::x86_mmx_pslli_w:
9281         NewIntNo = Intrinsic::x86_mmx_psll_w;
9282         break;
9283       case Intrinsic::x86_mmx_pslli_d:
9284         NewIntNo = Intrinsic::x86_mmx_psll_d;
9285         break;
9286       case Intrinsic::x86_mmx_pslli_q:
9287         NewIntNo = Intrinsic::x86_mmx_psll_q;
9288         break;
9289       case Intrinsic::x86_mmx_psrli_w:
9290         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9291         break;
9292       case Intrinsic::x86_mmx_psrli_d:
9293         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9294         break;
9295       case Intrinsic::x86_mmx_psrli_q:
9296         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9297         break;
9298       case Intrinsic::x86_mmx_psrai_w:
9299         NewIntNo = Intrinsic::x86_mmx_psra_w;
9300         break;
9301       case Intrinsic::x86_mmx_psrai_d:
9302         NewIntNo = Intrinsic::x86_mmx_psra_d;
9303         break;
9304       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9305       }
9306       break;
9307     }
9308     }
9309
9310     // The vector shift intrinsics with scalars uses 32b shift amounts but
9311     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9312     // to be zero.
9313     SDValue ShOps[4];
9314     ShOps[0] = ShAmt;
9315     ShOps[1] = DAG.getConstant(0, MVT::i32);
9316     if (ShAmtVT == MVT::v4i32) {
9317       ShOps[2] = DAG.getUNDEF(MVT::i32);
9318       ShOps[3] = DAG.getUNDEF(MVT::i32);
9319       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9320     } else {
9321       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9322 // FIXME this must be lowered to get rid of the invalid type.
9323     }
9324
9325     EVT VT = Op.getValueType();
9326     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9327     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9328                        DAG.getConstant(NewIntNo, MVT::i32),
9329                        Op.getOperand(1), ShAmt);
9330   }
9331   }
9332 }
9333
9334 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9335                                            SelectionDAG &DAG) const {
9336   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9337   MFI->setReturnAddressIsTaken(true);
9338
9339   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9340   DebugLoc dl = Op.getDebugLoc();
9341
9342   if (Depth > 0) {
9343     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9344     SDValue Offset =
9345       DAG.getConstant(TD->getPointerSize(),
9346                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9347     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9348                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9349                                    FrameAddr, Offset),
9350                        MachinePointerInfo(), false, false, 0);
9351   }
9352
9353   // Just load the return address.
9354   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9355   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9356                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9357 }
9358
9359 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9360   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9361   MFI->setFrameAddressIsTaken(true);
9362
9363   EVT VT = Op.getValueType();
9364   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9365   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9366   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9367   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9368   while (Depth--)
9369     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9370                             MachinePointerInfo(),
9371                             false, false, 0);
9372   return FrameAddr;
9373 }
9374
9375 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9376                                                      SelectionDAG &DAG) const {
9377   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9378 }
9379
9380 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9381   MachineFunction &MF = DAG.getMachineFunction();
9382   SDValue Chain     = Op.getOperand(0);
9383   SDValue Offset    = Op.getOperand(1);
9384   SDValue Handler   = Op.getOperand(2);
9385   DebugLoc dl       = Op.getDebugLoc();
9386
9387   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9388                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9389                                      getPointerTy());
9390   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9391
9392   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9393                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9394   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9395   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9396                        false, false, 0);
9397   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9398   MF.getRegInfo().addLiveOut(StoreAddrReg);
9399
9400   return DAG.getNode(X86ISD::EH_RETURN, dl,
9401                      MVT::Other,
9402                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9403 }
9404
9405 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
9406                                              SelectionDAG &DAG) const {
9407   SDValue Root = Op.getOperand(0);
9408   SDValue Trmp = Op.getOperand(1); // trampoline
9409   SDValue FPtr = Op.getOperand(2); // nested function
9410   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9411   DebugLoc dl  = Op.getDebugLoc();
9412
9413   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9414
9415   if (Subtarget->is64Bit()) {
9416     SDValue OutChains[6];
9417
9418     // Large code-model.
9419     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9420     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9421
9422     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9423     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9424
9425     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9426
9427     // Load the pointer to the nested function into R11.
9428     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9429     SDValue Addr = Trmp;
9430     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9431                                 Addr, MachinePointerInfo(TrmpAddr),
9432                                 false, false, 0);
9433
9434     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9435                        DAG.getConstant(2, MVT::i64));
9436     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9437                                 MachinePointerInfo(TrmpAddr, 2),
9438                                 false, false, 2);
9439
9440     // Load the 'nest' parameter value into R10.
9441     // R10 is specified in X86CallingConv.td
9442     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9443     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9444                        DAG.getConstant(10, MVT::i64));
9445     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9446                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9447                                 false, false, 0);
9448
9449     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9450                        DAG.getConstant(12, MVT::i64));
9451     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9452                                 MachinePointerInfo(TrmpAddr, 12),
9453                                 false, false, 2);
9454
9455     // Jump to the nested function.
9456     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9457     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9458                        DAG.getConstant(20, MVT::i64));
9459     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9460                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9461                                 false, false, 0);
9462
9463     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9464     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9465                        DAG.getConstant(22, MVT::i64));
9466     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9467                                 MachinePointerInfo(TrmpAddr, 22),
9468                                 false, false, 0);
9469
9470     SDValue Ops[] =
9471       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
9472     return DAG.getMergeValues(Ops, 2, dl);
9473   } else {
9474     const Function *Func =
9475       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9476     CallingConv::ID CC = Func->getCallingConv();
9477     unsigned NestReg;
9478
9479     switch (CC) {
9480     default:
9481       llvm_unreachable("Unsupported calling convention");
9482     case CallingConv::C:
9483     case CallingConv::X86_StdCall: {
9484       // Pass 'nest' parameter in ECX.
9485       // Must be kept in sync with X86CallingConv.td
9486       NestReg = X86::ECX;
9487
9488       // Check that ECX wasn't needed by an 'inreg' parameter.
9489       FunctionType *FTy = Func->getFunctionType();
9490       const AttrListPtr &Attrs = Func->getAttributes();
9491
9492       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9493         unsigned InRegCount = 0;
9494         unsigned Idx = 1;
9495
9496         for (FunctionType::param_iterator I = FTy->param_begin(),
9497              E = FTy->param_end(); I != E; ++I, ++Idx)
9498           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9499             // FIXME: should only count parameters that are lowered to integers.
9500             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9501
9502         if (InRegCount > 2) {
9503           report_fatal_error("Nest register in use - reduce number of inreg"
9504                              " parameters!");
9505         }
9506       }
9507       break;
9508     }
9509     case CallingConv::X86_FastCall:
9510     case CallingConv::X86_ThisCall:
9511     case CallingConv::Fast:
9512       // Pass 'nest' parameter in EAX.
9513       // Must be kept in sync with X86CallingConv.td
9514       NestReg = X86::EAX;
9515       break;
9516     }
9517
9518     SDValue OutChains[4];
9519     SDValue Addr, Disp;
9520
9521     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9522                        DAG.getConstant(10, MVT::i32));
9523     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9524
9525     // This is storing the opcode for MOV32ri.
9526     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9527     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9528     OutChains[0] = DAG.getStore(Root, dl,
9529                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9530                                 Trmp, MachinePointerInfo(TrmpAddr),
9531                                 false, false, 0);
9532
9533     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9534                        DAG.getConstant(1, MVT::i32));
9535     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9536                                 MachinePointerInfo(TrmpAddr, 1),
9537                                 false, false, 1);
9538
9539     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9540     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9541                        DAG.getConstant(5, MVT::i32));
9542     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9543                                 MachinePointerInfo(TrmpAddr, 5),
9544                                 false, false, 1);
9545
9546     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9547                        DAG.getConstant(6, MVT::i32));
9548     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9549                                 MachinePointerInfo(TrmpAddr, 6),
9550                                 false, false, 1);
9551
9552     SDValue Ops[] =
9553       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
9554     return DAG.getMergeValues(Ops, 2, dl);
9555   }
9556 }
9557
9558 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9559                                             SelectionDAG &DAG) const {
9560   /*
9561    The rounding mode is in bits 11:10 of FPSR, and has the following
9562    settings:
9563      00 Round to nearest
9564      01 Round to -inf
9565      10 Round to +inf
9566      11 Round to 0
9567
9568   FLT_ROUNDS, on the other hand, expects the following:
9569     -1 Undefined
9570      0 Round to 0
9571      1 Round to nearest
9572      2 Round to +inf
9573      3 Round to -inf
9574
9575   To perform the conversion, we do:
9576     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9577   */
9578
9579   MachineFunction &MF = DAG.getMachineFunction();
9580   const TargetMachine &TM = MF.getTarget();
9581   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9582   unsigned StackAlignment = TFI.getStackAlignment();
9583   EVT VT = Op.getValueType();
9584   DebugLoc DL = Op.getDebugLoc();
9585
9586   // Save FP Control Word to stack slot
9587   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9588   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9589
9590
9591   MachineMemOperand *MMO =
9592    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9593                            MachineMemOperand::MOStore, 2, 2);
9594
9595   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9596   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9597                                           DAG.getVTList(MVT::Other),
9598                                           Ops, 2, MVT::i16, MMO);
9599
9600   // Load FP Control Word from stack slot
9601   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9602                             MachinePointerInfo(), false, false, 0);
9603
9604   // Transform as necessary
9605   SDValue CWD1 =
9606     DAG.getNode(ISD::SRL, DL, MVT::i16,
9607                 DAG.getNode(ISD::AND, DL, MVT::i16,
9608                             CWD, DAG.getConstant(0x800, MVT::i16)),
9609                 DAG.getConstant(11, MVT::i8));
9610   SDValue CWD2 =
9611     DAG.getNode(ISD::SRL, DL, MVT::i16,
9612                 DAG.getNode(ISD::AND, DL, MVT::i16,
9613                             CWD, DAG.getConstant(0x400, MVT::i16)),
9614                 DAG.getConstant(9, MVT::i8));
9615
9616   SDValue RetVal =
9617     DAG.getNode(ISD::AND, DL, MVT::i16,
9618                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9619                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9620                             DAG.getConstant(1, MVT::i16)),
9621                 DAG.getConstant(3, MVT::i16));
9622
9623
9624   return DAG.getNode((VT.getSizeInBits() < 16 ?
9625                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9626 }
9627
9628 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9629   EVT VT = Op.getValueType();
9630   EVT OpVT = VT;
9631   unsigned NumBits = VT.getSizeInBits();
9632   DebugLoc dl = Op.getDebugLoc();
9633
9634   Op = Op.getOperand(0);
9635   if (VT == MVT::i8) {
9636     // Zero extend to i32 since there is not an i8 bsr.
9637     OpVT = MVT::i32;
9638     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9639   }
9640
9641   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9642   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9643   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9644
9645   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9646   SDValue Ops[] = {
9647     Op,
9648     DAG.getConstant(NumBits+NumBits-1, OpVT),
9649     DAG.getConstant(X86::COND_E, MVT::i8),
9650     Op.getValue(1)
9651   };
9652   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9653
9654   // Finally xor with NumBits-1.
9655   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9656
9657   if (VT == MVT::i8)
9658     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9659   return Op;
9660 }
9661
9662 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9663   EVT VT = Op.getValueType();
9664   EVT OpVT = VT;
9665   unsigned NumBits = VT.getSizeInBits();
9666   DebugLoc dl = Op.getDebugLoc();
9667
9668   Op = Op.getOperand(0);
9669   if (VT == MVT::i8) {
9670     OpVT = MVT::i32;
9671     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9672   }
9673
9674   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9675   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9676   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9677
9678   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9679   SDValue Ops[] = {
9680     Op,
9681     DAG.getConstant(NumBits, OpVT),
9682     DAG.getConstant(X86::COND_E, MVT::i8),
9683     Op.getValue(1)
9684   };
9685   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9686
9687   if (VT == MVT::i8)
9688     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9689   return Op;
9690 }
9691
9692 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9693 // ones, and then concatenate the result back.
9694 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9695   EVT VT = Op.getValueType();
9696
9697   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9698          "Unsupported value type for operation");
9699
9700   int NumElems = VT.getVectorNumElements();
9701   DebugLoc dl = Op.getDebugLoc();
9702   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9703   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9704
9705   // Extract the LHS vectors
9706   SDValue LHS = Op.getOperand(0);
9707   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9708   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9709
9710   // Extract the RHS vectors
9711   SDValue RHS = Op.getOperand(1);
9712   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9713   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9714
9715   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9716   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9717
9718   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9719                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9720                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9721 }
9722
9723 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9724   assert(Op.getValueType().getSizeInBits() == 256 &&
9725          Op.getValueType().isInteger() &&
9726          "Only handle AVX 256-bit vector integer operation");
9727   return Lower256IntArith(Op, DAG);
9728 }
9729
9730 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9731   assert(Op.getValueType().getSizeInBits() == 256 &&
9732          Op.getValueType().isInteger() &&
9733          "Only handle AVX 256-bit vector integer operation");
9734   return Lower256IntArith(Op, DAG);
9735 }
9736
9737 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9738   EVT VT = Op.getValueType();
9739
9740   // Decompose 256-bit ops into smaller 128-bit ops.
9741   if (VT.getSizeInBits() == 256)
9742     return Lower256IntArith(Op, DAG);
9743
9744   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9745   DebugLoc dl = Op.getDebugLoc();
9746
9747   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9748   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9749   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9750   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9751   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9752   //
9753   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9754   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9755   //  return AloBlo + AloBhi + AhiBlo;
9756
9757   SDValue A = Op.getOperand(0);
9758   SDValue B = Op.getOperand(1);
9759
9760   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9761                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9762                        A, DAG.getConstant(32, MVT::i32));
9763   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9764                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9765                        B, DAG.getConstant(32, MVT::i32));
9766   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9767                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9768                        A, B);
9769   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9770                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9771                        A, Bhi);
9772   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9773                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9774                        Ahi, B);
9775   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9776                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9777                        AloBhi, DAG.getConstant(32, MVT::i32));
9778   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9779                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9780                        AhiBlo, DAG.getConstant(32, MVT::i32));
9781   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9782   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9783   return Res;
9784 }
9785
9786 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9787
9788   EVT VT = Op.getValueType();
9789   DebugLoc dl = Op.getDebugLoc();
9790   SDValue R = Op.getOperand(0);
9791   SDValue Amt = Op.getOperand(1);
9792   LLVMContext *Context = DAG.getContext();
9793
9794   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9795     return SDValue();
9796
9797   // Decompose 256-bit shifts into smaller 128-bit shifts.
9798   if (VT.getSizeInBits() == 256) {
9799     int NumElems = VT.getVectorNumElements();
9800     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9801     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9802
9803     // Extract the two vectors
9804     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9805     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9806                                      DAG, dl);
9807
9808     // Recreate the shift amount vectors
9809     SDValue Amt1, Amt2;
9810     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9811       // Constant shift amount
9812       SmallVector<SDValue, 4> Amt1Csts;
9813       SmallVector<SDValue, 4> Amt2Csts;
9814       for (int i = 0; i < NumElems/2; ++i)
9815         Amt1Csts.push_back(Amt->getOperand(i));
9816       for (int i = NumElems/2; i < NumElems; ++i)
9817         Amt2Csts.push_back(Amt->getOperand(i));
9818
9819       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9820                                  &Amt1Csts[0], NumElems/2);
9821       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9822                                  &Amt2Csts[0], NumElems/2);
9823     } else {
9824       // Variable shift amount
9825       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9826       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9827                                  DAG, dl);
9828     }
9829
9830     // Issue new vector shifts for the smaller types
9831     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9832     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9833
9834     // Concatenate the result back
9835     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9836   }
9837
9838   // Optimize shl/srl/sra with constant shift amount.
9839   if (isSplatVector(Amt.getNode())) {
9840     SDValue SclrAmt = Amt->getOperand(0);
9841     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9842       uint64_t ShiftAmt = C->getZExtValue();
9843
9844       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9845        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9846                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9847                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9848
9849       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9850        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9851                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9852                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9853
9854       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9855        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9856                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9857                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9858
9859       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9860        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9861                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9862                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9863
9864       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9865        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9866                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9867                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9868
9869       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9870        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9871                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9872                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9873
9874       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9875        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9876                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9877                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9878
9879       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9880        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9881                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9882                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9883     }
9884   }
9885
9886   // Lower SHL with variable shift amount.
9887   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9888     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9889                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9890                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9891
9892     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9893
9894     std::vector<Constant*> CV(4, CI);
9895     Constant *C = ConstantVector::get(CV);
9896     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9897     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9898                                  MachinePointerInfo::getConstantPool(),
9899                                  false, false, 16);
9900
9901     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9902     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9903     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9904     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9905   }
9906   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9907     // a = a << 5;
9908     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9909                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9910                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9911
9912     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9913     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9914
9915     std::vector<Constant*> CVM1(16, CM1);
9916     std::vector<Constant*> CVM2(16, CM2);
9917     Constant *C = ConstantVector::get(CVM1);
9918     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9919     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9920                             MachinePointerInfo::getConstantPool(),
9921                             false, false, 16);
9922
9923     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9924     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9925     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9926                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9927                     DAG.getConstant(4, MVT::i32));
9928     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9929     // a += a
9930     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9931
9932     C = ConstantVector::get(CVM2);
9933     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9934     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9935                     MachinePointerInfo::getConstantPool(),
9936                     false, false, 16);
9937
9938     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9939     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9940     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9941                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9942                     DAG.getConstant(2, MVT::i32));
9943     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9944     // a += a
9945     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9946
9947     // return pblendv(r, r+r, a);
9948     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9949                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9950     return R;
9951   }
9952   return SDValue();
9953 }
9954
9955 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9956   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9957   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9958   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9959   // has only one use.
9960   SDNode *N = Op.getNode();
9961   SDValue LHS = N->getOperand(0);
9962   SDValue RHS = N->getOperand(1);
9963   unsigned BaseOp = 0;
9964   unsigned Cond = 0;
9965   DebugLoc DL = Op.getDebugLoc();
9966   switch (Op.getOpcode()) {
9967   default: llvm_unreachable("Unknown ovf instruction!");
9968   case ISD::SADDO:
9969     // A subtract of one will be selected as a INC. Note that INC doesn't
9970     // set CF, so we can't do this for UADDO.
9971     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9972       if (C->isOne()) {
9973         BaseOp = X86ISD::INC;
9974         Cond = X86::COND_O;
9975         break;
9976       }
9977     BaseOp = X86ISD::ADD;
9978     Cond = X86::COND_O;
9979     break;
9980   case ISD::UADDO:
9981     BaseOp = X86ISD::ADD;
9982     Cond = X86::COND_B;
9983     break;
9984   case ISD::SSUBO:
9985     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9986     // set CF, so we can't do this for USUBO.
9987     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9988       if (C->isOne()) {
9989         BaseOp = X86ISD::DEC;
9990         Cond = X86::COND_O;
9991         break;
9992       }
9993     BaseOp = X86ISD::SUB;
9994     Cond = X86::COND_O;
9995     break;
9996   case ISD::USUBO:
9997     BaseOp = X86ISD::SUB;
9998     Cond = X86::COND_B;
9999     break;
10000   case ISD::SMULO:
10001     BaseOp = X86ISD::SMUL;
10002     Cond = X86::COND_O;
10003     break;
10004   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10005     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10006                                  MVT::i32);
10007     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10008
10009     SDValue SetCC =
10010       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10011                   DAG.getConstant(X86::COND_O, MVT::i32),
10012                   SDValue(Sum.getNode(), 2));
10013
10014     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10015   }
10016   }
10017
10018   // Also sets EFLAGS.
10019   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10020   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10021
10022   SDValue SetCC =
10023     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10024                 DAG.getConstant(Cond, MVT::i32),
10025                 SDValue(Sum.getNode(), 1));
10026
10027   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10028 }
10029
10030 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10031   DebugLoc dl = Op.getDebugLoc();
10032   SDNode* Node = Op.getNode();
10033   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10034   EVT VT = Node->getValueType(0);
10035
10036   if (Subtarget->hasSSE2() && VT.isVector()) {
10037     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10038                         ExtraVT.getScalarType().getSizeInBits();
10039     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10040
10041     unsigned SHLIntrinsicsID = 0;
10042     unsigned SRAIntrinsicsID = 0;
10043     switch (VT.getSimpleVT().SimpleTy) {
10044       default:
10045         return SDValue();
10046       case MVT::v2i64: {
10047         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10048         SRAIntrinsicsID = 0;
10049         break;
10050       }
10051       case MVT::v4i32: {
10052         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10053         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10054         break;
10055       }
10056       case MVT::v8i16: {
10057         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10058         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10059         break;
10060       }
10061     }
10062
10063     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10064                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10065                          Node->getOperand(0), ShAmt);
10066
10067     // In case of 1 bit sext, no need to shr
10068     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10069
10070     if (SRAIntrinsicsID) {
10071       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10072                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10073                          Tmp1, ShAmt);
10074     }
10075     return Tmp1;
10076   }
10077
10078   return SDValue();
10079 }
10080
10081
10082 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10083   DebugLoc dl = Op.getDebugLoc();
10084
10085   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10086   // There isn't any reason to disable it if the target processor supports it.
10087   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10088     SDValue Chain = Op.getOperand(0);
10089     SDValue Zero = DAG.getConstant(0, MVT::i32);
10090     SDValue Ops[] = {
10091       DAG.getRegister(X86::ESP, MVT::i32), // Base
10092       DAG.getTargetConstant(1, MVT::i8),   // Scale
10093       DAG.getRegister(0, MVT::i32),        // Index
10094       DAG.getTargetConstant(0, MVT::i32),  // Disp
10095       DAG.getRegister(0, MVT::i32),        // Segment.
10096       Zero,
10097       Chain
10098     };
10099     SDNode *Res =
10100       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10101                           array_lengthof(Ops));
10102     return SDValue(Res, 0);
10103   }
10104
10105   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10106   if (!isDev)
10107     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10108
10109   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10110   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10111   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10112   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10113
10114   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10115   if (!Op1 && !Op2 && !Op3 && Op4)
10116     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10117
10118   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10119   if (Op1 && !Op2 && !Op3 && !Op4)
10120     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10121
10122   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10123   //           (MFENCE)>;
10124   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10125 }
10126
10127 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10128                                              SelectionDAG &DAG) const {
10129   DebugLoc dl = Op.getDebugLoc();
10130   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10131     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10132   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10133     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10134
10135   // The only fence that needs an instruction is a sequentially-consistent
10136   // cross-thread fence.
10137   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10138     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10139     // no-sse2). There isn't any reason to disable it if the target processor
10140     // supports it.
10141     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10142       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10143
10144     SDValue Chain = Op.getOperand(0);
10145     SDValue Zero = DAG.getConstant(0, MVT::i32);
10146     SDValue Ops[] = {
10147       DAG.getRegister(X86::ESP, MVT::i32), // Base
10148       DAG.getTargetConstant(1, MVT::i8),   // Scale
10149       DAG.getRegister(0, MVT::i32),        // Index
10150       DAG.getTargetConstant(0, MVT::i32),  // Disp
10151       DAG.getRegister(0, MVT::i32),        // Segment.
10152       Zero,
10153       Chain
10154     };
10155     SDNode *Res =
10156       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10157                          array_lengthof(Ops));
10158     return SDValue(Res, 0);
10159   }
10160
10161   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10162   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10163 }
10164
10165
10166 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10167   EVT T = Op.getValueType();
10168   DebugLoc DL = Op.getDebugLoc();
10169   unsigned Reg = 0;
10170   unsigned size = 0;
10171   switch(T.getSimpleVT().SimpleTy) {
10172   default:
10173     assert(false && "Invalid value type!");
10174   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10175   case MVT::i16: Reg = X86::AX;  size = 2; break;
10176   case MVT::i32: Reg = X86::EAX; size = 4; break;
10177   case MVT::i64:
10178     assert(Subtarget->is64Bit() && "Node not type legal!");
10179     Reg = X86::RAX; size = 8;
10180     break;
10181   }
10182   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10183                                     Op.getOperand(2), SDValue());
10184   SDValue Ops[] = { cpIn.getValue(0),
10185                     Op.getOperand(1),
10186                     Op.getOperand(3),
10187                     DAG.getTargetConstant(size, MVT::i8),
10188                     cpIn.getValue(1) };
10189   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10190   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10191   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10192                                            Ops, 5, T, MMO);
10193   SDValue cpOut =
10194     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10195   return cpOut;
10196 }
10197
10198 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10199                                                  SelectionDAG &DAG) const {
10200   assert(Subtarget->is64Bit() && "Result not type legalized?");
10201   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10202   SDValue TheChain = Op.getOperand(0);
10203   DebugLoc dl = Op.getDebugLoc();
10204   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10205   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10206   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10207                                    rax.getValue(2));
10208   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10209                             DAG.getConstant(32, MVT::i8));
10210   SDValue Ops[] = {
10211     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10212     rdx.getValue(1)
10213   };
10214   return DAG.getMergeValues(Ops, 2, dl);
10215 }
10216
10217 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10218                                             SelectionDAG &DAG) const {
10219   EVT SrcVT = Op.getOperand(0).getValueType();
10220   EVT DstVT = Op.getValueType();
10221   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10222          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10223   assert((DstVT == MVT::i64 ||
10224           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10225          "Unexpected custom BITCAST");
10226   // i64 <=> MMX conversions are Legal.
10227   if (SrcVT==MVT::i64 && DstVT.isVector())
10228     return Op;
10229   if (DstVT==MVT::i64 && SrcVT.isVector())
10230     return Op;
10231   // MMX <=> MMX conversions are Legal.
10232   if (SrcVT.isVector() && DstVT.isVector())
10233     return Op;
10234   // All other conversions need to be expanded.
10235   return SDValue();
10236 }
10237
10238 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10239   SDNode *Node = Op.getNode();
10240   DebugLoc dl = Node->getDebugLoc();
10241   EVT T = Node->getValueType(0);
10242   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10243                               DAG.getConstant(0, T), Node->getOperand(2));
10244   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10245                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10246                        Node->getOperand(0),
10247                        Node->getOperand(1), negOp,
10248                        cast<AtomicSDNode>(Node)->getSrcValue(),
10249                        cast<AtomicSDNode>(Node)->getAlignment(),
10250                        cast<AtomicSDNode>(Node)->getOrdering(),
10251                        cast<AtomicSDNode>(Node)->getSynchScope());
10252 }
10253
10254 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10255   SDNode *Node = Op.getNode();
10256   DebugLoc dl = Node->getDebugLoc();
10257   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10258
10259   // Convert seq_cst store -> xchg
10260   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10261   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10262   //        (The only way to get a 16-byte store is cmpxchg16b)
10263   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10264   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10265       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10266     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10267                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10268                                  Node->getOperand(0),
10269                                  Node->getOperand(1), Node->getOperand(2),
10270                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10271                                  cast<AtomicSDNode>(Node)->getOrdering(),
10272                                  cast<AtomicSDNode>(Node)->getSynchScope());
10273     return Swap.getValue(1);
10274   }
10275   // Other atomic stores have a simple pattern.
10276   return Op;
10277 }
10278
10279 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10280   EVT VT = Op.getNode()->getValueType(0);
10281
10282   // Let legalize expand this if it isn't a legal type yet.
10283   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10284     return SDValue();
10285
10286   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10287
10288   unsigned Opc;
10289   bool ExtraOp = false;
10290   switch (Op.getOpcode()) {
10291   default: assert(0 && "Invalid code");
10292   case ISD::ADDC: Opc = X86ISD::ADD; break;
10293   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10294   case ISD::SUBC: Opc = X86ISD::SUB; break;
10295   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10296   }
10297
10298   if (!ExtraOp)
10299     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10300                        Op.getOperand(1));
10301   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10302                      Op.getOperand(1), Op.getOperand(2));
10303 }
10304
10305 /// LowerOperation - Provide custom lowering hooks for some operations.
10306 ///
10307 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10308   switch (Op.getOpcode()) {
10309   default: llvm_unreachable("Should not custom lower this!");
10310   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10311   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10312   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10313   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10314   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10315   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10316   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10317   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10318   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10319   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10320   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10321   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10322   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10323   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10324   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10325   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10326   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10327   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10328   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10329   case ISD::SHL_PARTS:
10330   case ISD::SRA_PARTS:
10331   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10332   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10333   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10334   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10335   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10336   case ISD::FABS:               return LowerFABS(Op, DAG);
10337   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10338   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10339   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10340   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10341   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
10342   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10343   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10344   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10345   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10346   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10347   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10348   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10349   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10350   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10351   case ISD::FRAME_TO_ARGS_OFFSET:
10352                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10353   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10354   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10355   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
10356   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10357   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10358   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10359   case ISD::MUL:                return LowerMUL(Op, DAG);
10360   case ISD::SRA:
10361   case ISD::SRL:
10362   case ISD::SHL:                return LowerShift(Op, DAG);
10363   case ISD::SADDO:
10364   case ISD::UADDO:
10365   case ISD::SSUBO:
10366   case ISD::USUBO:
10367   case ISD::SMULO:
10368   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10369   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10370   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10371   case ISD::ADDC:
10372   case ISD::ADDE:
10373   case ISD::SUBC:
10374   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10375   case ISD::ADD:                return LowerADD(Op, DAG);
10376   case ISD::SUB:                return LowerSUB(Op, DAG);
10377   }
10378 }
10379
10380 static void ReplaceATOMIC_LOAD(SDNode *Node,
10381                                   SmallVectorImpl<SDValue> &Results,
10382                                   SelectionDAG &DAG) {
10383   DebugLoc dl = Node->getDebugLoc();
10384   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10385
10386   // Convert wide load -> cmpxchg8b/cmpxchg16b
10387   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10388   //        (The only way to get a 16-byte load is cmpxchg16b)
10389   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10390   SDValue Zero = DAG.getConstant(0, VT);
10391   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10392                                Node->getOperand(0),
10393                                Node->getOperand(1), Zero, Zero,
10394                                cast<AtomicSDNode>(Node)->getMemOperand(),
10395                                cast<AtomicSDNode>(Node)->getOrdering(),
10396                                cast<AtomicSDNode>(Node)->getSynchScope());
10397   Results.push_back(Swap.getValue(0));
10398   Results.push_back(Swap.getValue(1));
10399 }
10400
10401 void X86TargetLowering::
10402 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10403                         SelectionDAG &DAG, unsigned NewOp) const {
10404   EVT T = Node->getValueType(0);
10405   DebugLoc dl = Node->getDebugLoc();
10406   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10407
10408   SDValue Chain = Node->getOperand(0);
10409   SDValue In1 = Node->getOperand(1);
10410   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10411                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10412   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10413                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10414   SDValue Ops[] = { Chain, In1, In2L, In2H };
10415   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10416   SDValue Result =
10417     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10418                             cast<MemSDNode>(Node)->getMemOperand());
10419   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10420   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10421   Results.push_back(Result.getValue(2));
10422 }
10423
10424 /// ReplaceNodeResults - Replace a node with an illegal result type
10425 /// with a new node built out of custom code.
10426 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10427                                            SmallVectorImpl<SDValue>&Results,
10428                                            SelectionDAG &DAG) const {
10429   DebugLoc dl = N->getDebugLoc();
10430   switch (N->getOpcode()) {
10431   default:
10432     assert(false && "Do not know how to custom type legalize this operation!");
10433     return;
10434   case ISD::SIGN_EXTEND_INREG:
10435   case ISD::ADDC:
10436   case ISD::ADDE:
10437   case ISD::SUBC:
10438   case ISD::SUBE:
10439     // We don't want to expand or promote these.
10440     return;
10441   case ISD::FP_TO_SINT: {
10442     std::pair<SDValue,SDValue> Vals =
10443         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10444     SDValue FIST = Vals.first, StackSlot = Vals.second;
10445     if (FIST.getNode() != 0) {
10446       EVT VT = N->getValueType(0);
10447       // Return a load from the stack slot.
10448       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10449                                     MachinePointerInfo(), false, false, 0));
10450     }
10451     return;
10452   }
10453   case ISD::READCYCLECOUNTER: {
10454     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10455     SDValue TheChain = N->getOperand(0);
10456     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10457     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10458                                      rd.getValue(1));
10459     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10460                                      eax.getValue(2));
10461     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10462     SDValue Ops[] = { eax, edx };
10463     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10464     Results.push_back(edx.getValue(1));
10465     return;
10466   }
10467   case ISD::ATOMIC_CMP_SWAP: {
10468     EVT T = N->getValueType(0);
10469     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10470     bool Regs64bit = T == MVT::i128;
10471     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10472     SDValue cpInL, cpInH;
10473     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10474                         DAG.getConstant(0, HalfT));
10475     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10476                         DAG.getConstant(1, HalfT));
10477     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10478                              Regs64bit ? X86::RAX : X86::EAX,
10479                              cpInL, SDValue());
10480     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10481                              Regs64bit ? X86::RDX : X86::EDX,
10482                              cpInH, cpInL.getValue(1));
10483     SDValue swapInL, swapInH;
10484     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10485                           DAG.getConstant(0, HalfT));
10486     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10487                           DAG.getConstant(1, HalfT));
10488     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10489                                Regs64bit ? X86::RBX : X86::EBX,
10490                                swapInL, cpInH.getValue(1));
10491     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10492                                Regs64bit ? X86::RCX : X86::ECX, 
10493                                swapInH, swapInL.getValue(1));
10494     SDValue Ops[] = { swapInH.getValue(0),
10495                       N->getOperand(1),
10496                       swapInH.getValue(1) };
10497     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10498     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10499     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10500                                   X86ISD::LCMPXCHG8_DAG;
10501     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10502                                              Ops, 3, T, MMO);
10503     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10504                                         Regs64bit ? X86::RAX : X86::EAX,
10505                                         HalfT, Result.getValue(1));
10506     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10507                                         Regs64bit ? X86::RDX : X86::EDX,
10508                                         HalfT, cpOutL.getValue(2));
10509     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10510     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10511     Results.push_back(cpOutH.getValue(1));
10512     return;
10513   }
10514   case ISD::ATOMIC_LOAD_ADD:
10515     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10516     return;
10517   case ISD::ATOMIC_LOAD_AND:
10518     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10519     return;
10520   case ISD::ATOMIC_LOAD_NAND:
10521     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10522     return;
10523   case ISD::ATOMIC_LOAD_OR:
10524     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10525     return;
10526   case ISD::ATOMIC_LOAD_SUB:
10527     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10528     return;
10529   case ISD::ATOMIC_LOAD_XOR:
10530     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10531     return;
10532   case ISD::ATOMIC_SWAP:
10533     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10534     return;
10535   case ISD::ATOMIC_LOAD:
10536     ReplaceATOMIC_LOAD(N, Results, DAG);
10537   }
10538 }
10539
10540 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10541   switch (Opcode) {
10542   default: return NULL;
10543   case X86ISD::BSF:                return "X86ISD::BSF";
10544   case X86ISD::BSR:                return "X86ISD::BSR";
10545   case X86ISD::SHLD:               return "X86ISD::SHLD";
10546   case X86ISD::SHRD:               return "X86ISD::SHRD";
10547   case X86ISD::FAND:               return "X86ISD::FAND";
10548   case X86ISD::FOR:                return "X86ISD::FOR";
10549   case X86ISD::FXOR:               return "X86ISD::FXOR";
10550   case X86ISD::FSRL:               return "X86ISD::FSRL";
10551   case X86ISD::FILD:               return "X86ISD::FILD";
10552   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10553   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10554   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10555   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10556   case X86ISD::FLD:                return "X86ISD::FLD";
10557   case X86ISD::FST:                return "X86ISD::FST";
10558   case X86ISD::CALL:               return "X86ISD::CALL";
10559   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10560   case X86ISD::BT:                 return "X86ISD::BT";
10561   case X86ISD::CMP:                return "X86ISD::CMP";
10562   case X86ISD::COMI:               return "X86ISD::COMI";
10563   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10564   case X86ISD::SETCC:              return "X86ISD::SETCC";
10565   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10566   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10567   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10568   case X86ISD::CMOV:               return "X86ISD::CMOV";
10569   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10570   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10571   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10572   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10573   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10574   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10575   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10576   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10577   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10578   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10579   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10580   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10581   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10582   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10583   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10584   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10585   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10586   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
10587   case X86ISD::FMAX:               return "X86ISD::FMAX";
10588   case X86ISD::FMIN:               return "X86ISD::FMIN";
10589   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10590   case X86ISD::FRCP:               return "X86ISD::FRCP";
10591   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10592   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10593   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10594   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10595   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10596   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10597   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10598   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10599   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10600   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10601   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10602   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10603   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10604   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10605   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10606   case X86ISD::VSHL:               return "X86ISD::VSHL";
10607   case X86ISD::VSRL:               return "X86ISD::VSRL";
10608   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10609   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10610   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10611   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10612   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10613   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10614   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10615   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10616   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10617   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10618   case X86ISD::ADD:                return "X86ISD::ADD";
10619   case X86ISD::SUB:                return "X86ISD::SUB";
10620   case X86ISD::ADC:                return "X86ISD::ADC";
10621   case X86ISD::SBB:                return "X86ISD::SBB";
10622   case X86ISD::SMUL:               return "X86ISD::SMUL";
10623   case X86ISD::UMUL:               return "X86ISD::UMUL";
10624   case X86ISD::INC:                return "X86ISD::INC";
10625   case X86ISD::DEC:                return "X86ISD::DEC";
10626   case X86ISD::OR:                 return "X86ISD::OR";
10627   case X86ISD::XOR:                return "X86ISD::XOR";
10628   case X86ISD::AND:                return "X86ISD::AND";
10629   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10630   case X86ISD::PTEST:              return "X86ISD::PTEST";
10631   case X86ISD::TESTP:              return "X86ISD::TESTP";
10632   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10633   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10634   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10635   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10636   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10637   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10638   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10639   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10640   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10641   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10642   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10643   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10644   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10645   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10646   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10647   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10648   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10649   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10650   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10651   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10652   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10653   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10654   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10655   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10656   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10657   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10658   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10659   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10660   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10661   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10662   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10663   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10664   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10665   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10666   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10667   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10668   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10669   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10670   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10671   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10672   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10673   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10674   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10675   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10676   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10677   }
10678 }
10679
10680 // isLegalAddressingMode - Return true if the addressing mode represented
10681 // by AM is legal for this target, for a load/store of the specified type.
10682 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10683                                               Type *Ty) const {
10684   // X86 supports extremely general addressing modes.
10685   CodeModel::Model M = getTargetMachine().getCodeModel();
10686   Reloc::Model R = getTargetMachine().getRelocationModel();
10687
10688   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10689   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10690     return false;
10691
10692   if (AM.BaseGV) {
10693     unsigned GVFlags =
10694       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10695
10696     // If a reference to this global requires an extra load, we can't fold it.
10697     if (isGlobalStubReference(GVFlags))
10698       return false;
10699
10700     // If BaseGV requires a register for the PIC base, we cannot also have a
10701     // BaseReg specified.
10702     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10703       return false;
10704
10705     // If lower 4G is not available, then we must use rip-relative addressing.
10706     if ((M != CodeModel::Small || R != Reloc::Static) &&
10707         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10708       return false;
10709   }
10710
10711   switch (AM.Scale) {
10712   case 0:
10713   case 1:
10714   case 2:
10715   case 4:
10716   case 8:
10717     // These scales always work.
10718     break;
10719   case 3:
10720   case 5:
10721   case 9:
10722     // These scales are formed with basereg+scalereg.  Only accept if there is
10723     // no basereg yet.
10724     if (AM.HasBaseReg)
10725       return false;
10726     break;
10727   default:  // Other stuff never works.
10728     return false;
10729   }
10730
10731   return true;
10732 }
10733
10734
10735 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10736   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10737     return false;
10738   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10739   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10740   if (NumBits1 <= NumBits2)
10741     return false;
10742   return true;
10743 }
10744
10745 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10746   if (!VT1.isInteger() || !VT2.isInteger())
10747     return false;
10748   unsigned NumBits1 = VT1.getSizeInBits();
10749   unsigned NumBits2 = VT2.getSizeInBits();
10750   if (NumBits1 <= NumBits2)
10751     return false;
10752   return true;
10753 }
10754
10755 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10756   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10757   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10758 }
10759
10760 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10761   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10762   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10763 }
10764
10765 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10766   // i16 instructions are longer (0x66 prefix) and potentially slower.
10767   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10768 }
10769
10770 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10771 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10772 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10773 /// are assumed to be legal.
10774 bool
10775 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10776                                       EVT VT) const {
10777   // Very little shuffling can be done for 64-bit vectors right now.
10778   if (VT.getSizeInBits() == 64)
10779     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10780
10781   // FIXME: pshufb, blends, shifts.
10782   return (VT.getVectorNumElements() == 2 ||
10783           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10784           isMOVLMask(M, VT) ||
10785           isSHUFPMask(M, VT) ||
10786           isPSHUFDMask(M, VT) ||
10787           isPSHUFHWMask(M, VT) ||
10788           isPSHUFLWMask(M, VT) ||
10789           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10790           isUNPCKLMask(M, VT) ||
10791           isUNPCKHMask(M, VT) ||
10792           isUNPCKL_v_undef_Mask(M, VT) ||
10793           isUNPCKH_v_undef_Mask(M, VT));
10794 }
10795
10796 bool
10797 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10798                                           EVT VT) const {
10799   unsigned NumElts = VT.getVectorNumElements();
10800   // FIXME: This collection of masks seems suspect.
10801   if (NumElts == 2)
10802     return true;
10803   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10804     return (isMOVLMask(Mask, VT)  ||
10805             isCommutedMOVLMask(Mask, VT, true) ||
10806             isSHUFPMask(Mask, VT) ||
10807             isCommutedSHUFPMask(Mask, VT));
10808   }
10809   return false;
10810 }
10811
10812 //===----------------------------------------------------------------------===//
10813 //                           X86 Scheduler Hooks
10814 //===----------------------------------------------------------------------===//
10815
10816 // private utility function
10817 MachineBasicBlock *
10818 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10819                                                        MachineBasicBlock *MBB,
10820                                                        unsigned regOpc,
10821                                                        unsigned immOpc,
10822                                                        unsigned LoadOpc,
10823                                                        unsigned CXchgOpc,
10824                                                        unsigned notOpc,
10825                                                        unsigned EAXreg,
10826                                                        TargetRegisterClass *RC,
10827                                                        bool invSrc) const {
10828   // For the atomic bitwise operator, we generate
10829   //   thisMBB:
10830   //   newMBB:
10831   //     ld  t1 = [bitinstr.addr]
10832   //     op  t2 = t1, [bitinstr.val]
10833   //     mov EAX = t1
10834   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10835   //     bz  newMBB
10836   //     fallthrough -->nextMBB
10837   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10838   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10839   MachineFunction::iterator MBBIter = MBB;
10840   ++MBBIter;
10841
10842   /// First build the CFG
10843   MachineFunction *F = MBB->getParent();
10844   MachineBasicBlock *thisMBB = MBB;
10845   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10846   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10847   F->insert(MBBIter, newMBB);
10848   F->insert(MBBIter, nextMBB);
10849
10850   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10851   nextMBB->splice(nextMBB->begin(), thisMBB,
10852                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10853                   thisMBB->end());
10854   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10855
10856   // Update thisMBB to fall through to newMBB
10857   thisMBB->addSuccessor(newMBB);
10858
10859   // newMBB jumps to itself and fall through to nextMBB
10860   newMBB->addSuccessor(nextMBB);
10861   newMBB->addSuccessor(newMBB);
10862
10863   // Insert instructions into newMBB based on incoming instruction
10864   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10865          "unexpected number of operands");
10866   DebugLoc dl = bInstr->getDebugLoc();
10867   MachineOperand& destOper = bInstr->getOperand(0);
10868   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10869   int numArgs = bInstr->getNumOperands() - 1;
10870   for (int i=0; i < numArgs; ++i)
10871     argOpers[i] = &bInstr->getOperand(i+1);
10872
10873   // x86 address has 4 operands: base, index, scale, and displacement
10874   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10875   int valArgIndx = lastAddrIndx + 1;
10876
10877   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10878   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10879   for (int i=0; i <= lastAddrIndx; ++i)
10880     (*MIB).addOperand(*argOpers[i]);
10881
10882   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10883   if (invSrc) {
10884     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10885   }
10886   else
10887     tt = t1;
10888
10889   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10890   assert((argOpers[valArgIndx]->isReg() ||
10891           argOpers[valArgIndx]->isImm()) &&
10892          "invalid operand");
10893   if (argOpers[valArgIndx]->isReg())
10894     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10895   else
10896     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10897   MIB.addReg(tt);
10898   (*MIB).addOperand(*argOpers[valArgIndx]);
10899
10900   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10901   MIB.addReg(t1);
10902
10903   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10904   for (int i=0; i <= lastAddrIndx; ++i)
10905     (*MIB).addOperand(*argOpers[i]);
10906   MIB.addReg(t2);
10907   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10908   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10909                     bInstr->memoperands_end());
10910
10911   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10912   MIB.addReg(EAXreg);
10913
10914   // insert branch
10915   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10916
10917   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10918   return nextMBB;
10919 }
10920
10921 // private utility function:  64 bit atomics on 32 bit host.
10922 MachineBasicBlock *
10923 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10924                                                        MachineBasicBlock *MBB,
10925                                                        unsigned regOpcL,
10926                                                        unsigned regOpcH,
10927                                                        unsigned immOpcL,
10928                                                        unsigned immOpcH,
10929                                                        bool invSrc) const {
10930   // For the atomic bitwise operator, we generate
10931   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10932   //     ld t1,t2 = [bitinstr.addr]
10933   //   newMBB:
10934   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10935   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10936   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10937   //     mov ECX, EBX <- t5, t6
10938   //     mov EAX, EDX <- t1, t2
10939   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10940   //     mov t3, t4 <- EAX, EDX
10941   //     bz  newMBB
10942   //     result in out1, out2
10943   //     fallthrough -->nextMBB
10944
10945   const TargetRegisterClass *RC = X86::GR32RegisterClass;
10946   const unsigned LoadOpc = X86::MOV32rm;
10947   const unsigned NotOpc = X86::NOT32r;
10948   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10949   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10950   MachineFunction::iterator MBBIter = MBB;
10951   ++MBBIter;
10952
10953   /// First build the CFG
10954   MachineFunction *F = MBB->getParent();
10955   MachineBasicBlock *thisMBB = MBB;
10956   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10957   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10958   F->insert(MBBIter, newMBB);
10959   F->insert(MBBIter, nextMBB);
10960
10961   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10962   nextMBB->splice(nextMBB->begin(), thisMBB,
10963                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10964                   thisMBB->end());
10965   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10966
10967   // Update thisMBB to fall through to newMBB
10968   thisMBB->addSuccessor(newMBB);
10969
10970   // newMBB jumps to itself and fall through to nextMBB
10971   newMBB->addSuccessor(nextMBB);
10972   newMBB->addSuccessor(newMBB);
10973
10974   DebugLoc dl = bInstr->getDebugLoc();
10975   // Insert instructions into newMBB based on incoming instruction
10976   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10977   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10978          "unexpected number of operands");
10979   MachineOperand& dest1Oper = bInstr->getOperand(0);
10980   MachineOperand& dest2Oper = bInstr->getOperand(1);
10981   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10982   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10983     argOpers[i] = &bInstr->getOperand(i+2);
10984
10985     // We use some of the operands multiple times, so conservatively just
10986     // clear any kill flags that might be present.
10987     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10988       argOpers[i]->setIsKill(false);
10989   }
10990
10991   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10992   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10993
10994   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10995   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10996   for (int i=0; i <= lastAddrIndx; ++i)
10997     (*MIB).addOperand(*argOpers[i]);
10998   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10999   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11000   // add 4 to displacement.
11001   for (int i=0; i <= lastAddrIndx-2; ++i)
11002     (*MIB).addOperand(*argOpers[i]);
11003   MachineOperand newOp3 = *(argOpers[3]);
11004   if (newOp3.isImm())
11005     newOp3.setImm(newOp3.getImm()+4);
11006   else
11007     newOp3.setOffset(newOp3.getOffset()+4);
11008   (*MIB).addOperand(newOp3);
11009   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11010
11011   // t3/4 are defined later, at the bottom of the loop
11012   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11013   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11014   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11015     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11016   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11017     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11018
11019   // The subsequent operations should be using the destination registers of
11020   //the PHI instructions.
11021   if (invSrc) {
11022     t1 = F->getRegInfo().createVirtualRegister(RC);
11023     t2 = F->getRegInfo().createVirtualRegister(RC);
11024     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11025     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11026   } else {
11027     t1 = dest1Oper.getReg();
11028     t2 = dest2Oper.getReg();
11029   }
11030
11031   int valArgIndx = lastAddrIndx + 1;
11032   assert((argOpers[valArgIndx]->isReg() ||
11033           argOpers[valArgIndx]->isImm()) &&
11034          "invalid operand");
11035   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11036   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11037   if (argOpers[valArgIndx]->isReg())
11038     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11039   else
11040     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11041   if (regOpcL != X86::MOV32rr)
11042     MIB.addReg(t1);
11043   (*MIB).addOperand(*argOpers[valArgIndx]);
11044   assert(argOpers[valArgIndx + 1]->isReg() ==
11045          argOpers[valArgIndx]->isReg());
11046   assert(argOpers[valArgIndx + 1]->isImm() ==
11047          argOpers[valArgIndx]->isImm());
11048   if (argOpers[valArgIndx + 1]->isReg())
11049     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11050   else
11051     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11052   if (regOpcH != X86::MOV32rr)
11053     MIB.addReg(t2);
11054   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11055
11056   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11057   MIB.addReg(t1);
11058   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11059   MIB.addReg(t2);
11060
11061   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11062   MIB.addReg(t5);
11063   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11064   MIB.addReg(t6);
11065
11066   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11067   for (int i=0; i <= lastAddrIndx; ++i)
11068     (*MIB).addOperand(*argOpers[i]);
11069
11070   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11071   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11072                     bInstr->memoperands_end());
11073
11074   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11075   MIB.addReg(X86::EAX);
11076   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11077   MIB.addReg(X86::EDX);
11078
11079   // insert branch
11080   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11081
11082   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11083   return nextMBB;
11084 }
11085
11086 // private utility function
11087 MachineBasicBlock *
11088 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11089                                                       MachineBasicBlock *MBB,
11090                                                       unsigned cmovOpc) const {
11091   // For the atomic min/max operator, we generate
11092   //   thisMBB:
11093   //   newMBB:
11094   //     ld t1 = [min/max.addr]
11095   //     mov t2 = [min/max.val]
11096   //     cmp  t1, t2
11097   //     cmov[cond] t2 = t1
11098   //     mov EAX = t1
11099   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11100   //     bz   newMBB
11101   //     fallthrough -->nextMBB
11102   //
11103   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11104   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11105   MachineFunction::iterator MBBIter = MBB;
11106   ++MBBIter;
11107
11108   /// First build the CFG
11109   MachineFunction *F = MBB->getParent();
11110   MachineBasicBlock *thisMBB = MBB;
11111   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11112   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11113   F->insert(MBBIter, newMBB);
11114   F->insert(MBBIter, nextMBB);
11115
11116   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11117   nextMBB->splice(nextMBB->begin(), thisMBB,
11118                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11119                   thisMBB->end());
11120   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11121
11122   // Update thisMBB to fall through to newMBB
11123   thisMBB->addSuccessor(newMBB);
11124
11125   // newMBB jumps to newMBB and fall through to nextMBB
11126   newMBB->addSuccessor(nextMBB);
11127   newMBB->addSuccessor(newMBB);
11128
11129   DebugLoc dl = mInstr->getDebugLoc();
11130   // Insert instructions into newMBB based on incoming instruction
11131   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11132          "unexpected number of operands");
11133   MachineOperand& destOper = mInstr->getOperand(0);
11134   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11135   int numArgs = mInstr->getNumOperands() - 1;
11136   for (int i=0; i < numArgs; ++i)
11137     argOpers[i] = &mInstr->getOperand(i+1);
11138
11139   // x86 address has 4 operands: base, index, scale, and displacement
11140   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11141   int valArgIndx = lastAddrIndx + 1;
11142
11143   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11144   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11145   for (int i=0; i <= lastAddrIndx; ++i)
11146     (*MIB).addOperand(*argOpers[i]);
11147
11148   // We only support register and immediate values
11149   assert((argOpers[valArgIndx]->isReg() ||
11150           argOpers[valArgIndx]->isImm()) &&
11151          "invalid operand");
11152
11153   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11154   if (argOpers[valArgIndx]->isReg())
11155     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11156   else
11157     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11158   (*MIB).addOperand(*argOpers[valArgIndx]);
11159
11160   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11161   MIB.addReg(t1);
11162
11163   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11164   MIB.addReg(t1);
11165   MIB.addReg(t2);
11166
11167   // Generate movc
11168   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11169   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11170   MIB.addReg(t2);
11171   MIB.addReg(t1);
11172
11173   // Cmp and exchange if none has modified the memory location
11174   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11175   for (int i=0; i <= lastAddrIndx; ++i)
11176     (*MIB).addOperand(*argOpers[i]);
11177   MIB.addReg(t3);
11178   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11179   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11180                     mInstr->memoperands_end());
11181
11182   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11183   MIB.addReg(X86::EAX);
11184
11185   // insert branch
11186   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11187
11188   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11189   return nextMBB;
11190 }
11191
11192 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11193 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11194 // in the .td file.
11195 MachineBasicBlock *
11196 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11197                             unsigned numArgs, bool memArg) const {
11198   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11199          "Target must have SSE4.2 or AVX features enabled");
11200
11201   DebugLoc dl = MI->getDebugLoc();
11202   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11203   unsigned Opc;
11204   if (!Subtarget->hasAVX()) {
11205     if (memArg)
11206       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11207     else
11208       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11209   } else {
11210     if (memArg)
11211       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11212     else
11213       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11214   }
11215
11216   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11217   for (unsigned i = 0; i < numArgs; ++i) {
11218     MachineOperand &Op = MI->getOperand(i+1);
11219     if (!(Op.isReg() && Op.isImplicit()))
11220       MIB.addOperand(Op);
11221   }
11222   BuildMI(*BB, MI, dl,
11223     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11224              MI->getOperand(0).getReg())
11225     .addReg(X86::XMM0);
11226
11227   MI->eraseFromParent();
11228   return BB;
11229 }
11230
11231 MachineBasicBlock *
11232 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11233   DebugLoc dl = MI->getDebugLoc();
11234   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11235
11236   // Address into RAX/EAX, other two args into ECX, EDX.
11237   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11238   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11239   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11240   for (int i = 0; i < X86::AddrNumOperands; ++i)
11241     MIB.addOperand(MI->getOperand(i));
11242
11243   unsigned ValOps = X86::AddrNumOperands;
11244   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11245     .addReg(MI->getOperand(ValOps).getReg());
11246   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11247     .addReg(MI->getOperand(ValOps+1).getReg());
11248
11249   // The instruction doesn't actually take any operands though.
11250   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11251
11252   MI->eraseFromParent(); // The pseudo is gone now.
11253   return BB;
11254 }
11255
11256 MachineBasicBlock *
11257 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11258   DebugLoc dl = MI->getDebugLoc();
11259   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11260
11261   // First arg in ECX, the second in EAX.
11262   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11263     .addReg(MI->getOperand(0).getReg());
11264   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11265     .addReg(MI->getOperand(1).getReg());
11266
11267   // The instruction doesn't actually take any operands though.
11268   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11269
11270   MI->eraseFromParent(); // The pseudo is gone now.
11271   return BB;
11272 }
11273
11274 MachineBasicBlock *
11275 X86TargetLowering::EmitVAARG64WithCustomInserter(
11276                    MachineInstr *MI,
11277                    MachineBasicBlock *MBB) const {
11278   // Emit va_arg instruction on X86-64.
11279
11280   // Operands to this pseudo-instruction:
11281   // 0  ) Output        : destination address (reg)
11282   // 1-5) Input         : va_list address (addr, i64mem)
11283   // 6  ) ArgSize       : Size (in bytes) of vararg type
11284   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11285   // 8  ) Align         : Alignment of type
11286   // 9  ) EFLAGS (implicit-def)
11287
11288   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11289   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11290
11291   unsigned DestReg = MI->getOperand(0).getReg();
11292   MachineOperand &Base = MI->getOperand(1);
11293   MachineOperand &Scale = MI->getOperand(2);
11294   MachineOperand &Index = MI->getOperand(3);
11295   MachineOperand &Disp = MI->getOperand(4);
11296   MachineOperand &Segment = MI->getOperand(5);
11297   unsigned ArgSize = MI->getOperand(6).getImm();
11298   unsigned ArgMode = MI->getOperand(7).getImm();
11299   unsigned Align = MI->getOperand(8).getImm();
11300
11301   // Memory Reference
11302   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11303   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11304   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11305
11306   // Machine Information
11307   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11308   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11309   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11310   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11311   DebugLoc DL = MI->getDebugLoc();
11312
11313   // struct va_list {
11314   //   i32   gp_offset
11315   //   i32   fp_offset
11316   //   i64   overflow_area (address)
11317   //   i64   reg_save_area (address)
11318   // }
11319   // sizeof(va_list) = 24
11320   // alignment(va_list) = 8
11321
11322   unsigned TotalNumIntRegs = 6;
11323   unsigned TotalNumXMMRegs = 8;
11324   bool UseGPOffset = (ArgMode == 1);
11325   bool UseFPOffset = (ArgMode == 2);
11326   unsigned MaxOffset = TotalNumIntRegs * 8 +
11327                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11328
11329   /* Align ArgSize to a multiple of 8 */
11330   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11331   bool NeedsAlign = (Align > 8);
11332
11333   MachineBasicBlock *thisMBB = MBB;
11334   MachineBasicBlock *overflowMBB;
11335   MachineBasicBlock *offsetMBB;
11336   MachineBasicBlock *endMBB;
11337
11338   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11339   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11340   unsigned OffsetReg = 0;
11341
11342   if (!UseGPOffset && !UseFPOffset) {
11343     // If we only pull from the overflow region, we don't create a branch.
11344     // We don't need to alter control flow.
11345     OffsetDestReg = 0; // unused
11346     OverflowDestReg = DestReg;
11347
11348     offsetMBB = NULL;
11349     overflowMBB = thisMBB;
11350     endMBB = thisMBB;
11351   } else {
11352     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11353     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11354     // If not, pull from overflow_area. (branch to overflowMBB)
11355     //
11356     //       thisMBB
11357     //         |     .
11358     //         |        .
11359     //     offsetMBB   overflowMBB
11360     //         |        .
11361     //         |     .
11362     //        endMBB
11363
11364     // Registers for the PHI in endMBB
11365     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11366     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11367
11368     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11369     MachineFunction *MF = MBB->getParent();
11370     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11371     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11372     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11373
11374     MachineFunction::iterator MBBIter = MBB;
11375     ++MBBIter;
11376
11377     // Insert the new basic blocks
11378     MF->insert(MBBIter, offsetMBB);
11379     MF->insert(MBBIter, overflowMBB);
11380     MF->insert(MBBIter, endMBB);
11381
11382     // Transfer the remainder of MBB and its successor edges to endMBB.
11383     endMBB->splice(endMBB->begin(), thisMBB,
11384                     llvm::next(MachineBasicBlock::iterator(MI)),
11385                     thisMBB->end());
11386     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11387
11388     // Make offsetMBB and overflowMBB successors of thisMBB
11389     thisMBB->addSuccessor(offsetMBB);
11390     thisMBB->addSuccessor(overflowMBB);
11391
11392     // endMBB is a successor of both offsetMBB and overflowMBB
11393     offsetMBB->addSuccessor(endMBB);
11394     overflowMBB->addSuccessor(endMBB);
11395
11396     // Load the offset value into a register
11397     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11398     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11399       .addOperand(Base)
11400       .addOperand(Scale)
11401       .addOperand(Index)
11402       .addDisp(Disp, UseFPOffset ? 4 : 0)
11403       .addOperand(Segment)
11404       .setMemRefs(MMOBegin, MMOEnd);
11405
11406     // Check if there is enough room left to pull this argument.
11407     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11408       .addReg(OffsetReg)
11409       .addImm(MaxOffset + 8 - ArgSizeA8);
11410
11411     // Branch to "overflowMBB" if offset >= max
11412     // Fall through to "offsetMBB" otherwise
11413     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11414       .addMBB(overflowMBB);
11415   }
11416
11417   // In offsetMBB, emit code to use the reg_save_area.
11418   if (offsetMBB) {
11419     assert(OffsetReg != 0);
11420
11421     // Read the reg_save_area address.
11422     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11423     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11424       .addOperand(Base)
11425       .addOperand(Scale)
11426       .addOperand(Index)
11427       .addDisp(Disp, 16)
11428       .addOperand(Segment)
11429       .setMemRefs(MMOBegin, MMOEnd);
11430
11431     // Zero-extend the offset
11432     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11433       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11434         .addImm(0)
11435         .addReg(OffsetReg)
11436         .addImm(X86::sub_32bit);
11437
11438     // Add the offset to the reg_save_area to get the final address.
11439     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11440       .addReg(OffsetReg64)
11441       .addReg(RegSaveReg);
11442
11443     // Compute the offset for the next argument
11444     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11445     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11446       .addReg(OffsetReg)
11447       .addImm(UseFPOffset ? 16 : 8);
11448
11449     // Store it back into the va_list.
11450     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11451       .addOperand(Base)
11452       .addOperand(Scale)
11453       .addOperand(Index)
11454       .addDisp(Disp, UseFPOffset ? 4 : 0)
11455       .addOperand(Segment)
11456       .addReg(NextOffsetReg)
11457       .setMemRefs(MMOBegin, MMOEnd);
11458
11459     // Jump to endMBB
11460     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11461       .addMBB(endMBB);
11462   }
11463
11464   //
11465   // Emit code to use overflow area
11466   //
11467
11468   // Load the overflow_area address into a register.
11469   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11470   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11471     .addOperand(Base)
11472     .addOperand(Scale)
11473     .addOperand(Index)
11474     .addDisp(Disp, 8)
11475     .addOperand(Segment)
11476     .setMemRefs(MMOBegin, MMOEnd);
11477
11478   // If we need to align it, do so. Otherwise, just copy the address
11479   // to OverflowDestReg.
11480   if (NeedsAlign) {
11481     // Align the overflow address
11482     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11483     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11484
11485     // aligned_addr = (addr + (align-1)) & ~(align-1)
11486     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11487       .addReg(OverflowAddrReg)
11488       .addImm(Align-1);
11489
11490     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11491       .addReg(TmpReg)
11492       .addImm(~(uint64_t)(Align-1));
11493   } else {
11494     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11495       .addReg(OverflowAddrReg);
11496   }
11497
11498   // Compute the next overflow address after this argument.
11499   // (the overflow address should be kept 8-byte aligned)
11500   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11501   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11502     .addReg(OverflowDestReg)
11503     .addImm(ArgSizeA8);
11504
11505   // Store the new overflow address.
11506   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11507     .addOperand(Base)
11508     .addOperand(Scale)
11509     .addOperand(Index)
11510     .addDisp(Disp, 8)
11511     .addOperand(Segment)
11512     .addReg(NextAddrReg)
11513     .setMemRefs(MMOBegin, MMOEnd);
11514
11515   // If we branched, emit the PHI to the front of endMBB.
11516   if (offsetMBB) {
11517     BuildMI(*endMBB, endMBB->begin(), DL,
11518             TII->get(X86::PHI), DestReg)
11519       .addReg(OffsetDestReg).addMBB(offsetMBB)
11520       .addReg(OverflowDestReg).addMBB(overflowMBB);
11521   }
11522
11523   // Erase the pseudo instruction
11524   MI->eraseFromParent();
11525
11526   return endMBB;
11527 }
11528
11529 MachineBasicBlock *
11530 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11531                                                  MachineInstr *MI,
11532                                                  MachineBasicBlock *MBB) const {
11533   // Emit code to save XMM registers to the stack. The ABI says that the
11534   // number of registers to save is given in %al, so it's theoretically
11535   // possible to do an indirect jump trick to avoid saving all of them,
11536   // however this code takes a simpler approach and just executes all
11537   // of the stores if %al is non-zero. It's less code, and it's probably
11538   // easier on the hardware branch predictor, and stores aren't all that
11539   // expensive anyway.
11540
11541   // Create the new basic blocks. One block contains all the XMM stores,
11542   // and one block is the final destination regardless of whether any
11543   // stores were performed.
11544   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11545   MachineFunction *F = MBB->getParent();
11546   MachineFunction::iterator MBBIter = MBB;
11547   ++MBBIter;
11548   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11549   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11550   F->insert(MBBIter, XMMSaveMBB);
11551   F->insert(MBBIter, EndMBB);
11552
11553   // Transfer the remainder of MBB and its successor edges to EndMBB.
11554   EndMBB->splice(EndMBB->begin(), MBB,
11555                  llvm::next(MachineBasicBlock::iterator(MI)),
11556                  MBB->end());
11557   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11558
11559   // The original block will now fall through to the XMM save block.
11560   MBB->addSuccessor(XMMSaveMBB);
11561   // The XMMSaveMBB will fall through to the end block.
11562   XMMSaveMBB->addSuccessor(EndMBB);
11563
11564   // Now add the instructions.
11565   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11566   DebugLoc DL = MI->getDebugLoc();
11567
11568   unsigned CountReg = MI->getOperand(0).getReg();
11569   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11570   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11571
11572   if (!Subtarget->isTargetWin64()) {
11573     // If %al is 0, branch around the XMM save block.
11574     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11575     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11576     MBB->addSuccessor(EndMBB);
11577   }
11578
11579   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11580   // In the XMM save block, save all the XMM argument registers.
11581   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11582     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11583     MachineMemOperand *MMO =
11584       F->getMachineMemOperand(
11585           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11586         MachineMemOperand::MOStore,
11587         /*Size=*/16, /*Align=*/16);
11588     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11589       .addFrameIndex(RegSaveFrameIndex)
11590       .addImm(/*Scale=*/1)
11591       .addReg(/*IndexReg=*/0)
11592       .addImm(/*Disp=*/Offset)
11593       .addReg(/*Segment=*/0)
11594       .addReg(MI->getOperand(i).getReg())
11595       .addMemOperand(MMO);
11596   }
11597
11598   MI->eraseFromParent();   // The pseudo instruction is gone now.
11599
11600   return EndMBB;
11601 }
11602
11603 MachineBasicBlock *
11604 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11605                                      MachineBasicBlock *BB) const {
11606   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11607   DebugLoc DL = MI->getDebugLoc();
11608
11609   // To "insert" a SELECT_CC instruction, we actually have to insert the
11610   // diamond control-flow pattern.  The incoming instruction knows the
11611   // destination vreg to set, the condition code register to branch on, the
11612   // true/false values to select between, and a branch opcode to use.
11613   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11614   MachineFunction::iterator It = BB;
11615   ++It;
11616
11617   //  thisMBB:
11618   //  ...
11619   //   TrueVal = ...
11620   //   cmpTY ccX, r1, r2
11621   //   bCC copy1MBB
11622   //   fallthrough --> copy0MBB
11623   MachineBasicBlock *thisMBB = BB;
11624   MachineFunction *F = BB->getParent();
11625   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11626   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11627   F->insert(It, copy0MBB);
11628   F->insert(It, sinkMBB);
11629
11630   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11631   // live into the sink and copy blocks.
11632   const MachineFunction *MF = BB->getParent();
11633   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
11634   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
11635
11636   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
11637     const MachineOperand &MO = MI->getOperand(I);
11638     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
11639     unsigned Reg = MO.getReg();
11640     if (Reg != X86::EFLAGS) continue;
11641     copy0MBB->addLiveIn(Reg);
11642     sinkMBB->addLiveIn(Reg);
11643   }
11644
11645   // Transfer the remainder of BB and its successor edges to sinkMBB.
11646   sinkMBB->splice(sinkMBB->begin(), BB,
11647                   llvm::next(MachineBasicBlock::iterator(MI)),
11648                   BB->end());
11649   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11650
11651   // Add the true and fallthrough blocks as its successors.
11652   BB->addSuccessor(copy0MBB);
11653   BB->addSuccessor(sinkMBB);
11654
11655   // Create the conditional branch instruction.
11656   unsigned Opc =
11657     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11658   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11659
11660   //  copy0MBB:
11661   //   %FalseValue = ...
11662   //   # fallthrough to sinkMBB
11663   copy0MBB->addSuccessor(sinkMBB);
11664
11665   //  sinkMBB:
11666   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11667   //  ...
11668   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11669           TII->get(X86::PHI), MI->getOperand(0).getReg())
11670     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11671     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11672
11673   MI->eraseFromParent();   // The pseudo instruction is gone now.
11674   return sinkMBB;
11675 }
11676
11677 MachineBasicBlock *
11678 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11679                                         bool Is64Bit) const {
11680   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11681   DebugLoc DL = MI->getDebugLoc();
11682   MachineFunction *MF = BB->getParent();
11683   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11684
11685   assert(EnableSegmentedStacks);
11686
11687   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11688   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11689
11690   // BB:
11691   //  ... [Till the alloca]
11692   // If stacklet is not large enough, jump to mallocMBB
11693   //
11694   // bumpMBB:
11695   //  Allocate by subtracting from RSP
11696   //  Jump to continueMBB
11697   //
11698   // mallocMBB:
11699   //  Allocate by call to runtime
11700   //
11701   // continueMBB:
11702   //  ...
11703   //  [rest of original BB]
11704   //
11705
11706   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11707   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11708   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11709
11710   MachineRegisterInfo &MRI = MF->getRegInfo();
11711   const TargetRegisterClass *AddrRegClass =
11712     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11713
11714   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11715     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11716     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11717     sizeVReg = MI->getOperand(1).getReg(),
11718     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11719
11720   MachineFunction::iterator MBBIter = BB;
11721   ++MBBIter;
11722
11723   MF->insert(MBBIter, bumpMBB);
11724   MF->insert(MBBIter, mallocMBB);
11725   MF->insert(MBBIter, continueMBB);
11726
11727   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11728                       (MachineBasicBlock::iterator(MI)), BB->end());
11729   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11730
11731   // Add code to the main basic block to check if the stack limit has been hit,
11732   // and if so, jump to mallocMBB otherwise to bumpMBB.
11733   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11734   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11735     .addReg(tmpSPVReg).addReg(sizeVReg);
11736   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11737     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11738     .addReg(tmpSPVReg);
11739   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11740
11741   // bumpMBB simply decreases the stack pointer, since we know the current
11742   // stacklet has enough space.
11743   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11744     .addReg(tmpSPVReg);
11745   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11746     .addReg(tmpSPVReg);
11747   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11748
11749   // Calls into a routine in libgcc to allocate more space from the heap.
11750   if (Is64Bit) {
11751     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11752       .addReg(sizeVReg);
11753     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11754     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11755   } else {
11756     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11757       .addImm(12);
11758     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11759     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11760       .addExternalSymbol("__morestack_allocate_stack_space");
11761   }
11762
11763   if (!Is64Bit)
11764     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11765       .addImm(16);
11766
11767   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11768     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11769   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11770
11771   // Set up the CFG correctly.
11772   BB->addSuccessor(bumpMBB);
11773   BB->addSuccessor(mallocMBB);
11774   mallocMBB->addSuccessor(continueMBB);
11775   bumpMBB->addSuccessor(continueMBB);
11776
11777   // Take care of the PHI nodes.
11778   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11779           MI->getOperand(0).getReg())
11780     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11781     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11782
11783   // Delete the original pseudo instruction.
11784   MI->eraseFromParent();
11785
11786   // And we're done.
11787   return continueMBB;
11788 }
11789
11790 MachineBasicBlock *
11791 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11792                                           MachineBasicBlock *BB) const {
11793   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11794   DebugLoc DL = MI->getDebugLoc();
11795
11796   assert(!Subtarget->isTargetEnvMacho());
11797
11798   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11799   // non-trivial part is impdef of ESP.
11800
11801   if (Subtarget->isTargetWin64()) {
11802     if (Subtarget->isTargetCygMing()) {
11803       // ___chkstk(Mingw64):
11804       // Clobbers R10, R11, RAX and EFLAGS.
11805       // Updates RSP.
11806       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11807         .addExternalSymbol("___chkstk")
11808         .addReg(X86::RAX, RegState::Implicit)
11809         .addReg(X86::RSP, RegState::Implicit)
11810         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11811         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11812         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11813     } else {
11814       // __chkstk(MSVCRT): does not update stack pointer.
11815       // Clobbers R10, R11 and EFLAGS.
11816       // FIXME: RAX(allocated size) might be reused and not killed.
11817       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11818         .addExternalSymbol("__chkstk")
11819         .addReg(X86::RAX, RegState::Implicit)
11820         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11821       // RAX has the offset to subtracted from RSP.
11822       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11823         .addReg(X86::RSP)
11824         .addReg(X86::RAX);
11825     }
11826   } else {
11827     const char *StackProbeSymbol =
11828       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11829
11830     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11831       .addExternalSymbol(StackProbeSymbol)
11832       .addReg(X86::EAX, RegState::Implicit)
11833       .addReg(X86::ESP, RegState::Implicit)
11834       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11835       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11836       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11837   }
11838
11839   MI->eraseFromParent();   // The pseudo instruction is gone now.
11840   return BB;
11841 }
11842
11843 MachineBasicBlock *
11844 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11845                                       MachineBasicBlock *BB) const {
11846   // This is pretty easy.  We're taking the value that we received from
11847   // our load from the relocation, sticking it in either RDI (x86-64)
11848   // or EAX and doing an indirect call.  The return value will then
11849   // be in the normal return register.
11850   const X86InstrInfo *TII
11851     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11852   DebugLoc DL = MI->getDebugLoc();
11853   MachineFunction *F = BB->getParent();
11854
11855   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11856   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11857
11858   if (Subtarget->is64Bit()) {
11859     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11860                                       TII->get(X86::MOV64rm), X86::RDI)
11861     .addReg(X86::RIP)
11862     .addImm(0).addReg(0)
11863     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11864                       MI->getOperand(3).getTargetFlags())
11865     .addReg(0);
11866     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11867     addDirectMem(MIB, X86::RDI);
11868   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11869     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11870                                       TII->get(X86::MOV32rm), X86::EAX)
11871     .addReg(0)
11872     .addImm(0).addReg(0)
11873     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11874                       MI->getOperand(3).getTargetFlags())
11875     .addReg(0);
11876     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11877     addDirectMem(MIB, X86::EAX);
11878   } else {
11879     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11880                                       TII->get(X86::MOV32rm), X86::EAX)
11881     .addReg(TII->getGlobalBaseReg(F))
11882     .addImm(0).addReg(0)
11883     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11884                       MI->getOperand(3).getTargetFlags())
11885     .addReg(0);
11886     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11887     addDirectMem(MIB, X86::EAX);
11888   }
11889
11890   MI->eraseFromParent(); // The pseudo instruction is gone now.
11891   return BB;
11892 }
11893
11894 MachineBasicBlock *
11895 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11896                                                MachineBasicBlock *BB) const {
11897   switch (MI->getOpcode()) {
11898   default: assert(false && "Unexpected instr type to insert");
11899   case X86::TAILJMPd64:
11900   case X86::TAILJMPr64:
11901   case X86::TAILJMPm64:
11902     assert(!"TAILJMP64 would not be touched here.");
11903   case X86::TCRETURNdi64:
11904   case X86::TCRETURNri64:
11905   case X86::TCRETURNmi64:
11906     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11907     // On AMD64, additional defs should be added before register allocation.
11908     if (!Subtarget->isTargetWin64()) {
11909       MI->addRegisterDefined(X86::RSI);
11910       MI->addRegisterDefined(X86::RDI);
11911       MI->addRegisterDefined(X86::XMM6);
11912       MI->addRegisterDefined(X86::XMM7);
11913       MI->addRegisterDefined(X86::XMM8);
11914       MI->addRegisterDefined(X86::XMM9);
11915       MI->addRegisterDefined(X86::XMM10);
11916       MI->addRegisterDefined(X86::XMM11);
11917       MI->addRegisterDefined(X86::XMM12);
11918       MI->addRegisterDefined(X86::XMM13);
11919       MI->addRegisterDefined(X86::XMM14);
11920       MI->addRegisterDefined(X86::XMM15);
11921     }
11922     return BB;
11923   case X86::WIN_ALLOCA:
11924     return EmitLoweredWinAlloca(MI, BB);
11925   case X86::SEG_ALLOCA_32:
11926     return EmitLoweredSegAlloca(MI, BB, false);
11927   case X86::SEG_ALLOCA_64:
11928     return EmitLoweredSegAlloca(MI, BB, true);
11929   case X86::TLSCall_32:
11930   case X86::TLSCall_64:
11931     return EmitLoweredTLSCall(MI, BB);
11932   case X86::CMOV_GR8:
11933   case X86::CMOV_FR32:
11934   case X86::CMOV_FR64:
11935   case X86::CMOV_V4F32:
11936   case X86::CMOV_V2F64:
11937   case X86::CMOV_V2I64:
11938   case X86::CMOV_V8F32:
11939   case X86::CMOV_V4F64:
11940   case X86::CMOV_V4I64:
11941   case X86::CMOV_GR16:
11942   case X86::CMOV_GR32:
11943   case X86::CMOV_RFP32:
11944   case X86::CMOV_RFP64:
11945   case X86::CMOV_RFP80:
11946     return EmitLoweredSelect(MI, BB);
11947
11948   case X86::FP32_TO_INT16_IN_MEM:
11949   case X86::FP32_TO_INT32_IN_MEM:
11950   case X86::FP32_TO_INT64_IN_MEM:
11951   case X86::FP64_TO_INT16_IN_MEM:
11952   case X86::FP64_TO_INT32_IN_MEM:
11953   case X86::FP64_TO_INT64_IN_MEM:
11954   case X86::FP80_TO_INT16_IN_MEM:
11955   case X86::FP80_TO_INT32_IN_MEM:
11956   case X86::FP80_TO_INT64_IN_MEM: {
11957     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11958     DebugLoc DL = MI->getDebugLoc();
11959
11960     // Change the floating point control register to use "round towards zero"
11961     // mode when truncating to an integer value.
11962     MachineFunction *F = BB->getParent();
11963     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11964     addFrameReference(BuildMI(*BB, MI, DL,
11965                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
11966
11967     // Load the old value of the high byte of the control word...
11968     unsigned OldCW =
11969       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11970     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11971                       CWFrameIdx);
11972
11973     // Set the high part to be round to zero...
11974     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11975       .addImm(0xC7F);
11976
11977     // Reload the modified control word now...
11978     addFrameReference(BuildMI(*BB, MI, DL,
11979                               TII->get(X86::FLDCW16m)), CWFrameIdx);
11980
11981     // Restore the memory image of control word to original value
11982     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
11983       .addReg(OldCW);
11984
11985     // Get the X86 opcode to use.
11986     unsigned Opc;
11987     switch (MI->getOpcode()) {
11988     default: llvm_unreachable("illegal opcode!");
11989     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
11990     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
11991     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
11992     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
11993     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
11994     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
11995     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
11996     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
11997     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
11998     }
11999
12000     X86AddressMode AM;
12001     MachineOperand &Op = MI->getOperand(0);
12002     if (Op.isReg()) {
12003       AM.BaseType = X86AddressMode::RegBase;
12004       AM.Base.Reg = Op.getReg();
12005     } else {
12006       AM.BaseType = X86AddressMode::FrameIndexBase;
12007       AM.Base.FrameIndex = Op.getIndex();
12008     }
12009     Op = MI->getOperand(1);
12010     if (Op.isImm())
12011       AM.Scale = Op.getImm();
12012     Op = MI->getOperand(2);
12013     if (Op.isImm())
12014       AM.IndexReg = Op.getImm();
12015     Op = MI->getOperand(3);
12016     if (Op.isGlobal()) {
12017       AM.GV = Op.getGlobal();
12018     } else {
12019       AM.Disp = Op.getImm();
12020     }
12021     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12022                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12023
12024     // Reload the original control word now.
12025     addFrameReference(BuildMI(*BB, MI, DL,
12026                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12027
12028     MI->eraseFromParent();   // The pseudo instruction is gone now.
12029     return BB;
12030   }
12031     // String/text processing lowering.
12032   case X86::PCMPISTRM128REG:
12033   case X86::VPCMPISTRM128REG:
12034     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12035   case X86::PCMPISTRM128MEM:
12036   case X86::VPCMPISTRM128MEM:
12037     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12038   case X86::PCMPESTRM128REG:
12039   case X86::VPCMPESTRM128REG:
12040     return EmitPCMP(MI, BB, 5, false /* in mem */);
12041   case X86::PCMPESTRM128MEM:
12042   case X86::VPCMPESTRM128MEM:
12043     return EmitPCMP(MI, BB, 5, true /* in mem */);
12044
12045     // Thread synchronization.
12046   case X86::MONITOR:
12047     return EmitMonitor(MI, BB);
12048   case X86::MWAIT:
12049     return EmitMwait(MI, BB);
12050
12051     // Atomic Lowering.
12052   case X86::ATOMAND32:
12053     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12054                                                X86::AND32ri, X86::MOV32rm,
12055                                                X86::LCMPXCHG32,
12056                                                X86::NOT32r, X86::EAX,
12057                                                X86::GR32RegisterClass);
12058   case X86::ATOMOR32:
12059     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12060                                                X86::OR32ri, X86::MOV32rm,
12061                                                X86::LCMPXCHG32,
12062                                                X86::NOT32r, X86::EAX,
12063                                                X86::GR32RegisterClass);
12064   case X86::ATOMXOR32:
12065     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12066                                                X86::XOR32ri, X86::MOV32rm,
12067                                                X86::LCMPXCHG32,
12068                                                X86::NOT32r, X86::EAX,
12069                                                X86::GR32RegisterClass);
12070   case X86::ATOMNAND32:
12071     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12072                                                X86::AND32ri, X86::MOV32rm,
12073                                                X86::LCMPXCHG32,
12074                                                X86::NOT32r, X86::EAX,
12075                                                X86::GR32RegisterClass, true);
12076   case X86::ATOMMIN32:
12077     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12078   case X86::ATOMMAX32:
12079     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12080   case X86::ATOMUMIN32:
12081     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12082   case X86::ATOMUMAX32:
12083     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12084
12085   case X86::ATOMAND16:
12086     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12087                                                X86::AND16ri, X86::MOV16rm,
12088                                                X86::LCMPXCHG16,
12089                                                X86::NOT16r, X86::AX,
12090                                                X86::GR16RegisterClass);
12091   case X86::ATOMOR16:
12092     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12093                                                X86::OR16ri, X86::MOV16rm,
12094                                                X86::LCMPXCHG16,
12095                                                X86::NOT16r, X86::AX,
12096                                                X86::GR16RegisterClass);
12097   case X86::ATOMXOR16:
12098     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12099                                                X86::XOR16ri, X86::MOV16rm,
12100                                                X86::LCMPXCHG16,
12101                                                X86::NOT16r, X86::AX,
12102                                                X86::GR16RegisterClass);
12103   case X86::ATOMNAND16:
12104     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12105                                                X86::AND16ri, X86::MOV16rm,
12106                                                X86::LCMPXCHG16,
12107                                                X86::NOT16r, X86::AX,
12108                                                X86::GR16RegisterClass, true);
12109   case X86::ATOMMIN16:
12110     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12111   case X86::ATOMMAX16:
12112     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12113   case X86::ATOMUMIN16:
12114     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12115   case X86::ATOMUMAX16:
12116     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12117
12118   case X86::ATOMAND8:
12119     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12120                                                X86::AND8ri, X86::MOV8rm,
12121                                                X86::LCMPXCHG8,
12122                                                X86::NOT8r, X86::AL,
12123                                                X86::GR8RegisterClass);
12124   case X86::ATOMOR8:
12125     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12126                                                X86::OR8ri, X86::MOV8rm,
12127                                                X86::LCMPXCHG8,
12128                                                X86::NOT8r, X86::AL,
12129                                                X86::GR8RegisterClass);
12130   case X86::ATOMXOR8:
12131     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12132                                                X86::XOR8ri, X86::MOV8rm,
12133                                                X86::LCMPXCHG8,
12134                                                X86::NOT8r, X86::AL,
12135                                                X86::GR8RegisterClass);
12136   case X86::ATOMNAND8:
12137     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12138                                                X86::AND8ri, X86::MOV8rm,
12139                                                X86::LCMPXCHG8,
12140                                                X86::NOT8r, X86::AL,
12141                                                X86::GR8RegisterClass, true);
12142   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12143   // This group is for 64-bit host.
12144   case X86::ATOMAND64:
12145     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12146                                                X86::AND64ri32, X86::MOV64rm,
12147                                                X86::LCMPXCHG64,
12148                                                X86::NOT64r, X86::RAX,
12149                                                X86::GR64RegisterClass);
12150   case X86::ATOMOR64:
12151     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12152                                                X86::OR64ri32, X86::MOV64rm,
12153                                                X86::LCMPXCHG64,
12154                                                X86::NOT64r, X86::RAX,
12155                                                X86::GR64RegisterClass);
12156   case X86::ATOMXOR64:
12157     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12158                                                X86::XOR64ri32, X86::MOV64rm,
12159                                                X86::LCMPXCHG64,
12160                                                X86::NOT64r, X86::RAX,
12161                                                X86::GR64RegisterClass);
12162   case X86::ATOMNAND64:
12163     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12164                                                X86::AND64ri32, X86::MOV64rm,
12165                                                X86::LCMPXCHG64,
12166                                                X86::NOT64r, X86::RAX,
12167                                                X86::GR64RegisterClass, true);
12168   case X86::ATOMMIN64:
12169     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12170   case X86::ATOMMAX64:
12171     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12172   case X86::ATOMUMIN64:
12173     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12174   case X86::ATOMUMAX64:
12175     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12176
12177   // This group does 64-bit operations on a 32-bit host.
12178   case X86::ATOMAND6432:
12179     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12180                                                X86::AND32rr, X86::AND32rr,
12181                                                X86::AND32ri, X86::AND32ri,
12182                                                false);
12183   case X86::ATOMOR6432:
12184     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12185                                                X86::OR32rr, X86::OR32rr,
12186                                                X86::OR32ri, X86::OR32ri,
12187                                                false);
12188   case X86::ATOMXOR6432:
12189     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12190                                                X86::XOR32rr, X86::XOR32rr,
12191                                                X86::XOR32ri, X86::XOR32ri,
12192                                                false);
12193   case X86::ATOMNAND6432:
12194     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12195                                                X86::AND32rr, X86::AND32rr,
12196                                                X86::AND32ri, X86::AND32ri,
12197                                                true);
12198   case X86::ATOMADD6432:
12199     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12200                                                X86::ADD32rr, X86::ADC32rr,
12201                                                X86::ADD32ri, X86::ADC32ri,
12202                                                false);
12203   case X86::ATOMSUB6432:
12204     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12205                                                X86::SUB32rr, X86::SBB32rr,
12206                                                X86::SUB32ri, X86::SBB32ri,
12207                                                false);
12208   case X86::ATOMSWAP6432:
12209     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12210                                                X86::MOV32rr, X86::MOV32rr,
12211                                                X86::MOV32ri, X86::MOV32ri,
12212                                                false);
12213   case X86::VASTART_SAVE_XMM_REGS:
12214     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12215
12216   case X86::VAARG_64:
12217     return EmitVAARG64WithCustomInserter(MI, BB);
12218   }
12219 }
12220
12221 //===----------------------------------------------------------------------===//
12222 //                           X86 Optimization Hooks
12223 //===----------------------------------------------------------------------===//
12224
12225 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12226                                                        const APInt &Mask,
12227                                                        APInt &KnownZero,
12228                                                        APInt &KnownOne,
12229                                                        const SelectionDAG &DAG,
12230                                                        unsigned Depth) const {
12231   unsigned Opc = Op.getOpcode();
12232   assert((Opc >= ISD::BUILTIN_OP_END ||
12233           Opc == ISD::INTRINSIC_WO_CHAIN ||
12234           Opc == ISD::INTRINSIC_W_CHAIN ||
12235           Opc == ISD::INTRINSIC_VOID) &&
12236          "Should use MaskedValueIsZero if you don't know whether Op"
12237          " is a target node!");
12238
12239   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12240   switch (Opc) {
12241   default: break;
12242   case X86ISD::ADD:
12243   case X86ISD::SUB:
12244   case X86ISD::ADC:
12245   case X86ISD::SBB:
12246   case X86ISD::SMUL:
12247   case X86ISD::UMUL:
12248   case X86ISD::INC:
12249   case X86ISD::DEC:
12250   case X86ISD::OR:
12251   case X86ISD::XOR:
12252   case X86ISD::AND:
12253     // These nodes' second result is a boolean.
12254     if (Op.getResNo() == 0)
12255       break;
12256     // Fallthrough
12257   case X86ISD::SETCC:
12258     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12259                                        Mask.getBitWidth() - 1);
12260     break;
12261   }
12262 }
12263
12264 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12265                                                          unsigned Depth) const {
12266   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12267   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12268     return Op.getValueType().getScalarType().getSizeInBits();
12269
12270   // Fallback case.
12271   return 1;
12272 }
12273
12274 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12275 /// node is a GlobalAddress + offset.
12276 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12277                                        const GlobalValue* &GA,
12278                                        int64_t &Offset) const {
12279   if (N->getOpcode() == X86ISD::Wrapper) {
12280     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12281       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12282       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12283       return true;
12284     }
12285   }
12286   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12287 }
12288
12289 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12290 /// same as extracting the high 128-bit part of 256-bit vector and then
12291 /// inserting the result into the low part of a new 256-bit vector
12292 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12293   EVT VT = SVOp->getValueType(0);
12294   int NumElems = VT.getVectorNumElements();
12295
12296   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12297   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12298     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12299         SVOp->getMaskElt(j) >= 0)
12300       return false;
12301
12302   return true;
12303 }
12304
12305 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12306 /// same as extracting the low 128-bit part of 256-bit vector and then
12307 /// inserting the result into the high part of a new 256-bit vector
12308 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12309   EVT VT = SVOp->getValueType(0);
12310   int NumElems = VT.getVectorNumElements();
12311
12312   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12313   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12314     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12315         SVOp->getMaskElt(j) >= 0)
12316       return false;
12317
12318   return true;
12319 }
12320
12321 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12322 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12323                                         TargetLowering::DAGCombinerInfo &DCI) {
12324   DebugLoc dl = N->getDebugLoc();
12325   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12326   SDValue V1 = SVOp->getOperand(0);
12327   SDValue V2 = SVOp->getOperand(1);
12328   EVT VT = SVOp->getValueType(0);
12329   int NumElems = VT.getVectorNumElements();
12330
12331   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12332       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12333     //
12334     //                   0,0,0,...
12335     //                      |
12336     //    V      UNDEF    BUILD_VECTOR    UNDEF
12337     //     \      /           \           /
12338     //  CONCAT_VECTOR         CONCAT_VECTOR
12339     //         \                  /
12340     //          \                /
12341     //          RESULT: V + zero extended
12342     //
12343     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12344         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12345         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12346       return SDValue();
12347
12348     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12349       return SDValue();
12350
12351     // To match the shuffle mask, the first half of the mask should
12352     // be exactly the first vector, and all the rest a splat with the
12353     // first element of the second one.
12354     for (int i = 0; i < NumElems/2; ++i)
12355       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12356           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12357         return SDValue();
12358
12359     // Emit a zeroed vector and insert the desired subvector on its
12360     // first half.
12361     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
12362     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12363                          DAG.getConstant(0, MVT::i32), DAG, dl);
12364     return DCI.CombineTo(N, InsV);
12365   }
12366
12367   //===--------------------------------------------------------------------===//
12368   // Combine some shuffles into subvector extracts and inserts:
12369   //
12370
12371   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12372   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12373     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12374                                     DAG, dl);
12375     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12376                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12377     return DCI.CombineTo(N, InsV);
12378   }
12379
12380   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12381   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12382     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12383     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12384                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12385     return DCI.CombineTo(N, InsV);
12386   }
12387
12388   return SDValue();
12389 }
12390
12391 /// PerformShuffleCombine - Performs several different shuffle combines.
12392 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12393                                      TargetLowering::DAGCombinerInfo &DCI,
12394                                      const X86Subtarget *Subtarget) {
12395   DebugLoc dl = N->getDebugLoc();
12396   EVT VT = N->getValueType(0);
12397
12398   // Don't create instructions with illegal types after legalize types has run.
12399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12400   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12401     return SDValue();
12402
12403   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12404   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12405       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12406     return PerformShuffleCombine256(N, DAG, DCI);
12407
12408   // Only handle 128 wide vector from here on.
12409   if (VT.getSizeInBits() != 128)
12410     return SDValue();
12411
12412   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12413   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12414   // consecutive, non-overlapping, and in the right order.
12415   SmallVector<SDValue, 16> Elts;
12416   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12417     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12418
12419   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12420 }
12421
12422 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12423 /// generation and convert it from being a bunch of shuffles and extracts
12424 /// to a simple store and scalar loads to extract the elements.
12425 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12426                                                 const TargetLowering &TLI) {
12427   SDValue InputVector = N->getOperand(0);
12428
12429   // Only operate on vectors of 4 elements, where the alternative shuffling
12430   // gets to be more expensive.
12431   if (InputVector.getValueType() != MVT::v4i32)
12432     return SDValue();
12433
12434   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12435   // single use which is a sign-extend or zero-extend, and all elements are
12436   // used.
12437   SmallVector<SDNode *, 4> Uses;
12438   unsigned ExtractedElements = 0;
12439   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12440        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12441     if (UI.getUse().getResNo() != InputVector.getResNo())
12442       return SDValue();
12443
12444     SDNode *Extract = *UI;
12445     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12446       return SDValue();
12447
12448     if (Extract->getValueType(0) != MVT::i32)
12449       return SDValue();
12450     if (!Extract->hasOneUse())
12451       return SDValue();
12452     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12453         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12454       return SDValue();
12455     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12456       return SDValue();
12457
12458     // Record which element was extracted.
12459     ExtractedElements |=
12460       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12461
12462     Uses.push_back(Extract);
12463   }
12464
12465   // If not all the elements were used, this may not be worthwhile.
12466   if (ExtractedElements != 15)
12467     return SDValue();
12468
12469   // Ok, we've now decided to do the transformation.
12470   DebugLoc dl = InputVector.getDebugLoc();
12471
12472   // Store the value to a temporary stack slot.
12473   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12474   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12475                             MachinePointerInfo(), false, false, 0);
12476
12477   // Replace each use (extract) with a load of the appropriate element.
12478   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12479        UE = Uses.end(); UI != UE; ++UI) {
12480     SDNode *Extract = *UI;
12481
12482     // cOMpute the element's address.
12483     SDValue Idx = Extract->getOperand(1);
12484     unsigned EltSize =
12485         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12486     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12487     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12488
12489     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12490                                      StackPtr, OffsetVal);
12491
12492     // Load the scalar.
12493     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12494                                      ScalarAddr, MachinePointerInfo(),
12495                                      false, false, 0);
12496
12497     // Replace the exact with the load.
12498     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12499   }
12500
12501   // The replacement was made in place; don't return anything.
12502   return SDValue();
12503 }
12504
12505 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12506 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12507                                     const X86Subtarget *Subtarget) {
12508   DebugLoc DL = N->getDebugLoc();
12509   SDValue Cond = N->getOperand(0);
12510   // Get the LHS/RHS of the select.
12511   SDValue LHS = N->getOperand(1);
12512   SDValue RHS = N->getOperand(2);
12513
12514   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12515   // instructions match the semantics of the common C idiom x<y?x:y but not
12516   // x<=y?x:y, because of how they handle negative zero (which can be
12517   // ignored in unsafe-math mode).
12518   if (Subtarget->hasSSE2() &&
12519       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12520       Cond.getOpcode() == ISD::SETCC) {
12521     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12522
12523     unsigned Opcode = 0;
12524     // Check for x CC y ? x : y.
12525     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12526         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12527       switch (CC) {
12528       default: break;
12529       case ISD::SETULT:
12530         // Converting this to a min would handle NaNs incorrectly, and swapping
12531         // the operands would cause it to handle comparisons between positive
12532         // and negative zero incorrectly.
12533         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12534           if (!UnsafeFPMath &&
12535               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12536             break;
12537           std::swap(LHS, RHS);
12538         }
12539         Opcode = X86ISD::FMIN;
12540         break;
12541       case ISD::SETOLE:
12542         // Converting this to a min would handle comparisons between positive
12543         // and negative zero incorrectly.
12544         if (!UnsafeFPMath &&
12545             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12546           break;
12547         Opcode = X86ISD::FMIN;
12548         break;
12549       case ISD::SETULE:
12550         // Converting this to a min would handle both negative zeros and NaNs
12551         // incorrectly, but we can swap the operands to fix both.
12552         std::swap(LHS, RHS);
12553       case ISD::SETOLT:
12554       case ISD::SETLT:
12555       case ISD::SETLE:
12556         Opcode = X86ISD::FMIN;
12557         break;
12558
12559       case ISD::SETOGE:
12560         // Converting this to a max would handle comparisons between positive
12561         // and negative zero incorrectly.
12562         if (!UnsafeFPMath &&
12563             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12564           break;
12565         Opcode = X86ISD::FMAX;
12566         break;
12567       case ISD::SETUGT:
12568         // Converting this to a max would handle NaNs incorrectly, and swapping
12569         // the operands would cause it to handle comparisons between positive
12570         // and negative zero incorrectly.
12571         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12572           if (!UnsafeFPMath &&
12573               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12574             break;
12575           std::swap(LHS, RHS);
12576         }
12577         Opcode = X86ISD::FMAX;
12578         break;
12579       case ISD::SETUGE:
12580         // Converting this to a max would handle both negative zeros and NaNs
12581         // incorrectly, but we can swap the operands to fix both.
12582         std::swap(LHS, RHS);
12583       case ISD::SETOGT:
12584       case ISD::SETGT:
12585       case ISD::SETGE:
12586         Opcode = X86ISD::FMAX;
12587         break;
12588       }
12589     // Check for x CC y ? y : x -- a min/max with reversed arms.
12590     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12591                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12592       switch (CC) {
12593       default: break;
12594       case ISD::SETOGE:
12595         // Converting this to a min would handle comparisons between positive
12596         // and negative zero incorrectly, and swapping the operands would
12597         // cause it to handle NaNs incorrectly.
12598         if (!UnsafeFPMath &&
12599             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12600           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12601             break;
12602           std::swap(LHS, RHS);
12603         }
12604         Opcode = X86ISD::FMIN;
12605         break;
12606       case ISD::SETUGT:
12607         // Converting this to a min would handle NaNs incorrectly.
12608         if (!UnsafeFPMath &&
12609             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12610           break;
12611         Opcode = X86ISD::FMIN;
12612         break;
12613       case ISD::SETUGE:
12614         // Converting this to a min would handle both negative zeros and NaNs
12615         // incorrectly, but we can swap the operands to fix both.
12616         std::swap(LHS, RHS);
12617       case ISD::SETOGT:
12618       case ISD::SETGT:
12619       case ISD::SETGE:
12620         Opcode = X86ISD::FMIN;
12621         break;
12622
12623       case ISD::SETULT:
12624         // Converting this to a max would handle NaNs incorrectly.
12625         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12626           break;
12627         Opcode = X86ISD::FMAX;
12628         break;
12629       case ISD::SETOLE:
12630         // Converting this to a max would handle comparisons between positive
12631         // and negative zero incorrectly, and swapping the operands would
12632         // cause it to handle NaNs incorrectly.
12633         if (!UnsafeFPMath &&
12634             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12635           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12636             break;
12637           std::swap(LHS, RHS);
12638         }
12639         Opcode = X86ISD::FMAX;
12640         break;
12641       case ISD::SETULE:
12642         // Converting this to a max would handle both negative zeros and NaNs
12643         // incorrectly, but we can swap the operands to fix both.
12644         std::swap(LHS, RHS);
12645       case ISD::SETOLT:
12646       case ISD::SETLT:
12647       case ISD::SETLE:
12648         Opcode = X86ISD::FMAX;
12649         break;
12650       }
12651     }
12652
12653     if (Opcode)
12654       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12655   }
12656
12657   // If this is a select between two integer constants, try to do some
12658   // optimizations.
12659   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12660     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12661       // Don't do this for crazy integer types.
12662       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12663         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12664         // so that TrueC (the true value) is larger than FalseC.
12665         bool NeedsCondInvert = false;
12666
12667         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12668             // Efficiently invertible.
12669             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12670              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12671               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12672           NeedsCondInvert = true;
12673           std::swap(TrueC, FalseC);
12674         }
12675
12676         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12677         if (FalseC->getAPIntValue() == 0 &&
12678             TrueC->getAPIntValue().isPowerOf2()) {
12679           if (NeedsCondInvert) // Invert the condition if needed.
12680             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12681                                DAG.getConstant(1, Cond.getValueType()));
12682
12683           // Zero extend the condition if needed.
12684           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12685
12686           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12687           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12688                              DAG.getConstant(ShAmt, MVT::i8));
12689         }
12690
12691         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12692         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12693           if (NeedsCondInvert) // Invert the condition if needed.
12694             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12695                                DAG.getConstant(1, Cond.getValueType()));
12696
12697           // Zero extend the condition if needed.
12698           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12699                              FalseC->getValueType(0), Cond);
12700           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12701                              SDValue(FalseC, 0));
12702         }
12703
12704         // Optimize cases that will turn into an LEA instruction.  This requires
12705         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12706         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12707           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12708           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12709
12710           bool isFastMultiplier = false;
12711           if (Diff < 10) {
12712             switch ((unsigned char)Diff) {
12713               default: break;
12714               case 1:  // result = add base, cond
12715               case 2:  // result = lea base(    , cond*2)
12716               case 3:  // result = lea base(cond, cond*2)
12717               case 4:  // result = lea base(    , cond*4)
12718               case 5:  // result = lea base(cond, cond*4)
12719               case 8:  // result = lea base(    , cond*8)
12720               case 9:  // result = lea base(cond, cond*8)
12721                 isFastMultiplier = true;
12722                 break;
12723             }
12724           }
12725
12726           if (isFastMultiplier) {
12727             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12728             if (NeedsCondInvert) // Invert the condition if needed.
12729               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12730                                  DAG.getConstant(1, Cond.getValueType()));
12731
12732             // Zero extend the condition if needed.
12733             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12734                                Cond);
12735             // Scale the condition by the difference.
12736             if (Diff != 1)
12737               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12738                                  DAG.getConstant(Diff, Cond.getValueType()));
12739
12740             // Add the base if non-zero.
12741             if (FalseC->getAPIntValue() != 0)
12742               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12743                                  SDValue(FalseC, 0));
12744             return Cond;
12745           }
12746         }
12747       }
12748   }
12749
12750   return SDValue();
12751 }
12752
12753 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12754 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12755                                   TargetLowering::DAGCombinerInfo &DCI) {
12756   DebugLoc DL = N->getDebugLoc();
12757
12758   // If the flag operand isn't dead, don't touch this CMOV.
12759   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12760     return SDValue();
12761
12762   SDValue FalseOp = N->getOperand(0);
12763   SDValue TrueOp = N->getOperand(1);
12764   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12765   SDValue Cond = N->getOperand(3);
12766   if (CC == X86::COND_E || CC == X86::COND_NE) {
12767     switch (Cond.getOpcode()) {
12768     default: break;
12769     case X86ISD::BSR:
12770     case X86ISD::BSF:
12771       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12772       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12773         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12774     }
12775   }
12776
12777   // If this is a select between two integer constants, try to do some
12778   // optimizations.  Note that the operands are ordered the opposite of SELECT
12779   // operands.
12780   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12781     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12782       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12783       // larger than FalseC (the false value).
12784       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12785         CC = X86::GetOppositeBranchCondition(CC);
12786         std::swap(TrueC, FalseC);
12787       }
12788
12789       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12790       // This is efficient for any integer data type (including i8/i16) and
12791       // shift amount.
12792       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12793         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12794                            DAG.getConstant(CC, MVT::i8), Cond);
12795
12796         // Zero extend the condition if needed.
12797         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12798
12799         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12800         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12801                            DAG.getConstant(ShAmt, MVT::i8));
12802         if (N->getNumValues() == 2)  // Dead flag value?
12803           return DCI.CombineTo(N, Cond, SDValue());
12804         return Cond;
12805       }
12806
12807       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12808       // for any integer data type, including i8/i16.
12809       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12810         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12811                            DAG.getConstant(CC, MVT::i8), Cond);
12812
12813         // Zero extend the condition if needed.
12814         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12815                            FalseC->getValueType(0), Cond);
12816         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12817                            SDValue(FalseC, 0));
12818
12819         if (N->getNumValues() == 2)  // Dead flag value?
12820           return DCI.CombineTo(N, Cond, SDValue());
12821         return Cond;
12822       }
12823
12824       // Optimize cases that will turn into an LEA instruction.  This requires
12825       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12826       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12827         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12828         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12829
12830         bool isFastMultiplier = false;
12831         if (Diff < 10) {
12832           switch ((unsigned char)Diff) {
12833           default: break;
12834           case 1:  // result = add base, cond
12835           case 2:  // result = lea base(    , cond*2)
12836           case 3:  // result = lea base(cond, cond*2)
12837           case 4:  // result = lea base(    , cond*4)
12838           case 5:  // result = lea base(cond, cond*4)
12839           case 8:  // result = lea base(    , cond*8)
12840           case 9:  // result = lea base(cond, cond*8)
12841             isFastMultiplier = true;
12842             break;
12843           }
12844         }
12845
12846         if (isFastMultiplier) {
12847           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12848           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12849                              DAG.getConstant(CC, MVT::i8), Cond);
12850           // Zero extend the condition if needed.
12851           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12852                              Cond);
12853           // Scale the condition by the difference.
12854           if (Diff != 1)
12855             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12856                                DAG.getConstant(Diff, Cond.getValueType()));
12857
12858           // Add the base if non-zero.
12859           if (FalseC->getAPIntValue() != 0)
12860             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12861                                SDValue(FalseC, 0));
12862           if (N->getNumValues() == 2)  // Dead flag value?
12863             return DCI.CombineTo(N, Cond, SDValue());
12864           return Cond;
12865         }
12866       }
12867     }
12868   }
12869   return SDValue();
12870 }
12871
12872
12873 /// PerformMulCombine - Optimize a single multiply with constant into two
12874 /// in order to implement it with two cheaper instructions, e.g.
12875 /// LEA + SHL, LEA + LEA.
12876 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12877                                  TargetLowering::DAGCombinerInfo &DCI) {
12878   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12879     return SDValue();
12880
12881   EVT VT = N->getValueType(0);
12882   if (VT != MVT::i64)
12883     return SDValue();
12884
12885   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12886   if (!C)
12887     return SDValue();
12888   uint64_t MulAmt = C->getZExtValue();
12889   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12890     return SDValue();
12891
12892   uint64_t MulAmt1 = 0;
12893   uint64_t MulAmt2 = 0;
12894   if ((MulAmt % 9) == 0) {
12895     MulAmt1 = 9;
12896     MulAmt2 = MulAmt / 9;
12897   } else if ((MulAmt % 5) == 0) {
12898     MulAmt1 = 5;
12899     MulAmt2 = MulAmt / 5;
12900   } else if ((MulAmt % 3) == 0) {
12901     MulAmt1 = 3;
12902     MulAmt2 = MulAmt / 3;
12903   }
12904   if (MulAmt2 &&
12905       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12906     DebugLoc DL = N->getDebugLoc();
12907
12908     if (isPowerOf2_64(MulAmt2) &&
12909         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12910       // If second multiplifer is pow2, issue it first. We want the multiply by
12911       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12912       // is an add.
12913       std::swap(MulAmt1, MulAmt2);
12914
12915     SDValue NewMul;
12916     if (isPowerOf2_64(MulAmt1))
12917       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12918                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12919     else
12920       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12921                            DAG.getConstant(MulAmt1, VT));
12922
12923     if (isPowerOf2_64(MulAmt2))
12924       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12925                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12926     else
12927       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12928                            DAG.getConstant(MulAmt2, VT));
12929
12930     // Do not add new nodes to DAG combiner worklist.
12931     DCI.CombineTo(N, NewMul, false);
12932   }
12933   return SDValue();
12934 }
12935
12936 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12937   SDValue N0 = N->getOperand(0);
12938   SDValue N1 = N->getOperand(1);
12939   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12940   EVT VT = N0.getValueType();
12941
12942   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12943   // since the result of setcc_c is all zero's or all ones.
12944   if (N1C && N0.getOpcode() == ISD::AND &&
12945       N0.getOperand(1).getOpcode() == ISD::Constant) {
12946     SDValue N00 = N0.getOperand(0);
12947     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12948         ((N00.getOpcode() == ISD::ANY_EXTEND ||
12949           N00.getOpcode() == ISD::ZERO_EXTEND) &&
12950          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12951       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12952       APInt ShAmt = N1C->getAPIntValue();
12953       Mask = Mask.shl(ShAmt);
12954       if (Mask != 0)
12955         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12956                            N00, DAG.getConstant(Mask, VT));
12957     }
12958   }
12959
12960   return SDValue();
12961 }
12962
12963 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12964 ///                       when possible.
12965 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12966                                    const X86Subtarget *Subtarget) {
12967   EVT VT = N->getValueType(0);
12968   if (!VT.isVector() && VT.isInteger() &&
12969       N->getOpcode() == ISD::SHL)
12970     return PerformSHLCombine(N, DAG);
12971
12972   // On X86 with SSE2 support, we can transform this to a vector shift if
12973   // all elements are shifted by the same amount.  We can't do this in legalize
12974   // because the a constant vector is typically transformed to a constant pool
12975   // so we have no knowledge of the shift amount.
12976   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12977     return SDValue();
12978
12979   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
12980     return SDValue();
12981
12982   SDValue ShAmtOp = N->getOperand(1);
12983   EVT EltVT = VT.getVectorElementType();
12984   DebugLoc DL = N->getDebugLoc();
12985   SDValue BaseShAmt = SDValue();
12986   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
12987     unsigned NumElts = VT.getVectorNumElements();
12988     unsigned i = 0;
12989     for (; i != NumElts; ++i) {
12990       SDValue Arg = ShAmtOp.getOperand(i);
12991       if (Arg.getOpcode() == ISD::UNDEF) continue;
12992       BaseShAmt = Arg;
12993       break;
12994     }
12995     for (; i != NumElts; ++i) {
12996       SDValue Arg = ShAmtOp.getOperand(i);
12997       if (Arg.getOpcode() == ISD::UNDEF) continue;
12998       if (Arg != BaseShAmt) {
12999         return SDValue();
13000       }
13001     }
13002   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13003              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13004     SDValue InVec = ShAmtOp.getOperand(0);
13005     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13006       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13007       unsigned i = 0;
13008       for (; i != NumElts; ++i) {
13009         SDValue Arg = InVec.getOperand(i);
13010         if (Arg.getOpcode() == ISD::UNDEF) continue;
13011         BaseShAmt = Arg;
13012         break;
13013       }
13014     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13015        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13016          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13017          if (C->getZExtValue() == SplatIdx)
13018            BaseShAmt = InVec.getOperand(1);
13019        }
13020     }
13021     if (BaseShAmt.getNode() == 0)
13022       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13023                               DAG.getIntPtrConstant(0));
13024   } else
13025     return SDValue();
13026
13027   // The shift amount is an i32.
13028   if (EltVT.bitsGT(MVT::i32))
13029     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13030   else if (EltVT.bitsLT(MVT::i32))
13031     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13032
13033   // The shift amount is identical so we can do a vector shift.
13034   SDValue  ValOp = N->getOperand(0);
13035   switch (N->getOpcode()) {
13036   default:
13037     llvm_unreachable("Unknown shift opcode!");
13038     break;
13039   case ISD::SHL:
13040     if (VT == MVT::v2i64)
13041       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13042                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13043                          ValOp, BaseShAmt);
13044     if (VT == MVT::v4i32)
13045       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13046                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13047                          ValOp, BaseShAmt);
13048     if (VT == MVT::v8i16)
13049       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13050                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13051                          ValOp, BaseShAmt);
13052     break;
13053   case ISD::SRA:
13054     if (VT == MVT::v4i32)
13055       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13056                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13057                          ValOp, BaseShAmt);
13058     if (VT == MVT::v8i16)
13059       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13060                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13061                          ValOp, BaseShAmt);
13062     break;
13063   case ISD::SRL:
13064     if (VT == MVT::v2i64)
13065       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13066                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13067                          ValOp, BaseShAmt);
13068     if (VT == MVT::v4i32)
13069       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13070                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13071                          ValOp, BaseShAmt);
13072     if (VT ==  MVT::v8i16)
13073       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13074                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13075                          ValOp, BaseShAmt);
13076     break;
13077   }
13078   return SDValue();
13079 }
13080
13081
13082 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13083 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13084 // and friends.  Likewise for OR -> CMPNEQSS.
13085 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13086                             TargetLowering::DAGCombinerInfo &DCI,
13087                             const X86Subtarget *Subtarget) {
13088   unsigned opcode;
13089
13090   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13091   // we're requiring SSE2 for both.
13092   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13093     SDValue N0 = N->getOperand(0);
13094     SDValue N1 = N->getOperand(1);
13095     SDValue CMP0 = N0->getOperand(1);
13096     SDValue CMP1 = N1->getOperand(1);
13097     DebugLoc DL = N->getDebugLoc();
13098
13099     // The SETCCs should both refer to the same CMP.
13100     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13101       return SDValue();
13102
13103     SDValue CMP00 = CMP0->getOperand(0);
13104     SDValue CMP01 = CMP0->getOperand(1);
13105     EVT     VT    = CMP00.getValueType();
13106
13107     if (VT == MVT::f32 || VT == MVT::f64) {
13108       bool ExpectingFlags = false;
13109       // Check for any users that want flags:
13110       for (SDNode::use_iterator UI = N->use_begin(),
13111              UE = N->use_end();
13112            !ExpectingFlags && UI != UE; ++UI)
13113         switch (UI->getOpcode()) {
13114         default:
13115         case ISD::BR_CC:
13116         case ISD::BRCOND:
13117         case ISD::SELECT:
13118           ExpectingFlags = true;
13119           break;
13120         case ISD::CopyToReg:
13121         case ISD::SIGN_EXTEND:
13122         case ISD::ZERO_EXTEND:
13123         case ISD::ANY_EXTEND:
13124           break;
13125         }
13126
13127       if (!ExpectingFlags) {
13128         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13129         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13130
13131         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13132           X86::CondCode tmp = cc0;
13133           cc0 = cc1;
13134           cc1 = tmp;
13135         }
13136
13137         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13138             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13139           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13140           X86ISD::NodeType NTOperator = is64BitFP ?
13141             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13142           // FIXME: need symbolic constants for these magic numbers.
13143           // See X86ATTInstPrinter.cpp:printSSECC().
13144           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13145           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13146                                               DAG.getConstant(x86cc, MVT::i8));
13147           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13148                                               OnesOrZeroesF);
13149           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13150                                       DAG.getConstant(1, MVT::i32));
13151           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13152           return OneBitOfTruth;
13153         }
13154       }
13155     }
13156   }
13157   return SDValue();
13158 }
13159
13160 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13161 /// so it can be folded inside ANDNP.
13162 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13163   EVT VT = N->getValueType(0);
13164
13165   // Match direct AllOnes for 128 and 256-bit vectors
13166   if (ISD::isBuildVectorAllOnes(N))
13167     return true;
13168
13169   // Look through a bit convert.
13170   if (N->getOpcode() == ISD::BITCAST)
13171     N = N->getOperand(0).getNode();
13172
13173   // Sometimes the operand may come from a insert_subvector building a 256-bit
13174   // allones vector
13175   if (VT.getSizeInBits() == 256 &&
13176       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13177     SDValue V1 = N->getOperand(0);
13178     SDValue V2 = N->getOperand(1);
13179
13180     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13181         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13182         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13183         ISD::isBuildVectorAllOnes(V2.getNode()))
13184       return true;
13185   }
13186
13187   return false;
13188 }
13189
13190 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13191                                  TargetLowering::DAGCombinerInfo &DCI,
13192                                  const X86Subtarget *Subtarget) {
13193   if (DCI.isBeforeLegalizeOps())
13194     return SDValue();
13195
13196   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13197   if (R.getNode())
13198     return R;
13199
13200   // Want to form ANDNP nodes:
13201   // 1) In the hopes of then easily combining them with OR and AND nodes
13202   //    to form PBLEND/PSIGN.
13203   // 2) To match ANDN packed intrinsics
13204   EVT VT = N->getValueType(0);
13205   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13206     return SDValue();
13207
13208   SDValue N0 = N->getOperand(0);
13209   SDValue N1 = N->getOperand(1);
13210   DebugLoc DL = N->getDebugLoc();
13211
13212   // Check LHS for vnot
13213   if (N0.getOpcode() == ISD::XOR &&
13214       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13215       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13216     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13217
13218   // Check RHS for vnot
13219   if (N1.getOpcode() == ISD::XOR &&
13220       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13221       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13222     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13223
13224   return SDValue();
13225 }
13226
13227 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13228                                 TargetLowering::DAGCombinerInfo &DCI,
13229                                 const X86Subtarget *Subtarget) {
13230   if (DCI.isBeforeLegalizeOps())
13231     return SDValue();
13232
13233   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13234   if (R.getNode())
13235     return R;
13236
13237   EVT VT = N->getValueType(0);
13238   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13239     return SDValue();
13240
13241   SDValue N0 = N->getOperand(0);
13242   SDValue N1 = N->getOperand(1);
13243
13244   // look for psign/blend
13245   if (Subtarget->hasSSSE3()) {
13246     if (VT == MVT::v2i64) {
13247       // Canonicalize pandn to RHS
13248       if (N0.getOpcode() == X86ISD::ANDNP)
13249         std::swap(N0, N1);
13250       // or (and (m, x), (pandn m, y))
13251       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13252         SDValue Mask = N1.getOperand(0);
13253         SDValue X    = N1.getOperand(1);
13254         SDValue Y;
13255         if (N0.getOperand(0) == Mask)
13256           Y = N0.getOperand(1);
13257         if (N0.getOperand(1) == Mask)
13258           Y = N0.getOperand(0);
13259
13260         // Check to see if the mask appeared in both the AND and ANDNP and
13261         if (!Y.getNode())
13262           return SDValue();
13263
13264         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13265         if (Mask.getOpcode() != ISD::BITCAST ||
13266             X.getOpcode() != ISD::BITCAST ||
13267             Y.getOpcode() != ISD::BITCAST)
13268           return SDValue();
13269
13270         // Look through mask bitcast.
13271         Mask = Mask.getOperand(0);
13272         EVT MaskVT = Mask.getValueType();
13273
13274         // Validate that the Mask operand is a vector sra node.  The sra node
13275         // will be an intrinsic.
13276         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13277           return SDValue();
13278
13279         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13280         // there is no psrai.b
13281         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13282         case Intrinsic::x86_sse2_psrai_w:
13283         case Intrinsic::x86_sse2_psrai_d:
13284           break;
13285         default: return SDValue();
13286         }
13287
13288         // Check that the SRA is all signbits.
13289         SDValue SraC = Mask.getOperand(2);
13290         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13291         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13292         if ((SraAmt + 1) != EltBits)
13293           return SDValue();
13294
13295         DebugLoc DL = N->getDebugLoc();
13296
13297         // Now we know we at least have a plendvb with the mask val.  See if
13298         // we can form a psignb/w/d.
13299         // psign = x.type == y.type == mask.type && y = sub(0, x);
13300         X = X.getOperand(0);
13301         Y = Y.getOperand(0);
13302         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13303             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13304             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13305           unsigned Opc = 0;
13306           switch (EltBits) {
13307           case 8: Opc = X86ISD::PSIGNB; break;
13308           case 16: Opc = X86ISD::PSIGNW; break;
13309           case 32: Opc = X86ISD::PSIGND; break;
13310           default: break;
13311           }
13312           if (Opc) {
13313             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13314             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13315           }
13316         }
13317         // PBLENDVB only available on SSE 4.1
13318         if (!Subtarget->hasSSE41())
13319           return SDValue();
13320
13321         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13322         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13323         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13324         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
13325         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13326       }
13327     }
13328   }
13329
13330   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13331   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13332     std::swap(N0, N1);
13333   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13334     return SDValue();
13335   if (!N0.hasOneUse() || !N1.hasOneUse())
13336     return SDValue();
13337
13338   SDValue ShAmt0 = N0.getOperand(1);
13339   if (ShAmt0.getValueType() != MVT::i8)
13340     return SDValue();
13341   SDValue ShAmt1 = N1.getOperand(1);
13342   if (ShAmt1.getValueType() != MVT::i8)
13343     return SDValue();
13344   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13345     ShAmt0 = ShAmt0.getOperand(0);
13346   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13347     ShAmt1 = ShAmt1.getOperand(0);
13348
13349   DebugLoc DL = N->getDebugLoc();
13350   unsigned Opc = X86ISD::SHLD;
13351   SDValue Op0 = N0.getOperand(0);
13352   SDValue Op1 = N1.getOperand(0);
13353   if (ShAmt0.getOpcode() == ISD::SUB) {
13354     Opc = X86ISD::SHRD;
13355     std::swap(Op0, Op1);
13356     std::swap(ShAmt0, ShAmt1);
13357   }
13358
13359   unsigned Bits = VT.getSizeInBits();
13360   if (ShAmt1.getOpcode() == ISD::SUB) {
13361     SDValue Sum = ShAmt1.getOperand(0);
13362     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13363       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13364       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13365         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13366       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13367         return DAG.getNode(Opc, DL, VT,
13368                            Op0, Op1,
13369                            DAG.getNode(ISD::TRUNCATE, DL,
13370                                        MVT::i8, ShAmt0));
13371     }
13372   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13373     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13374     if (ShAmt0C &&
13375         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13376       return DAG.getNode(Opc, DL, VT,
13377                          N0.getOperand(0), N1.getOperand(0),
13378                          DAG.getNode(ISD::TRUNCATE, DL,
13379                                        MVT::i8, ShAmt0));
13380   }
13381
13382   return SDValue();
13383 }
13384
13385 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13386 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13387                                    const X86Subtarget *Subtarget) {
13388   StoreSDNode *St = cast<StoreSDNode>(N);
13389   EVT VT = St->getValue().getValueType();
13390   EVT StVT = St->getMemoryVT();
13391   DebugLoc dl = St->getDebugLoc();
13392   SDValue StoredVal = St->getOperand(1);
13393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13394
13395   // If we are saving a concatination of two XMM registers, perform two stores.
13396   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13397   // 128-bit ones. If in the future the cost becomes only one memory access the
13398   // first version would be better.
13399   if (VT.getSizeInBits() == 256 &&
13400     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13401     StoredVal.getNumOperands() == 2) {
13402
13403     SDValue Value0 = StoredVal.getOperand(0);
13404     SDValue Value1 = StoredVal.getOperand(1);
13405
13406     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13407     SDValue Ptr0 = St->getBasePtr();
13408     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13409
13410     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13411                                 St->getPointerInfo(), St->isVolatile(),
13412                                 St->isNonTemporal(), St->getAlignment());
13413     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13414                                 St->getPointerInfo(), St->isVolatile(),
13415                                 St->isNonTemporal(), St->getAlignment());
13416     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13417   }
13418
13419   // Optimize trunc store (of multiple scalars) to shuffle and store.
13420   // First, pack all of the elements in one place. Next, store to memory
13421   // in fewer chunks.
13422   if (St->isTruncatingStore() && VT.isVector()) {
13423     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13424     unsigned NumElems = VT.getVectorNumElements();
13425     assert(StVT != VT && "Cannot truncate to the same type");
13426     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13427     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13428
13429     // From, To sizes and ElemCount must be pow of two
13430     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13431     // We are going to use the original vector elt for storing.
13432     // accumulated smaller vector elements must be a multiple of bigger size.
13433     if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13434     unsigned SizeRatio  = FromSz / ToSz;
13435
13436     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13437
13438     // Create a type on which we perform the shuffle
13439     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13440             StVT.getScalarType(), NumElems*SizeRatio);
13441
13442     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13443
13444     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13445     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13446     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13447
13448     // Can't shuffle using an illegal type
13449     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13450
13451     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13452                                 DAG.getUNDEF(WideVec.getValueType()),
13453                                 ShuffleVec.data());
13454     // At this point all of the data is stored at the bottom of the
13455     // register. We now need to save it to mem.
13456
13457     // Find the largest store unit
13458     MVT StoreType = MVT::i8;
13459     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13460          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13461       MVT Tp = (MVT::SimpleValueType)tp;
13462       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13463         StoreType = Tp;
13464     }
13465
13466     // Bitcast the original vector into a vector of store-size units
13467     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13468             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13469     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13470     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13471     SmallVector<SDValue, 8> Chains;
13472     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13473                                         TLI.getPointerTy());
13474     SDValue Ptr = St->getBasePtr();
13475
13476     // Perform one or more big stores into memory.
13477     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13478       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13479                                    StoreType, ShuffWide,
13480                                    DAG.getIntPtrConstant(i));
13481       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13482                                 St->getPointerInfo(), St->isVolatile(),
13483                                 St->isNonTemporal(), St->getAlignment());
13484       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13485       Chains.push_back(Ch);
13486     }
13487
13488     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13489                                Chains.size());
13490   }
13491
13492
13493   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13494   // the FP state in cases where an emms may be missing.
13495   // A preferable solution to the general problem is to figure out the right
13496   // places to insert EMMS.  This qualifies as a quick hack.
13497
13498   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13499   if (VT.getSizeInBits() != 64)
13500     return SDValue();
13501
13502   const Function *F = DAG.getMachineFunction().getFunction();
13503   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13504   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13505     && Subtarget->hasSSE2();
13506   if ((VT.isVector() ||
13507        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13508       isa<LoadSDNode>(St->getValue()) &&
13509       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13510       St->getChain().hasOneUse() && !St->isVolatile()) {
13511     SDNode* LdVal = St->getValue().getNode();
13512     LoadSDNode *Ld = 0;
13513     int TokenFactorIndex = -1;
13514     SmallVector<SDValue, 8> Ops;
13515     SDNode* ChainVal = St->getChain().getNode();
13516     // Must be a store of a load.  We currently handle two cases:  the load
13517     // is a direct child, and it's under an intervening TokenFactor.  It is
13518     // possible to dig deeper under nested TokenFactors.
13519     if (ChainVal == LdVal)
13520       Ld = cast<LoadSDNode>(St->getChain());
13521     else if (St->getValue().hasOneUse() &&
13522              ChainVal->getOpcode() == ISD::TokenFactor) {
13523       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13524         if (ChainVal->getOperand(i).getNode() == LdVal) {
13525           TokenFactorIndex = i;
13526           Ld = cast<LoadSDNode>(St->getValue());
13527         } else
13528           Ops.push_back(ChainVal->getOperand(i));
13529       }
13530     }
13531
13532     if (!Ld || !ISD::isNormalLoad(Ld))
13533       return SDValue();
13534
13535     // If this is not the MMX case, i.e. we are just turning i64 load/store
13536     // into f64 load/store, avoid the transformation if there are multiple
13537     // uses of the loaded value.
13538     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13539       return SDValue();
13540
13541     DebugLoc LdDL = Ld->getDebugLoc();
13542     DebugLoc StDL = N->getDebugLoc();
13543     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13544     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13545     // pair instead.
13546     if (Subtarget->is64Bit() || F64IsLegal) {
13547       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13548       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13549                                   Ld->getPointerInfo(), Ld->isVolatile(),
13550                                   Ld->isNonTemporal(), Ld->getAlignment());
13551       SDValue NewChain = NewLd.getValue(1);
13552       if (TokenFactorIndex != -1) {
13553         Ops.push_back(NewChain);
13554         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13555                                Ops.size());
13556       }
13557       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13558                           St->getPointerInfo(),
13559                           St->isVolatile(), St->isNonTemporal(),
13560                           St->getAlignment());
13561     }
13562
13563     // Otherwise, lower to two pairs of 32-bit loads / stores.
13564     SDValue LoAddr = Ld->getBasePtr();
13565     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13566                                  DAG.getConstant(4, MVT::i32));
13567
13568     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13569                                Ld->getPointerInfo(),
13570                                Ld->isVolatile(), Ld->isNonTemporal(),
13571                                Ld->getAlignment());
13572     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13573                                Ld->getPointerInfo().getWithOffset(4),
13574                                Ld->isVolatile(), Ld->isNonTemporal(),
13575                                MinAlign(Ld->getAlignment(), 4));
13576
13577     SDValue NewChain = LoLd.getValue(1);
13578     if (TokenFactorIndex != -1) {
13579       Ops.push_back(LoLd);
13580       Ops.push_back(HiLd);
13581       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13582                              Ops.size());
13583     }
13584
13585     LoAddr = St->getBasePtr();
13586     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13587                          DAG.getConstant(4, MVT::i32));
13588
13589     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13590                                 St->getPointerInfo(),
13591                                 St->isVolatile(), St->isNonTemporal(),
13592                                 St->getAlignment());
13593     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13594                                 St->getPointerInfo().getWithOffset(4),
13595                                 St->isVolatile(),
13596                                 St->isNonTemporal(),
13597                                 MinAlign(St->getAlignment(), 4));
13598     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13599   }
13600   return SDValue();
13601 }
13602
13603 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13604 /// X86ISD::FXOR nodes.
13605 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13606   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13607   // F[X]OR(0.0, x) -> x
13608   // F[X]OR(x, 0.0) -> x
13609   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13610     if (C->getValueAPF().isPosZero())
13611       return N->getOperand(1);
13612   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13613     if (C->getValueAPF().isPosZero())
13614       return N->getOperand(0);
13615   return SDValue();
13616 }
13617
13618 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13619 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13620   // FAND(0.0, x) -> 0.0
13621   // FAND(x, 0.0) -> 0.0
13622   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13623     if (C->getValueAPF().isPosZero())
13624       return N->getOperand(0);
13625   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13626     if (C->getValueAPF().isPosZero())
13627       return N->getOperand(1);
13628   return SDValue();
13629 }
13630
13631 static SDValue PerformBTCombine(SDNode *N,
13632                                 SelectionDAG &DAG,
13633                                 TargetLowering::DAGCombinerInfo &DCI) {
13634   // BT ignores high bits in the bit index operand.
13635   SDValue Op1 = N->getOperand(1);
13636   if (Op1.hasOneUse()) {
13637     unsigned BitWidth = Op1.getValueSizeInBits();
13638     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13639     APInt KnownZero, KnownOne;
13640     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13641                                           !DCI.isBeforeLegalizeOps());
13642     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13643     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13644         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13645       DCI.CommitTargetLoweringOpt(TLO);
13646   }
13647   return SDValue();
13648 }
13649
13650 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13651   SDValue Op = N->getOperand(0);
13652   if (Op.getOpcode() == ISD::BITCAST)
13653     Op = Op.getOperand(0);
13654   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13655   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13656       VT.getVectorElementType().getSizeInBits() ==
13657       OpVT.getVectorElementType().getSizeInBits()) {
13658     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13659   }
13660   return SDValue();
13661 }
13662
13663 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13664   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13665   //           (and (i32 x86isd::setcc_carry), 1)
13666   // This eliminates the zext. This transformation is necessary because
13667   // ISD::SETCC is always legalized to i8.
13668   DebugLoc dl = N->getDebugLoc();
13669   SDValue N0 = N->getOperand(0);
13670   EVT VT = N->getValueType(0);
13671   if (N0.getOpcode() == ISD::AND &&
13672       N0.hasOneUse() &&
13673       N0.getOperand(0).hasOneUse()) {
13674     SDValue N00 = N0.getOperand(0);
13675     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13676       return SDValue();
13677     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13678     if (!C || C->getZExtValue() != 1)
13679       return SDValue();
13680     return DAG.getNode(ISD::AND, dl, VT,
13681                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13682                                    N00.getOperand(0), N00.getOperand(1)),
13683                        DAG.getConstant(1, VT));
13684   }
13685
13686   return SDValue();
13687 }
13688
13689 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13690 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13691   unsigned X86CC = N->getConstantOperandVal(0);
13692   SDValue EFLAG = N->getOperand(1);
13693   DebugLoc DL = N->getDebugLoc();
13694
13695   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13696   // a zext and produces an all-ones bit which is more useful than 0/1 in some
13697   // cases.
13698   if (X86CC == X86::COND_B)
13699     return DAG.getNode(ISD::AND, DL, MVT::i8,
13700                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13701                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
13702                        DAG.getConstant(1, MVT::i8));
13703
13704   return SDValue();
13705 }
13706
13707 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13708                                         const X86TargetLowering *XTLI) {
13709   SDValue Op0 = N->getOperand(0);
13710   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13711   // a 32-bit target where SSE doesn't support i64->FP operations.
13712   if (Op0.getOpcode() == ISD::LOAD) {
13713     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13714     EVT VT = Ld->getValueType(0);
13715     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13716         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13717         !XTLI->getSubtarget()->is64Bit() &&
13718         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13719       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13720                                           Ld->getChain(), Op0, DAG);
13721       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13722       return FILDChain;
13723     }
13724   }
13725   return SDValue();
13726 }
13727
13728 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13729 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13730                                  X86TargetLowering::DAGCombinerInfo &DCI) {
13731   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13732   // the result is either zero or one (depending on the input carry bit).
13733   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13734   if (X86::isZeroNode(N->getOperand(0)) &&
13735       X86::isZeroNode(N->getOperand(1)) &&
13736       // We don't have a good way to replace an EFLAGS use, so only do this when
13737       // dead right now.
13738       SDValue(N, 1).use_empty()) {
13739     DebugLoc DL = N->getDebugLoc();
13740     EVT VT = N->getValueType(0);
13741     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13742     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13743                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13744                                            DAG.getConstant(X86::COND_B,MVT::i8),
13745                                            N->getOperand(2)),
13746                                DAG.getConstant(1, VT));
13747     return DCI.CombineTo(N, Res1, CarryOut);
13748   }
13749
13750   return SDValue();
13751 }
13752
13753 // fold (add Y, (sete  X, 0)) -> adc  0, Y
13754 //      (add Y, (setne X, 0)) -> sbb -1, Y
13755 //      (sub (sete  X, 0), Y) -> sbb  0, Y
13756 //      (sub (setne X, 0), Y) -> adc -1, Y
13757 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13758   DebugLoc DL = N->getDebugLoc();
13759
13760   // Look through ZExts.
13761   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13762   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13763     return SDValue();
13764
13765   SDValue SetCC = Ext.getOperand(0);
13766   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13767     return SDValue();
13768
13769   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13770   if (CC != X86::COND_E && CC != X86::COND_NE)
13771     return SDValue();
13772
13773   SDValue Cmp = SetCC.getOperand(1);
13774   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13775       !X86::isZeroNode(Cmp.getOperand(1)) ||
13776       !Cmp.getOperand(0).getValueType().isInteger())
13777     return SDValue();
13778
13779   SDValue CmpOp0 = Cmp.getOperand(0);
13780   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13781                                DAG.getConstant(1, CmpOp0.getValueType()));
13782
13783   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13784   if (CC == X86::COND_NE)
13785     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13786                        DL, OtherVal.getValueType(), OtherVal,
13787                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13788   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13789                      DL, OtherVal.getValueType(), OtherVal,
13790                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13791 }
13792
13793 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13794   SDValue Op0 = N->getOperand(0);
13795   SDValue Op1 = N->getOperand(1);
13796
13797   // X86 can't encode an immediate LHS of a sub. See if we can push the
13798   // negation into a preceding instruction.
13799   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13800     // If the RHS of the sub is a XOR with one use and a constant, invert the
13801     // immediate. Then add one to the LHS of the sub so we can turn
13802     // X-Y -> X+~Y+1, saving one register.
13803     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13804         isa<ConstantSDNode>(Op1.getOperand(1))) {
13805       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13806       EVT VT = Op0.getValueType();
13807       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13808                                    Op1.getOperand(0),
13809                                    DAG.getConstant(~XorC, VT));
13810       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13811                          DAG.getConstant(C->getAPIntValue()+1, VT));
13812     }
13813   }
13814
13815   return OptimizeConditionalInDecrement(N, DAG);
13816 }
13817
13818 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13819                                              DAGCombinerInfo &DCI) const {
13820   SelectionDAG &DAG = DCI.DAG;
13821   switch (N->getOpcode()) {
13822   default: break;
13823   case ISD::EXTRACT_VECTOR_ELT:
13824     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13825   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
13826   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
13827   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
13828   case ISD::SUB:            return PerformSubCombine(N, DAG);
13829   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
13830   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
13831   case ISD::SHL:
13832   case ISD::SRA:
13833   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
13834   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
13835   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
13836   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
13837   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
13838   case X86ISD::FXOR:
13839   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
13840   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
13841   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
13842   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
13843   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
13844   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
13845   case X86ISD::SHUFPS:      // Handle all target specific shuffles
13846   case X86ISD::SHUFPD:
13847   case X86ISD::PALIGN:
13848   case X86ISD::PUNPCKHBW:
13849   case X86ISD::PUNPCKHWD:
13850   case X86ISD::PUNPCKHDQ:
13851   case X86ISD::PUNPCKHQDQ:
13852   case X86ISD::UNPCKHPS:
13853   case X86ISD::UNPCKHPD:
13854   case X86ISD::VUNPCKHPSY:
13855   case X86ISD::VUNPCKHPDY:
13856   case X86ISD::PUNPCKLBW:
13857   case X86ISD::PUNPCKLWD:
13858   case X86ISD::PUNPCKLDQ:
13859   case X86ISD::PUNPCKLQDQ:
13860   case X86ISD::UNPCKLPS:
13861   case X86ISD::UNPCKLPD:
13862   case X86ISD::VUNPCKLPSY:
13863   case X86ISD::VUNPCKLPDY:
13864   case X86ISD::MOVHLPS:
13865   case X86ISD::MOVLHPS:
13866   case X86ISD::PSHUFD:
13867   case X86ISD::PSHUFHW:
13868   case X86ISD::PSHUFLW:
13869   case X86ISD::MOVSS:
13870   case X86ISD::MOVSD:
13871   case X86ISD::VPERMILPS:
13872   case X86ISD::VPERMILPSY:
13873   case X86ISD::VPERMILPD:
13874   case X86ISD::VPERMILPDY:
13875   case X86ISD::VPERM2F128:
13876   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13877   }
13878
13879   return SDValue();
13880 }
13881
13882 /// isTypeDesirableForOp - Return true if the target has native support for
13883 /// the specified value type and it is 'desirable' to use the type for the
13884 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13885 /// instruction encodings are longer and some i16 instructions are slow.
13886 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13887   if (!isTypeLegal(VT))
13888     return false;
13889   if (VT != MVT::i16)
13890     return true;
13891
13892   switch (Opc) {
13893   default:
13894     return true;
13895   case ISD::LOAD:
13896   case ISD::SIGN_EXTEND:
13897   case ISD::ZERO_EXTEND:
13898   case ISD::ANY_EXTEND:
13899   case ISD::SHL:
13900   case ISD::SRL:
13901   case ISD::SUB:
13902   case ISD::ADD:
13903   case ISD::MUL:
13904   case ISD::AND:
13905   case ISD::OR:
13906   case ISD::XOR:
13907     return false;
13908   }
13909 }
13910
13911 /// IsDesirableToPromoteOp - This method query the target whether it is
13912 /// beneficial for dag combiner to promote the specified node. If true, it
13913 /// should return the desired promotion type by reference.
13914 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13915   EVT VT = Op.getValueType();
13916   if (VT != MVT::i16)
13917     return false;
13918
13919   bool Promote = false;
13920   bool Commute = false;
13921   switch (Op.getOpcode()) {
13922   default: break;
13923   case ISD::LOAD: {
13924     LoadSDNode *LD = cast<LoadSDNode>(Op);
13925     // If the non-extending load has a single use and it's not live out, then it
13926     // might be folded.
13927     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13928                                                      Op.hasOneUse()*/) {
13929       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13930              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13931         // The only case where we'd want to promote LOAD (rather then it being
13932         // promoted as an operand is when it's only use is liveout.
13933         if (UI->getOpcode() != ISD::CopyToReg)
13934           return false;
13935       }
13936     }
13937     Promote = true;
13938     break;
13939   }
13940   case ISD::SIGN_EXTEND:
13941   case ISD::ZERO_EXTEND:
13942   case ISD::ANY_EXTEND:
13943     Promote = true;
13944     break;
13945   case ISD::SHL:
13946   case ISD::SRL: {
13947     SDValue N0 = Op.getOperand(0);
13948     // Look out for (store (shl (load), x)).
13949     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13950       return false;
13951     Promote = true;
13952     break;
13953   }
13954   case ISD::ADD:
13955   case ISD::MUL:
13956   case ISD::AND:
13957   case ISD::OR:
13958   case ISD::XOR:
13959     Commute = true;
13960     // fallthrough
13961   case ISD::SUB: {
13962     SDValue N0 = Op.getOperand(0);
13963     SDValue N1 = Op.getOperand(1);
13964     if (!Commute && MayFoldLoad(N1))
13965       return false;
13966     // Avoid disabling potential load folding opportunities.
13967     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13968       return false;
13969     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13970       return false;
13971     Promote = true;
13972   }
13973   }
13974
13975   PVT = MVT::i32;
13976   return Promote;
13977 }
13978
13979 //===----------------------------------------------------------------------===//
13980 //                           X86 Inline Assembly Support
13981 //===----------------------------------------------------------------------===//
13982
13983 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
13984   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13985
13986   std::string AsmStr = IA->getAsmString();
13987
13988   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
13989   SmallVector<StringRef, 4> AsmPieces;
13990   SplitString(AsmStr, AsmPieces, ";\n");
13991
13992   switch (AsmPieces.size()) {
13993   default: return false;
13994   case 1:
13995     AsmStr = AsmPieces[0];
13996     AsmPieces.clear();
13997     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
13998
13999     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14000     // we will turn this bswap into something that will be lowered to logical ops
14001     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14002     // so don't worry about this.
14003     // bswap $0
14004     if (AsmPieces.size() == 2 &&
14005         (AsmPieces[0] == "bswap" ||
14006          AsmPieces[0] == "bswapq" ||
14007          AsmPieces[0] == "bswapl") &&
14008         (AsmPieces[1] == "$0" ||
14009          AsmPieces[1] == "${0:q}")) {
14010       // No need to check constraints, nothing other than the equivalent of
14011       // "=r,0" would be valid here.
14012       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14013       if (!Ty || Ty->getBitWidth() % 16 != 0)
14014         return false;
14015       return IntrinsicLowering::LowerToByteSwap(CI);
14016     }
14017     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14018     if (CI->getType()->isIntegerTy(16) &&
14019         AsmPieces.size() == 3 &&
14020         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14021         AsmPieces[1] == "$$8," &&
14022         AsmPieces[2] == "${0:w}" &&
14023         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14024       AsmPieces.clear();
14025       const std::string &ConstraintsStr = IA->getConstraintString();
14026       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14027       std::sort(AsmPieces.begin(), AsmPieces.end());
14028       if (AsmPieces.size() == 4 &&
14029           AsmPieces[0] == "~{cc}" &&
14030           AsmPieces[1] == "~{dirflag}" &&
14031           AsmPieces[2] == "~{flags}" &&
14032           AsmPieces[3] == "~{fpsr}") {
14033         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14034         if (!Ty || Ty->getBitWidth() % 16 != 0)
14035           return false;
14036         return IntrinsicLowering::LowerToByteSwap(CI);
14037       }
14038     }
14039     break;
14040   case 3:
14041     if (CI->getType()->isIntegerTy(32) &&
14042         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14043       SmallVector<StringRef, 4> Words;
14044       SplitString(AsmPieces[0], Words, " \t,");
14045       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14046           Words[2] == "${0:w}") {
14047         Words.clear();
14048         SplitString(AsmPieces[1], Words, " \t,");
14049         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14050             Words[2] == "$0") {
14051           Words.clear();
14052           SplitString(AsmPieces[2], Words, " \t,");
14053           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14054               Words[2] == "${0:w}") {
14055             AsmPieces.clear();
14056             const std::string &ConstraintsStr = IA->getConstraintString();
14057             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14058             std::sort(AsmPieces.begin(), AsmPieces.end());
14059             if (AsmPieces.size() == 4 &&
14060                 AsmPieces[0] == "~{cc}" &&
14061                 AsmPieces[1] == "~{dirflag}" &&
14062                 AsmPieces[2] == "~{flags}" &&
14063                 AsmPieces[3] == "~{fpsr}") {
14064               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14065               if (!Ty || Ty->getBitWidth() % 16 != 0)
14066                 return false;
14067               return IntrinsicLowering::LowerToByteSwap(CI);
14068             }
14069           }
14070         }
14071       }
14072     }
14073
14074     if (CI->getType()->isIntegerTy(64)) {
14075       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14076       if (Constraints.size() >= 2 &&
14077           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14078           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14079         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14080         SmallVector<StringRef, 4> Words;
14081         SplitString(AsmPieces[0], Words, " \t");
14082         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14083           Words.clear();
14084           SplitString(AsmPieces[1], Words, " \t");
14085           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14086             Words.clear();
14087             SplitString(AsmPieces[2], Words, " \t,");
14088             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14089                 Words[2] == "%edx") {
14090               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14091               if (!Ty || Ty->getBitWidth() % 16 != 0)
14092                 return false;
14093               return IntrinsicLowering::LowerToByteSwap(CI);
14094             }
14095           }
14096         }
14097       }
14098     }
14099     break;
14100   }
14101   return false;
14102 }
14103
14104
14105
14106 /// getConstraintType - Given a constraint letter, return the type of
14107 /// constraint it is for this target.
14108 X86TargetLowering::ConstraintType
14109 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14110   if (Constraint.size() == 1) {
14111     switch (Constraint[0]) {
14112     case 'R':
14113     case 'q':
14114     case 'Q':
14115     case 'f':
14116     case 't':
14117     case 'u':
14118     case 'y':
14119     case 'x':
14120     case 'Y':
14121     case 'l':
14122       return C_RegisterClass;
14123     case 'a':
14124     case 'b':
14125     case 'c':
14126     case 'd':
14127     case 'S':
14128     case 'D':
14129     case 'A':
14130       return C_Register;
14131     case 'I':
14132     case 'J':
14133     case 'K':
14134     case 'L':
14135     case 'M':
14136     case 'N':
14137     case 'G':
14138     case 'C':
14139     case 'e':
14140     case 'Z':
14141       return C_Other;
14142     default:
14143       break;
14144     }
14145   }
14146   return TargetLowering::getConstraintType(Constraint);
14147 }
14148
14149 /// Examine constraint type and operand type and determine a weight value.
14150 /// This object must already have been set up with the operand type
14151 /// and the current alternative constraint selected.
14152 TargetLowering::ConstraintWeight
14153   X86TargetLowering::getSingleConstraintMatchWeight(
14154     AsmOperandInfo &info, const char *constraint) const {
14155   ConstraintWeight weight = CW_Invalid;
14156   Value *CallOperandVal = info.CallOperandVal;
14157     // If we don't have a value, we can't do a match,
14158     // but allow it at the lowest weight.
14159   if (CallOperandVal == NULL)
14160     return CW_Default;
14161   Type *type = CallOperandVal->getType();
14162   // Look at the constraint type.
14163   switch (*constraint) {
14164   default:
14165     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14166   case 'R':
14167   case 'q':
14168   case 'Q':
14169   case 'a':
14170   case 'b':
14171   case 'c':
14172   case 'd':
14173   case 'S':
14174   case 'D':
14175   case 'A':
14176     if (CallOperandVal->getType()->isIntegerTy())
14177       weight = CW_SpecificReg;
14178     break;
14179   case 'f':
14180   case 't':
14181   case 'u':
14182       if (type->isFloatingPointTy())
14183         weight = CW_SpecificReg;
14184       break;
14185   case 'y':
14186       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14187         weight = CW_SpecificReg;
14188       break;
14189   case 'x':
14190   case 'Y':
14191     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14192       weight = CW_Register;
14193     break;
14194   case 'I':
14195     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14196       if (C->getZExtValue() <= 31)
14197         weight = CW_Constant;
14198     }
14199     break;
14200   case 'J':
14201     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14202       if (C->getZExtValue() <= 63)
14203         weight = CW_Constant;
14204     }
14205     break;
14206   case 'K':
14207     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14208       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14209         weight = CW_Constant;
14210     }
14211     break;
14212   case 'L':
14213     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14214       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14215         weight = CW_Constant;
14216     }
14217     break;
14218   case 'M':
14219     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14220       if (C->getZExtValue() <= 3)
14221         weight = CW_Constant;
14222     }
14223     break;
14224   case 'N':
14225     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14226       if (C->getZExtValue() <= 0xff)
14227         weight = CW_Constant;
14228     }
14229     break;
14230   case 'G':
14231   case 'C':
14232     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14233       weight = CW_Constant;
14234     }
14235     break;
14236   case 'e':
14237     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14238       if ((C->getSExtValue() >= -0x80000000LL) &&
14239           (C->getSExtValue() <= 0x7fffffffLL))
14240         weight = CW_Constant;
14241     }
14242     break;
14243   case 'Z':
14244     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14245       if (C->getZExtValue() <= 0xffffffff)
14246         weight = CW_Constant;
14247     }
14248     break;
14249   }
14250   return weight;
14251 }
14252
14253 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14254 /// with another that has more specific requirements based on the type of the
14255 /// corresponding operand.
14256 const char *X86TargetLowering::
14257 LowerXConstraint(EVT ConstraintVT) const {
14258   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14259   // 'f' like normal targets.
14260   if (ConstraintVT.isFloatingPoint()) {
14261     if (Subtarget->hasXMMInt())
14262       return "Y";
14263     if (Subtarget->hasXMM())
14264       return "x";
14265   }
14266
14267   return TargetLowering::LowerXConstraint(ConstraintVT);
14268 }
14269
14270 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14271 /// vector.  If it is invalid, don't add anything to Ops.
14272 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14273                                                      std::string &Constraint,
14274                                                      std::vector<SDValue>&Ops,
14275                                                      SelectionDAG &DAG) const {
14276   SDValue Result(0, 0);
14277
14278   // Only support length 1 constraints for now.
14279   if (Constraint.length() > 1) return;
14280
14281   char ConstraintLetter = Constraint[0];
14282   switch (ConstraintLetter) {
14283   default: break;
14284   case 'I':
14285     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14286       if (C->getZExtValue() <= 31) {
14287         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14288         break;
14289       }
14290     }
14291     return;
14292   case 'J':
14293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14294       if (C->getZExtValue() <= 63) {
14295         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14296         break;
14297       }
14298     }
14299     return;
14300   case 'K':
14301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14302       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14303         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14304         break;
14305       }
14306     }
14307     return;
14308   case 'N':
14309     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14310       if (C->getZExtValue() <= 255) {
14311         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14312         break;
14313       }
14314     }
14315     return;
14316   case 'e': {
14317     // 32-bit signed value
14318     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14319       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14320                                            C->getSExtValue())) {
14321         // Widen to 64 bits here to get it sign extended.
14322         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14323         break;
14324       }
14325     // FIXME gcc accepts some relocatable values here too, but only in certain
14326     // memory models; it's complicated.
14327     }
14328     return;
14329   }
14330   case 'Z': {
14331     // 32-bit unsigned value
14332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14333       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14334                                            C->getZExtValue())) {
14335         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14336         break;
14337       }
14338     }
14339     // FIXME gcc accepts some relocatable values here too, but only in certain
14340     // memory models; it's complicated.
14341     return;
14342   }
14343   case 'i': {
14344     // Literal immediates are always ok.
14345     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14346       // Widen to 64 bits here to get it sign extended.
14347       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14348       break;
14349     }
14350
14351     // In any sort of PIC mode addresses need to be computed at runtime by
14352     // adding in a register or some sort of table lookup.  These can't
14353     // be used as immediates.
14354     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14355       return;
14356
14357     // If we are in non-pic codegen mode, we allow the address of a global (with
14358     // an optional displacement) to be used with 'i'.
14359     GlobalAddressSDNode *GA = 0;
14360     int64_t Offset = 0;
14361
14362     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14363     while (1) {
14364       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14365         Offset += GA->getOffset();
14366         break;
14367       } else if (Op.getOpcode() == ISD::ADD) {
14368         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14369           Offset += C->getZExtValue();
14370           Op = Op.getOperand(0);
14371           continue;
14372         }
14373       } else if (Op.getOpcode() == ISD::SUB) {
14374         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14375           Offset += -C->getZExtValue();
14376           Op = Op.getOperand(0);
14377           continue;
14378         }
14379       }
14380
14381       // Otherwise, this isn't something we can handle, reject it.
14382       return;
14383     }
14384
14385     const GlobalValue *GV = GA->getGlobal();
14386     // If we require an extra load to get this address, as in PIC mode, we
14387     // can't accept it.
14388     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14389                                                         getTargetMachine())))
14390       return;
14391
14392     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14393                                         GA->getValueType(0), Offset);
14394     break;
14395   }
14396   }
14397
14398   if (Result.getNode()) {
14399     Ops.push_back(Result);
14400     return;
14401   }
14402   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14403 }
14404
14405 std::pair<unsigned, const TargetRegisterClass*>
14406 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14407                                                 EVT VT) const {
14408   // First, see if this is a constraint that directly corresponds to an LLVM
14409   // register class.
14410   if (Constraint.size() == 1) {
14411     // GCC Constraint Letters
14412     switch (Constraint[0]) {
14413     default: break;
14414       // TODO: Slight differences here in allocation order and leaving
14415       // RIP in the class. Do they matter any more here than they do
14416       // in the normal allocation?
14417     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14418       if (Subtarget->is64Bit()) {
14419         if (VT == MVT::i32 || VT == MVT::f32)
14420           return std::make_pair(0U, X86::GR32RegisterClass);
14421         else if (VT == MVT::i16)
14422           return std::make_pair(0U, X86::GR16RegisterClass);
14423         else if (VT == MVT::i8 || VT == MVT::i1)
14424           return std::make_pair(0U, X86::GR8RegisterClass);
14425         else if (VT == MVT::i64 || VT == MVT::f64)
14426           return std::make_pair(0U, X86::GR64RegisterClass);
14427         break;
14428       }
14429       // 32-bit fallthrough
14430     case 'Q':   // Q_REGS
14431       if (VT == MVT::i32 || VT == MVT::f32)
14432         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14433       else if (VT == MVT::i16)
14434         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14435       else if (VT == MVT::i8 || VT == MVT::i1)
14436         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14437       else if (VT == MVT::i64)
14438         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14439       break;
14440     case 'r':   // GENERAL_REGS
14441     case 'l':   // INDEX_REGS
14442       if (VT == MVT::i8 || VT == MVT::i1)
14443         return std::make_pair(0U, X86::GR8RegisterClass);
14444       if (VT == MVT::i16)
14445         return std::make_pair(0U, X86::GR16RegisterClass);
14446       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14447         return std::make_pair(0U, X86::GR32RegisterClass);
14448       return std::make_pair(0U, X86::GR64RegisterClass);
14449     case 'R':   // LEGACY_REGS
14450       if (VT == MVT::i8 || VT == MVT::i1)
14451         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14452       if (VT == MVT::i16)
14453         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14454       if (VT == MVT::i32 || !Subtarget->is64Bit())
14455         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14456       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14457     case 'f':  // FP Stack registers.
14458       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14459       // value to the correct fpstack register class.
14460       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14461         return std::make_pair(0U, X86::RFP32RegisterClass);
14462       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14463         return std::make_pair(0U, X86::RFP64RegisterClass);
14464       return std::make_pair(0U, X86::RFP80RegisterClass);
14465     case 'y':   // MMX_REGS if MMX allowed.
14466       if (!Subtarget->hasMMX()) break;
14467       return std::make_pair(0U, X86::VR64RegisterClass);
14468     case 'Y':   // SSE_REGS if SSE2 allowed
14469       if (!Subtarget->hasXMMInt()) break;
14470       // FALL THROUGH.
14471     case 'x':   // SSE_REGS if SSE1 allowed
14472       if (!Subtarget->hasXMM()) break;
14473
14474       switch (VT.getSimpleVT().SimpleTy) {
14475       default: break;
14476       // Scalar SSE types.
14477       case MVT::f32:
14478       case MVT::i32:
14479         return std::make_pair(0U, X86::FR32RegisterClass);
14480       case MVT::f64:
14481       case MVT::i64:
14482         return std::make_pair(0U, X86::FR64RegisterClass);
14483       // Vector types.
14484       case MVT::v16i8:
14485       case MVT::v8i16:
14486       case MVT::v4i32:
14487       case MVT::v2i64:
14488       case MVT::v4f32:
14489       case MVT::v2f64:
14490         return std::make_pair(0U, X86::VR128RegisterClass);
14491       }
14492       break;
14493     }
14494   }
14495
14496   // Use the default implementation in TargetLowering to convert the register
14497   // constraint into a member of a register class.
14498   std::pair<unsigned, const TargetRegisterClass*> Res;
14499   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14500
14501   // Not found as a standard register?
14502   if (Res.second == 0) {
14503     // Map st(0) -> st(7) -> ST0
14504     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14505         tolower(Constraint[1]) == 's' &&
14506         tolower(Constraint[2]) == 't' &&
14507         Constraint[3] == '(' &&
14508         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14509         Constraint[5] == ')' &&
14510         Constraint[6] == '}') {
14511
14512       Res.first = X86::ST0+Constraint[4]-'0';
14513       Res.second = X86::RFP80RegisterClass;
14514       return Res;
14515     }
14516
14517     // GCC allows "st(0)" to be called just plain "st".
14518     if (StringRef("{st}").equals_lower(Constraint)) {
14519       Res.first = X86::ST0;
14520       Res.second = X86::RFP80RegisterClass;
14521       return Res;
14522     }
14523
14524     // flags -> EFLAGS
14525     if (StringRef("{flags}").equals_lower(Constraint)) {
14526       Res.first = X86::EFLAGS;
14527       Res.second = X86::CCRRegisterClass;
14528       return Res;
14529     }
14530
14531     // 'A' means EAX + EDX.
14532     if (Constraint == "A") {
14533       Res.first = X86::EAX;
14534       Res.second = X86::GR32_ADRegisterClass;
14535       return Res;
14536     }
14537     return Res;
14538   }
14539
14540   // Otherwise, check to see if this is a register class of the wrong value
14541   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14542   // turn into {ax},{dx}.
14543   if (Res.second->hasType(VT))
14544     return Res;   // Correct type already, nothing to do.
14545
14546   // All of the single-register GCC register classes map their values onto
14547   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14548   // really want an 8-bit or 32-bit register, map to the appropriate register
14549   // class and return the appropriate register.
14550   if (Res.second == X86::GR16RegisterClass) {
14551     if (VT == MVT::i8) {
14552       unsigned DestReg = 0;
14553       switch (Res.first) {
14554       default: break;
14555       case X86::AX: DestReg = X86::AL; break;
14556       case X86::DX: DestReg = X86::DL; break;
14557       case X86::CX: DestReg = X86::CL; break;
14558       case X86::BX: DestReg = X86::BL; break;
14559       }
14560       if (DestReg) {
14561         Res.first = DestReg;
14562         Res.second = X86::GR8RegisterClass;
14563       }
14564     } else if (VT == MVT::i32) {
14565       unsigned DestReg = 0;
14566       switch (Res.first) {
14567       default: break;
14568       case X86::AX: DestReg = X86::EAX; break;
14569       case X86::DX: DestReg = X86::EDX; break;
14570       case X86::CX: DestReg = X86::ECX; break;
14571       case X86::BX: DestReg = X86::EBX; break;
14572       case X86::SI: DestReg = X86::ESI; break;
14573       case X86::DI: DestReg = X86::EDI; break;
14574       case X86::BP: DestReg = X86::EBP; break;
14575       case X86::SP: DestReg = X86::ESP; break;
14576       }
14577       if (DestReg) {
14578         Res.first = DestReg;
14579         Res.second = X86::GR32RegisterClass;
14580       }
14581     } else if (VT == MVT::i64) {
14582       unsigned DestReg = 0;
14583       switch (Res.first) {
14584       default: break;
14585       case X86::AX: DestReg = X86::RAX; break;
14586       case X86::DX: DestReg = X86::RDX; break;
14587       case X86::CX: DestReg = X86::RCX; break;
14588       case X86::BX: DestReg = X86::RBX; break;
14589       case X86::SI: DestReg = X86::RSI; break;
14590       case X86::DI: DestReg = X86::RDI; break;
14591       case X86::BP: DestReg = X86::RBP; break;
14592       case X86::SP: DestReg = X86::RSP; break;
14593       }
14594       if (DestReg) {
14595         Res.first = DestReg;
14596         Res.second = X86::GR64RegisterClass;
14597       }
14598     }
14599   } else if (Res.second == X86::FR32RegisterClass ||
14600              Res.second == X86::FR64RegisterClass ||
14601              Res.second == X86::VR128RegisterClass) {
14602     // Handle references to XMM physical registers that got mapped into the
14603     // wrong class.  This can happen with constraints like {xmm0} where the
14604     // target independent register mapper will just pick the first match it can
14605     // find, ignoring the required type.
14606     if (VT == MVT::f32)
14607       Res.second = X86::FR32RegisterClass;
14608     else if (VT == MVT::f64)
14609       Res.second = X86::FR64RegisterClass;
14610     else if (X86::VR128RegisterClass->hasType(VT))
14611       Res.second = X86::VR128RegisterClass;
14612   }
14613
14614   return Res;
14615 }