Add X86 LZCNT instruction. Including instruction selection support.
[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();
173   X86ScalarSSEf32 = Subtarget->hasXMM();
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   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187   // For 64-bit since we have so many registers use the ILP scheduler, for
188   // 32-bit code use the register pressure specific scheduling.
189   if (Subtarget->is64Bit())
190     setSchedulingPreference(Sched::ILP);
191   else
192     setSchedulingPreference(Sched::RegPressure);
193   setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196     // Setup Windows compiler runtime calls.
197     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199     setLibcallName(RTLIB::SREM_I64, "_allrem");
200     setLibcallName(RTLIB::UREM_I64, "_aullrem");
201     setLibcallName(RTLIB::MUL_I64, "_allmul");
202     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211   }
212
213   if (Subtarget->isTargetDarwin()) {
214     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215     setUseUnderscoreSetJmp(false);
216     setUseUnderscoreLongJmp(false);
217   } else if (Subtarget->isTargetMingw()) {
218     // MS runtime is weird: it exports _setjmp, but longjmp!
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(false);
221   } else {
222     setUseUnderscoreSetJmp(true);
223     setUseUnderscoreLongJmp(true);
224   }
225
226   // Set up the register classes.
227   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230   if (Subtarget->is64Bit())
231     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235   // We don't accept any truncstore of integer registers.
236   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243   // SETOEQ and SETUNE require checking two conditions.
244   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252   // operation.
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257   if (Subtarget->is64Bit()) {
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260   } else if (!UseSoftFloat) {
261     // We have an algorithm for SSE2->double, and we turn this into a
262     // 64-bit FILD followed by conditional FADD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264     // We have an algorithm for SSE2, and we turn this into a 64-bit
265     // FILD for other targets.
266     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267   }
268
269   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270   // this operation.
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274   if (!UseSoftFloat) {
275     // SSE has no i16 to fp conversion, only i32
276     if (X86ScalarSSEf32) {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278       // f32 and f64 cases are Legal, f80 case is not
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     } else {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283     }
284   } else {
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287   }
288
289   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290   // are Legal, f80 is custom lowered.
291   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295   // this operation.
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299   if (X86ScalarSSEf32) {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301     // f32 and f64 cases are Legal, f80 case is not
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   } else {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306   }
307
308   // Handle FP_TO_UINT by promoting the destination to a larger signed
309   // conversion.
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314   if (Subtarget->is64Bit()) {
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317   } else if (!UseSoftFloat) {
318     // Since AVX is a superset of SSE3, only check for SSE here.
319     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320       // Expand FP_TO_UINT into a select.
321       // FIXME: We would like to use a Custom expander here eventually to do
322       // the optimal thing for SSE vs. the default expansion in the legalizer.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324     else
325       // With SSE3 we can use fisttpll to convert to a signed i64; without
326       // SSE, we're stuck with a fistpll.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328   }
329
330   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331   if (!X86ScalarSSEf64) {
332     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334     if (Subtarget->is64Bit()) {
335       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336       // Without SSE, i64->f64 goes through memory.
337       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338     }
339   }
340
341   // Scalar integer divide and remainder are lowered to use operations that
342   // produce two results, to match the available instructions. This exposes
343   // the two-result form to trivial CSE, which is able to combine x/y and x%y
344   // into a single instruction.
345   //
346   // Scalar integer multiply-high is also lowered to use two-result
347   // operations, to match the available instructions. However, plain multiply
348   // (low) operations are left as Legal, as there are single-result
349   // instructions for this in x86. Using the two-result multiply instructions
350   // when both high and low results are needed must be arranged by dagcombine.
351   for (unsigned i = 0, e = 4; i != e; ++i) {
352     MVT VT = IntVTs[i];
353     setOperationAction(ISD::MULHS, VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::SDIV, VT, Expand);
356     setOperationAction(ISD::UDIV, VT, Expand);
357     setOperationAction(ISD::SREM, VT, Expand);
358     setOperationAction(ISD::UREM, VT, Expand);
359
360     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361     setOperationAction(ISD::ADDC, VT, Custom);
362     setOperationAction(ISD::ADDE, VT, Custom);
363     setOperationAction(ISD::SUBC, VT, Custom);
364     setOperationAction(ISD::SUBE, VT, Custom);
365   }
366
367   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371   if (Subtarget->is64Bit())
372     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
383   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
384   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
385   if (Subtarget->is64Bit())
386     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
387
388   if (Subtarget->hasLZCNT()) {
389     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
390   } else {
391     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
392     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
393     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
396   }
397
398   if (Subtarget->hasPOPCNT()) {
399     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
400   } else {
401     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
403     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
404     if (Subtarget->is64Bit())
405       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
406   }
407
408   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
409   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
410
411   // These should be promoted to a larger select which is supported.
412   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
413   // X86 wants to expand cmov itself.
414   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
415   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
416   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
420   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
421   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
422   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
426   if (Subtarget->is64Bit()) {
427     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
428     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
429   }
430   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
431
432   // Darwin ABI issue.
433   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
434   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
437   if (Subtarget->is64Bit())
438     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
439   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
440   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
441   if (Subtarget->is64Bit()) {
442     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
443     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
444     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
445     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
446     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
447   }
448   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
449   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
456   }
457
458   if (Subtarget->hasXMM())
459     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
460
461   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // On X86 and X86-64, atomic operations are lowered to locked instructions.
465   // Locked instructions, in turn, have implicit fence semantics (all memory
466   // operations are flushed before issuing the locked instruction, and they
467   // are not buffered), so we can fold away the common pattern of
468   // fence-atomic-fence.
469   setShouldFoldAtomicFences(true);
470
471   // Expand certain atomics
472   for (unsigned i = 0, e = 4; i != e; ++i) {
473     MVT VT = IntVTs[i];
474     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
475     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
476     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
477   }
478
479   if (!Subtarget->is64Bit()) {
480     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
482     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
483     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
484     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
488   }
489
490   if (Subtarget->hasCmpxchg16b()) {
491     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
492   }
493
494   // FIXME - use subtarget debug flags
495   if (!Subtarget->isTargetDarwin() &&
496       !Subtarget->isTargetELF() &&
497       !Subtarget->isTargetCygMing()) {
498     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
499   }
500
501   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
502   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
503   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
504   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
505   if (Subtarget->is64Bit()) {
506     setExceptionPointerRegister(X86::RAX);
507     setExceptionSelectorRegister(X86::RDX);
508   } else {
509     setExceptionPointerRegister(X86::EAX);
510     setExceptionSelectorRegister(X86::EDX);
511   }
512   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
513   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
514
515   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
516   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
517
518   setOperationAction(ISD::TRAP, MVT::Other, Legal);
519
520   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
521   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
522   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
523   if (Subtarget->is64Bit()) {
524     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
525     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
526   } else {
527     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
528     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
529   }
530
531   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
532   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
533
534   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
535     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
536                        MVT::i64 : MVT::i32, Custom);
537   else if (EnableSegmentedStacks)
538     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539                        MVT::i64 : MVT::i32, Custom);
540   else
541     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542                        MVT::i64 : MVT::i32, Expand);
543
544   if (!UseSoftFloat && X86ScalarSSEf64) {
545     // f32 and f64 use SSE.
546     // Set up the FP register classes.
547     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
548     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
549
550     // Use ANDPD to simulate FABS.
551     setOperationAction(ISD::FABS , MVT::f64, Custom);
552     setOperationAction(ISD::FABS , MVT::f32, Custom);
553
554     // Use XORP to simulate FNEG.
555     setOperationAction(ISD::FNEG , MVT::f64, Custom);
556     setOperationAction(ISD::FNEG , MVT::f32, Custom);
557
558     // Use ANDPD and ORPD to simulate FCOPYSIGN.
559     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
560     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
561
562     // Lower this to FGETSIGNx86 plus an AND.
563     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
564     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN , MVT::f64, Expand);
568     setOperationAction(ISD::FCOS , MVT::f64, Expand);
569     setOperationAction(ISD::FSIN , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS , MVT::f32, Expand);
571
572     // Expand FP immediates into loads from the stack, except for the special
573     // cases we handle.
574     addLegalFPImmediate(APFloat(+0.0)); // xorpd
575     addLegalFPImmediate(APFloat(+0.0f)); // xorps
576   } else if (!UseSoftFloat && X86ScalarSSEf32) {
577     // Use SSE for f32, x87 for f64.
578     // Set up the FP register classes.
579     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
580     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
581
582     // Use ANDPS to simulate FABS.
583     setOperationAction(ISD::FABS , MVT::f32, Custom);
584
585     // Use XORP to simulate FNEG.
586     setOperationAction(ISD::FNEG , MVT::f32, Custom);
587
588     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
589
590     // Use ANDPS and ORPS to simulate FCOPYSIGN.
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
593
594     // We don't support sin/cos/fmod
595     setOperationAction(ISD::FSIN , MVT::f32, Expand);
596     setOperationAction(ISD::FCOS , MVT::f32, Expand);
597
598     // Special cases we handle for FP constants.
599     addLegalFPImmediate(APFloat(+0.0f)); // xorps
600     addLegalFPImmediate(APFloat(+0.0)); // FLD0
601     addLegalFPImmediate(APFloat(+1.0)); // FLD1
602     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
603     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
604
605     if (!UnsafeFPMath) {
606       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
607       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
608     }
609   } else if (!UseSoftFloat) {
610     // f32 and f64 in x87.
611     // Set up the FP register classes.
612     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
613     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
614
615     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
616     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
617     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
618     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
619
620     if (!UnsafeFPMath) {
621       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623     }
624     addLegalFPImmediate(APFloat(+0.0)); // FLD0
625     addLegalFPImmediate(APFloat(+1.0)); // FLD1
626     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
627     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
628     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
629     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
630     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
631     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
632   }
633
634   // We don't support FMA.
635   setOperationAction(ISD::FMA, MVT::f64, Expand);
636   setOperationAction(ISD::FMA, MVT::f32, Expand);
637
638   // Long double always uses X87.
639   if (!UseSoftFloat) {
640     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
641     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
643     {
644       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
645       addLegalFPImmediate(TmpFlt);  // FLD0
646       TmpFlt.changeSign();
647       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
648
649       bool ignored;
650       APFloat TmpFlt2(+1.0);
651       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
652                       &ignored);
653       addLegalFPImmediate(TmpFlt2);  // FLD1
654       TmpFlt2.changeSign();
655       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
656     }
657
658     if (!UnsafeFPMath) {
659       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
660       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
661     }
662
663     setOperationAction(ISD::FMA, MVT::f80, Expand);
664   }
665
666   // Always use a library call for pow.
667   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
668   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
669   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
670
671   setOperationAction(ISD::FLOG, MVT::f80, Expand);
672   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
673   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
674   setOperationAction(ISD::FEXP, MVT::f80, Expand);
675   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
676
677   // First set operation action for all vector types to either promote
678   // (for widening) or expand (for scalarization). Then we will selectively
679   // turn on ones that can be effectively codegen'd.
680   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
681        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
682     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
697     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
699     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
700     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
732     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
737     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
738          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
739       setTruncStoreAction((MVT::SimpleValueType)VT,
740                           (MVT::SimpleValueType)InnerVT, Expand);
741     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
742     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
743     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
744   }
745
746   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
747   // with -msoft-float, disable use of MMX as well.
748   if (!UseSoftFloat && Subtarget->hasMMX()) {
749     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
750     // No operations on x86mmx supported, everything uses intrinsics.
751   }
752
753   // MMX-sized vectors (other than x86mmx) are expected to be expanded
754   // into smaller operations.
755   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
756   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
757   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
758   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
759   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
760   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
761   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
762   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
763   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
764   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
765   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
766   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
767   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
769   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
770   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
771   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
772   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
773   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
774   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
777   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
778   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
779   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
780   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
781   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
782   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
783   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
784
785   if (!UseSoftFloat && Subtarget->hasXMM()) {
786     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
787
788     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
789     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
790     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
791     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
792     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
793     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
794     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
795     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
796     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
797     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
798     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
799     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
800   }
801
802   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
803     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
804
805     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
806     // registers cannot be used even for integer operations.
807     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
808     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
809     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
810     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
811
812     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
813     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
814     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
815     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
841     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
842     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
843     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
845
846     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
847     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
848       EVT VT = (MVT::SimpleValueType)i;
849       // Do not attempt to custom lower non-power-of-2 vectors
850       if (!isPowerOf2_32(VT.getVectorNumElements()))
851         continue;
852       // Do not attempt to custom lower non-128-bit vectors
853       if (!VT.is128BitVector())
854         continue;
855       setOperationAction(ISD::BUILD_VECTOR,
856                          VT.getSimpleVT().SimpleTy, Custom);
857       setOperationAction(ISD::VECTOR_SHUFFLE,
858                          VT.getSimpleVT().SimpleTy, Custom);
859       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
860                          VT.getSimpleVT().SimpleTy, Custom);
861     }
862
863     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
864     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
865     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
866     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
867     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
868     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
869
870     if (Subtarget->is64Bit()) {
871       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
872       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
873     }
874
875     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
876     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
877       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
878       EVT VT = SVT;
879
880       // Do not attempt to promote non-128-bit vectors
881       if (!VT.is128BitVector())
882         continue;
883
884       setOperationAction(ISD::AND,    SVT, Promote);
885       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
886       setOperationAction(ISD::OR,     SVT, Promote);
887       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
888       setOperationAction(ISD::XOR,    SVT, Promote);
889       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
890       setOperationAction(ISD::LOAD,   SVT, Promote);
891       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
892       setOperationAction(ISD::SELECT, SVT, Promote);
893       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
894     }
895
896     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
897
898     // Custom lower v2i64 and v2f64 selects.
899     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
900     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
901     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
902     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
903
904     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
905     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
906   }
907
908   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
909     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
910     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
911     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
912     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
913     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
914     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
915     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
916     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
917     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
918     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
919
920     // FIXME: Do we need to handle scalar-to-vector here?
921     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
922
923     // Can turn SHL into an integer multiply.
924     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
925     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
926
927     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
928     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
929     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
930     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
931     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
932
933     // i8 and i16 vectors are custom , because the source register and source
934     // source memory operand types are not the same width.  f32 vectors are
935     // custom since the immediate controlling the insert encodes additional
936     // information.
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
941
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
946
947     if (Subtarget->is64Bit()) {
948       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
949       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
950     }
951   }
952
953   if (Subtarget->hasXMMInt()) {
954     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
955     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
956     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
957     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
958
959     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
960     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
961     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
962
963     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
964     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
965   }
966
967   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
968     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
969
970   if (!UseSoftFloat && Subtarget->hasAVX()) {
971     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
972     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
973     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
974     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
975     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
976     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
977
978     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
981
982     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
983     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
987     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
988
989     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
990     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
994     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
995
996     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
997     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
998     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
999
1000     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1001     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1002     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1003     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1004     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1005     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1006
1007     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1009     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1010     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1011
1012     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1013     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1014     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1015     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1016
1017     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1018     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1019
1020     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1021     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1022     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1023     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1024
1025     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1026     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1027     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1028
1029     setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1030     setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1031     setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1032     setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1033
1034     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1035     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1036     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1037     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1038
1039     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1040     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1041     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1042     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1043
1044     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1045     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1046     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1047     // Don't lower v32i8 because there is no 128-bit byte mul
1048
1049     // Custom lower several nodes for 256-bit types.
1050     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1051                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1052       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1053       EVT VT = SVT;
1054
1055       // Extract subvector is special because the value type
1056       // (result) is 128-bit but the source is 256-bit wide.
1057       if (VT.is128BitVector())
1058         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1059
1060       // Do not attempt to custom lower other non-256-bit vectors
1061       if (!VT.is256BitVector())
1062         continue;
1063
1064       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1065       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1066       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1067       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1068       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1069       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1070     }
1071
1072     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1073     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1074       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1075       EVT VT = SVT;
1076
1077       // Do not attempt to promote non-256-bit vectors
1078       if (!VT.is256BitVector())
1079         continue;
1080
1081       setOperationAction(ISD::AND,    SVT, Promote);
1082       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1083       setOperationAction(ISD::OR,     SVT, Promote);
1084       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1085       setOperationAction(ISD::XOR,    SVT, Promote);
1086       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1087       setOperationAction(ISD::LOAD,   SVT, Promote);
1088       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1089       setOperationAction(ISD::SELECT, SVT, Promote);
1090       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1091     }
1092   }
1093
1094   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1095   // of this type with custom code.
1096   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1097          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1098     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1099   }
1100
1101   // We want to custom lower some of our intrinsics.
1102   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1103
1104
1105   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1106   // handle type legalization for these operations here.
1107   //
1108   // FIXME: We really should do custom legalization for addition and
1109   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1110   // than generic legalization for 64-bit multiplication-with-overflow, though.
1111   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1112     // Add/Sub/Mul with overflow operations are custom lowered.
1113     MVT VT = IntVTs[i];
1114     setOperationAction(ISD::SADDO, VT, Custom);
1115     setOperationAction(ISD::UADDO, VT, Custom);
1116     setOperationAction(ISD::SSUBO, VT, Custom);
1117     setOperationAction(ISD::USUBO, VT, Custom);
1118     setOperationAction(ISD::SMULO, VT, Custom);
1119     setOperationAction(ISD::UMULO, VT, Custom);
1120   }
1121
1122   // There are no 8-bit 3-address imul/mul instructions
1123   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1124   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1125
1126   if (!Subtarget->is64Bit()) {
1127     // These libcalls are not available in 32-bit.
1128     setLibcallName(RTLIB::SHL_I128, 0);
1129     setLibcallName(RTLIB::SRL_I128, 0);
1130     setLibcallName(RTLIB::SRA_I128, 0);
1131   }
1132
1133   // We have target-specific dag combine patterns for the following nodes:
1134   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1135   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1136   setTargetDAGCombine(ISD::BUILD_VECTOR);
1137   setTargetDAGCombine(ISD::VSELECT);
1138   setTargetDAGCombine(ISD::SELECT);
1139   setTargetDAGCombine(ISD::SHL);
1140   setTargetDAGCombine(ISD::SRA);
1141   setTargetDAGCombine(ISD::SRL);
1142   setTargetDAGCombine(ISD::OR);
1143   setTargetDAGCombine(ISD::AND);
1144   setTargetDAGCombine(ISD::ADD);
1145   setTargetDAGCombine(ISD::FADD);
1146   setTargetDAGCombine(ISD::FSUB);
1147   setTargetDAGCombine(ISD::SUB);
1148   setTargetDAGCombine(ISD::LOAD);
1149   setTargetDAGCombine(ISD::STORE);
1150   setTargetDAGCombine(ISD::ZERO_EXTEND);
1151   setTargetDAGCombine(ISD::SINT_TO_FP);
1152   if (Subtarget->is64Bit())
1153     setTargetDAGCombine(ISD::MUL);
1154
1155   computeRegisterProperties();
1156
1157   // On Darwin, -Os means optimize for size without hurting performance,
1158   // do not reduce the limit.
1159   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1160   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1161   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1162   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1163   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1164   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1165   setPrefLoopAlignment(16);
1166   benefitFromCodePlacementOpt = true;
1167
1168   setPrefFunctionAlignment(4);
1169 }
1170
1171
1172 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1173   if (!VT.isVector()) return MVT::i8;
1174   return VT.changeVectorElementTypeToInteger();
1175 }
1176
1177
1178 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1179 /// the desired ByVal argument alignment.
1180 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1181   if (MaxAlign == 16)
1182     return;
1183   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1184     if (VTy->getBitWidth() == 128)
1185       MaxAlign = 16;
1186   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1187     unsigned EltAlign = 0;
1188     getMaxByValAlign(ATy->getElementType(), EltAlign);
1189     if (EltAlign > MaxAlign)
1190       MaxAlign = EltAlign;
1191   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1192     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1193       unsigned EltAlign = 0;
1194       getMaxByValAlign(STy->getElementType(i), EltAlign);
1195       if (EltAlign > MaxAlign)
1196         MaxAlign = EltAlign;
1197       if (MaxAlign == 16)
1198         break;
1199     }
1200   }
1201   return;
1202 }
1203
1204 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1205 /// function arguments in the caller parameter area. For X86, aggregates
1206 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1207 /// are at 4-byte boundaries.
1208 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1209   if (Subtarget->is64Bit()) {
1210     // Max of 8 and alignment of type.
1211     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1212     if (TyAlign > 8)
1213       return TyAlign;
1214     return 8;
1215   }
1216
1217   unsigned Align = 4;
1218   if (Subtarget->hasXMM())
1219     getMaxByValAlign(Ty, Align);
1220   return Align;
1221 }
1222
1223 /// getOptimalMemOpType - Returns the target specific optimal type for load
1224 /// and store operations as a result of memset, memcpy, and memmove
1225 /// lowering. If DstAlign is zero that means it's safe to destination
1226 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1227 /// means there isn't a need to check it against alignment requirement,
1228 /// probably because the source does not need to be loaded. If
1229 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1230 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1231 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1232 /// constant so it does not need to be loaded.
1233 /// It returns EVT::Other if the type should be determined using generic
1234 /// target-independent logic.
1235 EVT
1236 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1237                                        unsigned DstAlign, unsigned SrcAlign,
1238                                        bool NonScalarIntSafe,
1239                                        bool MemcpyStrSrc,
1240                                        MachineFunction &MF) const {
1241   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1242   // linux.  This is because the stack realignment code can't handle certain
1243   // cases like PR2962.  This should be removed when PR2962 is fixed.
1244   const Function *F = MF.getFunction();
1245   if (NonScalarIntSafe &&
1246       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1247     if (Size >= 16 &&
1248         (Subtarget->isUnalignedMemAccessFast() ||
1249          ((DstAlign == 0 || DstAlign >= 16) &&
1250           (SrcAlign == 0 || SrcAlign >= 16))) &&
1251         Subtarget->getStackAlignment() >= 16) {
1252       if (Subtarget->hasAVX() &&
1253           Subtarget->getStackAlignment() >= 32)
1254         return MVT::v8f32;
1255       if (Subtarget->hasXMMInt())
1256         return MVT::v4i32;
1257       if (Subtarget->hasXMM())
1258         return MVT::v4f32;
1259     } else if (!MemcpyStrSrc && Size >= 8 &&
1260                !Subtarget->is64Bit() &&
1261                Subtarget->getStackAlignment() >= 8 &&
1262                Subtarget->hasXMMInt()) {
1263       // Do not use f64 to lower memcpy if source is string constant. It's
1264       // better to use i32 to avoid the loads.
1265       return MVT::f64;
1266     }
1267   }
1268   if (Subtarget->is64Bit() && Size >= 8)
1269     return MVT::i64;
1270   return MVT::i32;
1271 }
1272
1273 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1274 /// current function.  The returned value is a member of the
1275 /// MachineJumpTableInfo::JTEntryKind enum.
1276 unsigned X86TargetLowering::getJumpTableEncoding() const {
1277   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1278   // symbol.
1279   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1280       Subtarget->isPICStyleGOT())
1281     return MachineJumpTableInfo::EK_Custom32;
1282
1283   // Otherwise, use the normal jump table encoding heuristics.
1284   return TargetLowering::getJumpTableEncoding();
1285 }
1286
1287 const MCExpr *
1288 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1289                                              const MachineBasicBlock *MBB,
1290                                              unsigned uid,MCContext &Ctx) const{
1291   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1292          Subtarget->isPICStyleGOT());
1293   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1294   // entries.
1295   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1296                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1297 }
1298
1299 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1300 /// jumptable.
1301 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1302                                                     SelectionDAG &DAG) const {
1303   if (!Subtarget->is64Bit())
1304     // This doesn't have DebugLoc associated with it, but is not really the
1305     // same as a Register.
1306     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1307   return Table;
1308 }
1309
1310 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1311 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1312 /// MCExpr.
1313 const MCExpr *X86TargetLowering::
1314 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1315                              MCContext &Ctx) const {
1316   // X86-64 uses RIP relative addressing based on the jump table label.
1317   if (Subtarget->isPICStyleRIPRel())
1318     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1319
1320   // Otherwise, the reference is relative to the PIC base.
1321   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1322 }
1323
1324 // FIXME: Why this routine is here? Move to RegInfo!
1325 std::pair<const TargetRegisterClass*, uint8_t>
1326 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1327   const TargetRegisterClass *RRC = 0;
1328   uint8_t Cost = 1;
1329   switch (VT.getSimpleVT().SimpleTy) {
1330   default:
1331     return TargetLowering::findRepresentativeClass(VT);
1332   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1333     RRC = (Subtarget->is64Bit()
1334            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1335     break;
1336   case MVT::x86mmx:
1337     RRC = X86::VR64RegisterClass;
1338     break;
1339   case MVT::f32: case MVT::f64:
1340   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1341   case MVT::v4f32: case MVT::v2f64:
1342   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1343   case MVT::v4f64:
1344     RRC = X86::VR128RegisterClass;
1345     break;
1346   }
1347   return std::make_pair(RRC, Cost);
1348 }
1349
1350 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1351                                                unsigned &Offset) const {
1352   if (!Subtarget->isTargetLinux())
1353     return false;
1354
1355   if (Subtarget->is64Bit()) {
1356     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1357     Offset = 0x28;
1358     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1359       AddressSpace = 256;
1360     else
1361       AddressSpace = 257;
1362   } else {
1363     // %gs:0x14 on i386
1364     Offset = 0x14;
1365     AddressSpace = 256;
1366   }
1367   return true;
1368 }
1369
1370
1371 //===----------------------------------------------------------------------===//
1372 //               Return Value Calling Convention Implementation
1373 //===----------------------------------------------------------------------===//
1374
1375 #include "X86GenCallingConv.inc"
1376
1377 bool
1378 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1379                                   MachineFunction &MF, bool isVarArg,
1380                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1381                         LLVMContext &Context) const {
1382   SmallVector<CCValAssign, 16> RVLocs;
1383   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1384                  RVLocs, Context);
1385   return CCInfo.CheckReturn(Outs, RetCC_X86);
1386 }
1387
1388 SDValue
1389 X86TargetLowering::LowerReturn(SDValue Chain,
1390                                CallingConv::ID CallConv, bool isVarArg,
1391                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1392                                const SmallVectorImpl<SDValue> &OutVals,
1393                                DebugLoc dl, SelectionDAG &DAG) const {
1394   MachineFunction &MF = DAG.getMachineFunction();
1395   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1396
1397   SmallVector<CCValAssign, 16> RVLocs;
1398   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1399                  RVLocs, *DAG.getContext());
1400   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1401
1402   // Add the regs to the liveout set for the function.
1403   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1404   for (unsigned i = 0; i != RVLocs.size(); ++i)
1405     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1406       MRI.addLiveOut(RVLocs[i].getLocReg());
1407
1408   SDValue Flag;
1409
1410   SmallVector<SDValue, 6> RetOps;
1411   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1412   // Operand #1 = Bytes To Pop
1413   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1414                    MVT::i16));
1415
1416   // Copy the result values into the output registers.
1417   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1418     CCValAssign &VA = RVLocs[i];
1419     assert(VA.isRegLoc() && "Can only return in registers!");
1420     SDValue ValToCopy = OutVals[i];
1421     EVT ValVT = ValToCopy.getValueType();
1422
1423     // If this is x86-64, and we disabled SSE, we can't return FP values,
1424     // or SSE or MMX vectors.
1425     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1426          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1427           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1428       report_fatal_error("SSE register return with SSE disabled");
1429     }
1430     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1431     // llvm-gcc has never done it right and no one has noticed, so this
1432     // should be OK for now.
1433     if (ValVT == MVT::f64 &&
1434         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1435       report_fatal_error("SSE2 register return with SSE2 disabled");
1436
1437     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1438     // the RET instruction and handled by the FP Stackifier.
1439     if (VA.getLocReg() == X86::ST0 ||
1440         VA.getLocReg() == X86::ST1) {
1441       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1442       // change the value to the FP stack register class.
1443       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1444         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1445       RetOps.push_back(ValToCopy);
1446       // Don't emit a copytoreg.
1447       continue;
1448     }
1449
1450     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1451     // which is returned in RAX / RDX.
1452     if (Subtarget->is64Bit()) {
1453       if (ValVT == MVT::x86mmx) {
1454         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1455           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1456           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1457                                   ValToCopy);
1458           // If we don't have SSE2 available, convert to v4f32 so the generated
1459           // register is legal.
1460           if (!Subtarget->hasXMMInt())
1461             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1462         }
1463       }
1464     }
1465
1466     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1467     Flag = Chain.getValue(1);
1468   }
1469
1470   // The x86-64 ABI for returning structs by value requires that we copy
1471   // the sret argument into %rax for the return. We saved the argument into
1472   // a virtual register in the entry block, so now we copy the value out
1473   // and into %rax.
1474   if (Subtarget->is64Bit() &&
1475       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1476     MachineFunction &MF = DAG.getMachineFunction();
1477     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1478     unsigned Reg = FuncInfo->getSRetReturnReg();
1479     assert(Reg &&
1480            "SRetReturnReg should have been set in LowerFormalArguments().");
1481     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1482
1483     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1484     Flag = Chain.getValue(1);
1485
1486     // RAX now acts like a return value.
1487     MRI.addLiveOut(X86::RAX);
1488   }
1489
1490   RetOps[0] = Chain;  // Update chain.
1491
1492   // Add the flag if we have it.
1493   if (Flag.getNode())
1494     RetOps.push_back(Flag);
1495
1496   return DAG.getNode(X86ISD::RET_FLAG, dl,
1497                      MVT::Other, &RetOps[0], RetOps.size());
1498 }
1499
1500 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1501   if (N->getNumValues() != 1)
1502     return false;
1503   if (!N->hasNUsesOfValue(1, 0))
1504     return false;
1505
1506   SDNode *Copy = *N->use_begin();
1507   if (Copy->getOpcode() != ISD::CopyToReg &&
1508       Copy->getOpcode() != ISD::FP_EXTEND)
1509     return false;
1510
1511   bool HasRet = false;
1512   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1513        UI != UE; ++UI) {
1514     if (UI->getOpcode() != X86ISD::RET_FLAG)
1515       return false;
1516     HasRet = true;
1517   }
1518
1519   return HasRet;
1520 }
1521
1522 EVT
1523 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1524                                             ISD::NodeType ExtendKind) const {
1525   MVT ReturnMVT;
1526   // TODO: Is this also valid on 32-bit?
1527   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1528     ReturnMVT = MVT::i8;
1529   else
1530     ReturnMVT = MVT::i32;
1531
1532   EVT MinVT = getRegisterType(Context, ReturnMVT);
1533   return VT.bitsLT(MinVT) ? MinVT : VT;
1534 }
1535
1536 /// LowerCallResult - Lower the result values of a call into the
1537 /// appropriate copies out of appropriate physical registers.
1538 ///
1539 SDValue
1540 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1541                                    CallingConv::ID CallConv, bool isVarArg,
1542                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1543                                    DebugLoc dl, SelectionDAG &DAG,
1544                                    SmallVectorImpl<SDValue> &InVals) const {
1545
1546   // Assign locations to each value returned by this call.
1547   SmallVector<CCValAssign, 16> RVLocs;
1548   bool Is64Bit = Subtarget->is64Bit();
1549   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1550                  getTargetMachine(), RVLocs, *DAG.getContext());
1551   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1552
1553   // Copy all of the result registers out of their specified physreg.
1554   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1555     CCValAssign &VA = RVLocs[i];
1556     EVT CopyVT = VA.getValVT();
1557
1558     // If this is x86-64, and we disabled SSE, we can't return FP values
1559     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1560         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1561       report_fatal_error("SSE register return with SSE disabled");
1562     }
1563
1564     SDValue Val;
1565
1566     // If this is a call to a function that returns an fp value on the floating
1567     // point stack, we must guarantee the the value is popped from the stack, so
1568     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1569     // if the return value is not used. We use the FpPOP_RETVAL instruction
1570     // instead.
1571     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1572       // If we prefer to use the value in xmm registers, copy it out as f80 and
1573       // use a truncate to move it from fp stack reg to xmm reg.
1574       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1575       SDValue Ops[] = { Chain, InFlag };
1576       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1577                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1578       Val = Chain.getValue(0);
1579
1580       // Round the f80 to the right size, which also moves it to the appropriate
1581       // xmm register.
1582       if (CopyVT != VA.getValVT())
1583         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1584                           // This truncation won't change the value.
1585                           DAG.getIntPtrConstant(1));
1586     } else {
1587       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1588                                  CopyVT, InFlag).getValue(1);
1589       Val = Chain.getValue(0);
1590     }
1591     InFlag = Chain.getValue(2);
1592     InVals.push_back(Val);
1593   }
1594
1595   return Chain;
1596 }
1597
1598
1599 //===----------------------------------------------------------------------===//
1600 //                C & StdCall & Fast Calling Convention implementation
1601 //===----------------------------------------------------------------------===//
1602 //  StdCall calling convention seems to be standard for many Windows' API
1603 //  routines and around. It differs from C calling convention just a little:
1604 //  callee should clean up the stack, not caller. Symbols should be also
1605 //  decorated in some fancy way :) It doesn't support any vector arguments.
1606 //  For info on fast calling convention see Fast Calling Convention (tail call)
1607 //  implementation LowerX86_32FastCCCallTo.
1608
1609 /// CallIsStructReturn - Determines whether a call uses struct return
1610 /// semantics.
1611 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1612   if (Outs.empty())
1613     return false;
1614
1615   return Outs[0].Flags.isSRet();
1616 }
1617
1618 /// ArgsAreStructReturn - Determines whether a function uses struct
1619 /// return semantics.
1620 static bool
1621 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1622   if (Ins.empty())
1623     return false;
1624
1625   return Ins[0].Flags.isSRet();
1626 }
1627
1628 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1629 /// by "Src" to address "Dst" with size and alignment information specified by
1630 /// the specific parameter attribute. The copy will be passed as a byval
1631 /// function parameter.
1632 static SDValue
1633 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1634                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1635                           DebugLoc dl) {
1636   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1637
1638   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1639                        /*isVolatile*/false, /*AlwaysInline=*/true,
1640                        MachinePointerInfo(), MachinePointerInfo());
1641 }
1642
1643 /// IsTailCallConvention - Return true if the calling convention is one that
1644 /// supports tail call optimization.
1645 static bool IsTailCallConvention(CallingConv::ID CC) {
1646   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1647 }
1648
1649 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1650   if (!CI->isTailCall())
1651     return false;
1652
1653   CallSite CS(CI);
1654   CallingConv::ID CalleeCC = CS.getCallingConv();
1655   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1656     return false;
1657
1658   return true;
1659 }
1660
1661 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1662 /// a tailcall target by changing its ABI.
1663 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1664   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1665 }
1666
1667 SDValue
1668 X86TargetLowering::LowerMemArgument(SDValue Chain,
1669                                     CallingConv::ID CallConv,
1670                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1671                                     DebugLoc dl, SelectionDAG &DAG,
1672                                     const CCValAssign &VA,
1673                                     MachineFrameInfo *MFI,
1674                                     unsigned i) const {
1675   // Create the nodes corresponding to a load from this parameter slot.
1676   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1677   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1678   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1679   EVT ValVT;
1680
1681   // If value is passed by pointer we have address passed instead of the value
1682   // itself.
1683   if (VA.getLocInfo() == CCValAssign::Indirect)
1684     ValVT = VA.getLocVT();
1685   else
1686     ValVT = VA.getValVT();
1687
1688   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1689   // changed with more analysis.
1690   // In case of tail call optimization mark all arguments mutable. Since they
1691   // could be overwritten by lowering of arguments in case of a tail call.
1692   if (Flags.isByVal()) {
1693     unsigned Bytes = Flags.getByValSize();
1694     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1695     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1696     return DAG.getFrameIndex(FI, getPointerTy());
1697   } else {
1698     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1699                                     VA.getLocMemOffset(), isImmutable);
1700     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1701     return DAG.getLoad(ValVT, dl, Chain, FIN,
1702                        MachinePointerInfo::getFixedStack(FI),
1703                        false, false, 0);
1704   }
1705 }
1706
1707 SDValue
1708 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1709                                         CallingConv::ID CallConv,
1710                                         bool isVarArg,
1711                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1712                                         DebugLoc dl,
1713                                         SelectionDAG &DAG,
1714                                         SmallVectorImpl<SDValue> &InVals)
1715                                           const {
1716   MachineFunction &MF = DAG.getMachineFunction();
1717   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1718
1719   const Function* Fn = MF.getFunction();
1720   if (Fn->hasExternalLinkage() &&
1721       Subtarget->isTargetCygMing() &&
1722       Fn->getName() == "main")
1723     FuncInfo->setForceFramePointer(true);
1724
1725   MachineFrameInfo *MFI = MF.getFrameInfo();
1726   bool Is64Bit = Subtarget->is64Bit();
1727   bool IsWin64 = Subtarget->isTargetWin64();
1728
1729   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1730          "Var args not supported with calling convention fastcc or ghc");
1731
1732   // Assign locations to all of the incoming arguments.
1733   SmallVector<CCValAssign, 16> ArgLocs;
1734   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1735                  ArgLocs, *DAG.getContext());
1736
1737   // Allocate shadow area for Win64
1738   if (IsWin64) {
1739     CCInfo.AllocateStack(32, 8);
1740   }
1741
1742   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1743
1744   unsigned LastVal = ~0U;
1745   SDValue ArgValue;
1746   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1747     CCValAssign &VA = ArgLocs[i];
1748     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1749     // places.
1750     assert(VA.getValNo() != LastVal &&
1751            "Don't support value assigned to multiple locs yet");
1752     LastVal = VA.getValNo();
1753
1754     if (VA.isRegLoc()) {
1755       EVT RegVT = VA.getLocVT();
1756       TargetRegisterClass *RC = NULL;
1757       if (RegVT == MVT::i32)
1758         RC = X86::GR32RegisterClass;
1759       else if (Is64Bit && RegVT == MVT::i64)
1760         RC = X86::GR64RegisterClass;
1761       else if (RegVT == MVT::f32)
1762         RC = X86::FR32RegisterClass;
1763       else if (RegVT == MVT::f64)
1764         RC = X86::FR64RegisterClass;
1765       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1766         RC = X86::VR256RegisterClass;
1767       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1768         RC = X86::VR128RegisterClass;
1769       else if (RegVT == MVT::x86mmx)
1770         RC = X86::VR64RegisterClass;
1771       else
1772         llvm_unreachable("Unknown argument type!");
1773
1774       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1775       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1776
1777       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1778       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1779       // right size.
1780       if (VA.getLocInfo() == CCValAssign::SExt)
1781         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1782                                DAG.getValueType(VA.getValVT()));
1783       else if (VA.getLocInfo() == CCValAssign::ZExt)
1784         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1785                                DAG.getValueType(VA.getValVT()));
1786       else if (VA.getLocInfo() == CCValAssign::BCvt)
1787         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1788
1789       if (VA.isExtInLoc()) {
1790         // Handle MMX values passed in XMM regs.
1791         if (RegVT.isVector()) {
1792           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1793                                  ArgValue);
1794         } else
1795           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1796       }
1797     } else {
1798       assert(VA.isMemLoc());
1799       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1800     }
1801
1802     // If value is passed via pointer - do a load.
1803     if (VA.getLocInfo() == CCValAssign::Indirect)
1804       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1805                              MachinePointerInfo(), false, false, 0);
1806
1807     InVals.push_back(ArgValue);
1808   }
1809
1810   // The x86-64 ABI for returning structs by value requires that we copy
1811   // the sret argument into %rax for the return. Save the argument into
1812   // a virtual register so that we can access it from the return points.
1813   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1814     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1815     unsigned Reg = FuncInfo->getSRetReturnReg();
1816     if (!Reg) {
1817       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1818       FuncInfo->setSRetReturnReg(Reg);
1819     }
1820     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1821     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1822   }
1823
1824   unsigned StackSize = CCInfo.getNextStackOffset();
1825   // Align stack specially for tail calls.
1826   if (FuncIsMadeTailCallSafe(CallConv))
1827     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1828
1829   // If the function takes variable number of arguments, make a frame index for
1830   // the start of the first vararg value... for expansion of llvm.va_start.
1831   if (isVarArg) {
1832     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1833                     CallConv != CallingConv::X86_ThisCall)) {
1834       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1835     }
1836     if (Is64Bit) {
1837       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1838
1839       // FIXME: We should really autogenerate these arrays
1840       static const unsigned GPR64ArgRegsWin64[] = {
1841         X86::RCX, X86::RDX, X86::R8,  X86::R9
1842       };
1843       static const unsigned GPR64ArgRegs64Bit[] = {
1844         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1845       };
1846       static const unsigned XMMArgRegs64Bit[] = {
1847         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1848         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1849       };
1850       const unsigned *GPR64ArgRegs;
1851       unsigned NumXMMRegs = 0;
1852
1853       if (IsWin64) {
1854         // The XMM registers which might contain var arg parameters are shadowed
1855         // in their paired GPR.  So we only need to save the GPR to their home
1856         // slots.
1857         TotalNumIntRegs = 4;
1858         GPR64ArgRegs = GPR64ArgRegsWin64;
1859       } else {
1860         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1861         GPR64ArgRegs = GPR64ArgRegs64Bit;
1862
1863         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1864       }
1865       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1866                                                        TotalNumIntRegs);
1867
1868       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1869       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1870              "SSE register cannot be used when SSE is disabled!");
1871       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1872              "SSE register cannot be used when SSE is disabled!");
1873       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1874         // Kernel mode asks for SSE to be disabled, so don't push them
1875         // on the stack.
1876         TotalNumXMMRegs = 0;
1877
1878       if (IsWin64) {
1879         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1880         // Get to the caller-allocated home save location.  Add 8 to account
1881         // for the return address.
1882         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1883         FuncInfo->setRegSaveFrameIndex(
1884           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1885         // Fixup to set vararg frame on shadow area (4 x i64).
1886         if (NumIntRegs < 4)
1887           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1888       } else {
1889         // For X86-64, if there are vararg parameters that are passed via
1890         // registers, then we must store them to their spots on the stack so they
1891         // may be loaded by deferencing the result of va_next.
1892         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1893         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1894         FuncInfo->setRegSaveFrameIndex(
1895           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1896                                false));
1897       }
1898
1899       // Store the integer parameter registers.
1900       SmallVector<SDValue, 8> MemOps;
1901       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1902                                         getPointerTy());
1903       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1904       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1905         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1906                                   DAG.getIntPtrConstant(Offset));
1907         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1908                                      X86::GR64RegisterClass);
1909         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1910         SDValue Store =
1911           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1912                        MachinePointerInfo::getFixedStack(
1913                          FuncInfo->getRegSaveFrameIndex(), Offset),
1914                        false, false, 0);
1915         MemOps.push_back(Store);
1916         Offset += 8;
1917       }
1918
1919       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1920         // Now store the XMM (fp + vector) parameter registers.
1921         SmallVector<SDValue, 11> SaveXMMOps;
1922         SaveXMMOps.push_back(Chain);
1923
1924         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1925         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1926         SaveXMMOps.push_back(ALVal);
1927
1928         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1929                                FuncInfo->getRegSaveFrameIndex()));
1930         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1931                                FuncInfo->getVarArgsFPOffset()));
1932
1933         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1934           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1935                                        X86::VR128RegisterClass);
1936           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1937           SaveXMMOps.push_back(Val);
1938         }
1939         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1940                                      MVT::Other,
1941                                      &SaveXMMOps[0], SaveXMMOps.size()));
1942       }
1943
1944       if (!MemOps.empty())
1945         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1946                             &MemOps[0], MemOps.size());
1947     }
1948   }
1949
1950   // Some CCs need callee pop.
1951   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1952     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1953   } else {
1954     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1955     // If this is an sret function, the return should pop the hidden pointer.
1956     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1957       FuncInfo->setBytesToPopOnReturn(4);
1958   }
1959
1960   if (!Is64Bit) {
1961     // RegSaveFrameIndex is X86-64 only.
1962     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1963     if (CallConv == CallingConv::X86_FastCall ||
1964         CallConv == CallingConv::X86_ThisCall)
1965       // fastcc functions can't have varargs.
1966       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1967   }
1968
1969   FuncInfo->setArgumentStackSize(StackSize);
1970
1971   return Chain;
1972 }
1973
1974 SDValue
1975 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1976                                     SDValue StackPtr, SDValue Arg,
1977                                     DebugLoc dl, SelectionDAG &DAG,
1978                                     const CCValAssign &VA,
1979                                     ISD::ArgFlagsTy Flags) const {
1980   unsigned LocMemOffset = VA.getLocMemOffset();
1981   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1982   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1983   if (Flags.isByVal())
1984     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1985
1986   return DAG.getStore(Chain, dl, Arg, PtrOff,
1987                       MachinePointerInfo::getStack(LocMemOffset),
1988                       false, false, 0);
1989 }
1990
1991 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1992 /// optimization is performed and it is required.
1993 SDValue
1994 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1995                                            SDValue &OutRetAddr, SDValue Chain,
1996                                            bool IsTailCall, bool Is64Bit,
1997                                            int FPDiff, DebugLoc dl) const {
1998   // Adjust the Return address stack slot.
1999   EVT VT = getPointerTy();
2000   OutRetAddr = getReturnAddressFrameIndex(DAG);
2001
2002   // Load the "old" Return address.
2003   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2004                            false, false, 0);
2005   return SDValue(OutRetAddr.getNode(), 1);
2006 }
2007
2008 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2009 /// optimization is performed and it is required (FPDiff!=0).
2010 static SDValue
2011 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2012                          SDValue Chain, SDValue RetAddrFrIdx,
2013                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2014   // Store the return address to the appropriate stack slot.
2015   if (!FPDiff) return Chain;
2016   // Calculate the new stack slot for the return address.
2017   int SlotSize = Is64Bit ? 8 : 4;
2018   int NewReturnAddrFI =
2019     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2020   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2021   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2022   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2023                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2024                        false, false, 0);
2025   return Chain;
2026 }
2027
2028 SDValue
2029 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2030                              CallingConv::ID CallConv, bool isVarArg,
2031                              bool &isTailCall,
2032                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2033                              const SmallVectorImpl<SDValue> &OutVals,
2034                              const SmallVectorImpl<ISD::InputArg> &Ins,
2035                              DebugLoc dl, SelectionDAG &DAG,
2036                              SmallVectorImpl<SDValue> &InVals) const {
2037   MachineFunction &MF = DAG.getMachineFunction();
2038   bool Is64Bit        = Subtarget->is64Bit();
2039   bool IsWin64        = Subtarget->isTargetWin64();
2040   bool IsStructRet    = CallIsStructReturn(Outs);
2041   bool IsSibcall      = false;
2042
2043   if (isTailCall) {
2044     // Check if it's really possible to do a tail call.
2045     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2046                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2047                                                    Outs, OutVals, Ins, DAG);
2048
2049     // Sibcalls are automatically detected tailcalls which do not require
2050     // ABI changes.
2051     if (!GuaranteedTailCallOpt && isTailCall)
2052       IsSibcall = true;
2053
2054     if (isTailCall)
2055       ++NumTailCalls;
2056   }
2057
2058   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2059          "Var args not supported with calling convention fastcc or ghc");
2060
2061   // Analyze operands of the call, assigning locations to each operand.
2062   SmallVector<CCValAssign, 16> ArgLocs;
2063   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2064                  ArgLocs, *DAG.getContext());
2065
2066   // Allocate shadow area for Win64
2067   if (IsWin64) {
2068     CCInfo.AllocateStack(32, 8);
2069   }
2070
2071   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2072
2073   // Get a count of how many bytes are to be pushed on the stack.
2074   unsigned NumBytes = CCInfo.getNextStackOffset();
2075   if (IsSibcall)
2076     // This is a sibcall. The memory operands are available in caller's
2077     // own caller's stack.
2078     NumBytes = 0;
2079   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2080     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2081
2082   int FPDiff = 0;
2083   if (isTailCall && !IsSibcall) {
2084     // Lower arguments at fp - stackoffset + fpdiff.
2085     unsigned NumBytesCallerPushed =
2086       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2087     FPDiff = NumBytesCallerPushed - NumBytes;
2088
2089     // Set the delta of movement of the returnaddr stackslot.
2090     // But only set if delta is greater than previous delta.
2091     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2092       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2093   }
2094
2095   if (!IsSibcall)
2096     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2097
2098   SDValue RetAddrFrIdx;
2099   // Load return address for tail calls.
2100   if (isTailCall && FPDiff)
2101     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2102                                     Is64Bit, FPDiff, dl);
2103
2104   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2105   SmallVector<SDValue, 8> MemOpChains;
2106   SDValue StackPtr;
2107
2108   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2109   // of tail call optimization arguments are handle later.
2110   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2111     CCValAssign &VA = ArgLocs[i];
2112     EVT RegVT = VA.getLocVT();
2113     SDValue Arg = OutVals[i];
2114     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2115     bool isByVal = Flags.isByVal();
2116
2117     // Promote the value if needed.
2118     switch (VA.getLocInfo()) {
2119     default: llvm_unreachable("Unknown loc info!");
2120     case CCValAssign::Full: break;
2121     case CCValAssign::SExt:
2122       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2123       break;
2124     case CCValAssign::ZExt:
2125       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2126       break;
2127     case CCValAssign::AExt:
2128       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2129         // Special case: passing MMX values in XMM registers.
2130         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2131         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2132         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2133       } else
2134         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2135       break;
2136     case CCValAssign::BCvt:
2137       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2138       break;
2139     case CCValAssign::Indirect: {
2140       // Store the argument.
2141       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2142       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2143       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2144                            MachinePointerInfo::getFixedStack(FI),
2145                            false, false, 0);
2146       Arg = SpillSlot;
2147       break;
2148     }
2149     }
2150
2151     if (VA.isRegLoc()) {
2152       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2153       if (isVarArg && IsWin64) {
2154         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2155         // shadow reg if callee is a varargs function.
2156         unsigned ShadowReg = 0;
2157         switch (VA.getLocReg()) {
2158         case X86::XMM0: ShadowReg = X86::RCX; break;
2159         case X86::XMM1: ShadowReg = X86::RDX; break;
2160         case X86::XMM2: ShadowReg = X86::R8; break;
2161         case X86::XMM3: ShadowReg = X86::R9; break;
2162         }
2163         if (ShadowReg)
2164           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2165       }
2166     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2167       assert(VA.isMemLoc());
2168       if (StackPtr.getNode() == 0)
2169         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2170       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2171                                              dl, DAG, VA, Flags));
2172     }
2173   }
2174
2175   if (!MemOpChains.empty())
2176     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2177                         &MemOpChains[0], MemOpChains.size());
2178
2179   // Build a sequence of copy-to-reg nodes chained together with token chain
2180   // and flag operands which copy the outgoing args into registers.
2181   SDValue InFlag;
2182   // Tail call byval lowering might overwrite argument registers so in case of
2183   // tail call optimization the copies to registers are lowered later.
2184   if (!isTailCall)
2185     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2186       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2187                                RegsToPass[i].second, InFlag);
2188       InFlag = Chain.getValue(1);
2189     }
2190
2191   if (Subtarget->isPICStyleGOT()) {
2192     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2193     // GOT pointer.
2194     if (!isTailCall) {
2195       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2196                                DAG.getNode(X86ISD::GlobalBaseReg,
2197                                            DebugLoc(), getPointerTy()),
2198                                InFlag);
2199       InFlag = Chain.getValue(1);
2200     } else {
2201       // If we are tail calling and generating PIC/GOT style code load the
2202       // address of the callee into ECX. The value in ecx is used as target of
2203       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2204       // for tail calls on PIC/GOT architectures. Normally we would just put the
2205       // address of GOT into ebx and then call target@PLT. But for tail calls
2206       // ebx would be restored (since ebx is callee saved) before jumping to the
2207       // target@PLT.
2208
2209       // Note: The actual moving to ECX is done further down.
2210       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2211       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2212           !G->getGlobal()->hasProtectedVisibility())
2213         Callee = LowerGlobalAddress(Callee, DAG);
2214       else if (isa<ExternalSymbolSDNode>(Callee))
2215         Callee = LowerExternalSymbol(Callee, DAG);
2216     }
2217   }
2218
2219   if (Is64Bit && isVarArg && !IsWin64) {
2220     // From AMD64 ABI document:
2221     // For calls that may call functions that use varargs or stdargs
2222     // (prototype-less calls or calls to functions containing ellipsis (...) in
2223     // the declaration) %al is used as hidden argument to specify the number
2224     // of SSE registers used. The contents of %al do not need to match exactly
2225     // the number of registers, but must be an ubound on the number of SSE
2226     // registers used and is in the range 0 - 8 inclusive.
2227
2228     // Count the number of XMM registers allocated.
2229     static const unsigned XMMArgRegs[] = {
2230       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2231       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2232     };
2233     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2234     assert((Subtarget->hasXMM() || !NumXMMRegs)
2235            && "SSE registers cannot be used when SSE is disabled");
2236
2237     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2238                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2239     InFlag = Chain.getValue(1);
2240   }
2241
2242
2243   // For tail calls lower the arguments to the 'real' stack slot.
2244   if (isTailCall) {
2245     // Force all the incoming stack arguments to be loaded from the stack
2246     // before any new outgoing arguments are stored to the stack, because the
2247     // outgoing stack slots may alias the incoming argument stack slots, and
2248     // the alias isn't otherwise explicit. This is slightly more conservative
2249     // than necessary, because it means that each store effectively depends
2250     // on every argument instead of just those arguments it would clobber.
2251     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2252
2253     SmallVector<SDValue, 8> MemOpChains2;
2254     SDValue FIN;
2255     int FI = 0;
2256     // Do not flag preceding copytoreg stuff together with the following stuff.
2257     InFlag = SDValue();
2258     if (GuaranteedTailCallOpt) {
2259       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2260         CCValAssign &VA = ArgLocs[i];
2261         if (VA.isRegLoc())
2262           continue;
2263         assert(VA.isMemLoc());
2264         SDValue Arg = OutVals[i];
2265         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2266         // Create frame index.
2267         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2268         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2269         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2270         FIN = DAG.getFrameIndex(FI, getPointerTy());
2271
2272         if (Flags.isByVal()) {
2273           // Copy relative to framepointer.
2274           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2275           if (StackPtr.getNode() == 0)
2276             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2277                                           getPointerTy());
2278           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2279
2280           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2281                                                            ArgChain,
2282                                                            Flags, DAG, dl));
2283         } else {
2284           // Store relative to framepointer.
2285           MemOpChains2.push_back(
2286             DAG.getStore(ArgChain, dl, Arg, FIN,
2287                          MachinePointerInfo::getFixedStack(FI),
2288                          false, false, 0));
2289         }
2290       }
2291     }
2292
2293     if (!MemOpChains2.empty())
2294       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2295                           &MemOpChains2[0], MemOpChains2.size());
2296
2297     // Copy arguments to their registers.
2298     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2299       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2300                                RegsToPass[i].second, InFlag);
2301       InFlag = Chain.getValue(1);
2302     }
2303     InFlag =SDValue();
2304
2305     // Store the return address to the appropriate stack slot.
2306     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2307                                      FPDiff, dl);
2308   }
2309
2310   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2311     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2312     // In the 64-bit large code model, we have to make all calls
2313     // through a register, since the call instruction's 32-bit
2314     // pc-relative offset may not be large enough to hold the whole
2315     // address.
2316   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2317     // If the callee is a GlobalAddress node (quite common, every direct call
2318     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2319     // it.
2320
2321     // We should use extra load for direct calls to dllimported functions in
2322     // non-JIT mode.
2323     const GlobalValue *GV = G->getGlobal();
2324     if (!GV->hasDLLImportLinkage()) {
2325       unsigned char OpFlags = 0;
2326       bool ExtraLoad = false;
2327       unsigned WrapperKind = ISD::DELETED_NODE;
2328
2329       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2330       // external symbols most go through the PLT in PIC mode.  If the symbol
2331       // has hidden or protected visibility, or if it is static or local, then
2332       // we don't need to use the PLT - we can directly call it.
2333       if (Subtarget->isTargetELF() &&
2334           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2335           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2336         OpFlags = X86II::MO_PLT;
2337       } else if (Subtarget->isPICStyleStubAny() &&
2338                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2339                  (!Subtarget->getTargetTriple().isMacOSX() ||
2340                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2341         // PC-relative references to external symbols should go through $stub,
2342         // unless we're building with the leopard linker or later, which
2343         // automatically synthesizes these stubs.
2344         OpFlags = X86II::MO_DARWIN_STUB;
2345       } else if (Subtarget->isPICStyleRIPRel() &&
2346                  isa<Function>(GV) &&
2347                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2348         // If the function is marked as non-lazy, generate an indirect call
2349         // which loads from the GOT directly. This avoids runtime overhead
2350         // at the cost of eager binding (and one extra byte of encoding).
2351         OpFlags = X86II::MO_GOTPCREL;
2352         WrapperKind = X86ISD::WrapperRIP;
2353         ExtraLoad = true;
2354       }
2355
2356       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2357                                           G->getOffset(), OpFlags);
2358
2359       // Add a wrapper if needed.
2360       if (WrapperKind != ISD::DELETED_NODE)
2361         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2362       // Add extra indirection if needed.
2363       if (ExtraLoad)
2364         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2365                              MachinePointerInfo::getGOT(),
2366                              false, false, 0);
2367     }
2368   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2369     unsigned char OpFlags = 0;
2370
2371     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2372     // external symbols should go through the PLT.
2373     if (Subtarget->isTargetELF() &&
2374         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2375       OpFlags = X86II::MO_PLT;
2376     } else if (Subtarget->isPICStyleStubAny() &&
2377                (!Subtarget->getTargetTriple().isMacOSX() ||
2378                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2379       // PC-relative references to external symbols should go through $stub,
2380       // unless we're building with the leopard linker or later, which
2381       // automatically synthesizes these stubs.
2382       OpFlags = X86II::MO_DARWIN_STUB;
2383     }
2384
2385     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2386                                          OpFlags);
2387   }
2388
2389   // Returns a chain & a flag for retval copy to use.
2390   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2391   SmallVector<SDValue, 8> Ops;
2392
2393   if (!IsSibcall && isTailCall) {
2394     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2395                            DAG.getIntPtrConstant(0, true), InFlag);
2396     InFlag = Chain.getValue(1);
2397   }
2398
2399   Ops.push_back(Chain);
2400   Ops.push_back(Callee);
2401
2402   if (isTailCall)
2403     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2404
2405   // Add argument registers to the end of the list so that they are known live
2406   // into the call.
2407   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2408     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2409                                   RegsToPass[i].second.getValueType()));
2410
2411   // Add an implicit use GOT pointer in EBX.
2412   if (!isTailCall && Subtarget->isPICStyleGOT())
2413     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2414
2415   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2416   if (Is64Bit && isVarArg && !IsWin64)
2417     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2418
2419   if (InFlag.getNode())
2420     Ops.push_back(InFlag);
2421
2422   if (isTailCall) {
2423     // We used to do:
2424     //// If this is the first return lowered for this function, add the regs
2425     //// to the liveout set for the function.
2426     // This isn't right, although it's probably harmless on x86; liveouts
2427     // should be computed from returns not tail calls.  Consider a void
2428     // function making a tail call to a function returning int.
2429     return DAG.getNode(X86ISD::TC_RETURN, dl,
2430                        NodeTys, &Ops[0], Ops.size());
2431   }
2432
2433   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2434   InFlag = Chain.getValue(1);
2435
2436   // Create the CALLSEQ_END node.
2437   unsigned NumBytesForCalleeToPush;
2438   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2439     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2440   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2441     // If this is a call to a struct-return function, the callee
2442     // pops the hidden struct pointer, so we have to push it back.
2443     // This is common for Darwin/X86, Linux & Mingw32 targets.
2444     NumBytesForCalleeToPush = 4;
2445   else
2446     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2447
2448   // Returns a flag for retval copy to use.
2449   if (!IsSibcall) {
2450     Chain = DAG.getCALLSEQ_END(Chain,
2451                                DAG.getIntPtrConstant(NumBytes, true),
2452                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2453                                                      true),
2454                                InFlag);
2455     InFlag = Chain.getValue(1);
2456   }
2457
2458   // Handle result values, copying them out of physregs into vregs that we
2459   // return.
2460   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2461                          Ins, dl, DAG, InVals);
2462 }
2463
2464
2465 //===----------------------------------------------------------------------===//
2466 //                Fast Calling Convention (tail call) implementation
2467 //===----------------------------------------------------------------------===//
2468
2469 //  Like std call, callee cleans arguments, convention except that ECX is
2470 //  reserved for storing the tail called function address. Only 2 registers are
2471 //  free for argument passing (inreg). Tail call optimization is performed
2472 //  provided:
2473 //                * tailcallopt is enabled
2474 //                * caller/callee are fastcc
2475 //  On X86_64 architecture with GOT-style position independent code only local
2476 //  (within module) calls are supported at the moment.
2477 //  To keep the stack aligned according to platform abi the function
2478 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2479 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2480 //  If a tail called function callee has more arguments than the caller the
2481 //  caller needs to make sure that there is room to move the RETADDR to. This is
2482 //  achieved by reserving an area the size of the argument delta right after the
2483 //  original REtADDR, but before the saved framepointer or the spilled registers
2484 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2485 //  stack layout:
2486 //    arg1
2487 //    arg2
2488 //    RETADDR
2489 //    [ new RETADDR
2490 //      move area ]
2491 //    (possible EBP)
2492 //    ESI
2493 //    EDI
2494 //    local1 ..
2495
2496 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2497 /// for a 16 byte align requirement.
2498 unsigned
2499 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2500                                                SelectionDAG& DAG) const {
2501   MachineFunction &MF = DAG.getMachineFunction();
2502   const TargetMachine &TM = MF.getTarget();
2503   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2504   unsigned StackAlignment = TFI.getStackAlignment();
2505   uint64_t AlignMask = StackAlignment - 1;
2506   int64_t Offset = StackSize;
2507   uint64_t SlotSize = TD->getPointerSize();
2508   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2509     // Number smaller than 12 so just add the difference.
2510     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2511   } else {
2512     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2513     Offset = ((~AlignMask) & Offset) + StackAlignment +
2514       (StackAlignment-SlotSize);
2515   }
2516   return Offset;
2517 }
2518
2519 /// MatchingStackOffset - Return true if the given stack call argument is
2520 /// already available in the same position (relatively) of the caller's
2521 /// incoming argument stack.
2522 static
2523 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2524                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2525                          const X86InstrInfo *TII) {
2526   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2527   int FI = INT_MAX;
2528   if (Arg.getOpcode() == ISD::CopyFromReg) {
2529     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2530     if (!TargetRegisterInfo::isVirtualRegister(VR))
2531       return false;
2532     MachineInstr *Def = MRI->getVRegDef(VR);
2533     if (!Def)
2534       return false;
2535     if (!Flags.isByVal()) {
2536       if (!TII->isLoadFromStackSlot(Def, FI))
2537         return false;
2538     } else {
2539       unsigned Opcode = Def->getOpcode();
2540       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2541           Def->getOperand(1).isFI()) {
2542         FI = Def->getOperand(1).getIndex();
2543         Bytes = Flags.getByValSize();
2544       } else
2545         return false;
2546     }
2547   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2548     if (Flags.isByVal())
2549       // ByVal argument is passed in as a pointer but it's now being
2550       // dereferenced. e.g.
2551       // define @foo(%struct.X* %A) {
2552       //   tail call @bar(%struct.X* byval %A)
2553       // }
2554       return false;
2555     SDValue Ptr = Ld->getBasePtr();
2556     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2557     if (!FINode)
2558       return false;
2559     FI = FINode->getIndex();
2560   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2561     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2562     FI = FINode->getIndex();
2563     Bytes = Flags.getByValSize();
2564   } else
2565     return false;
2566
2567   assert(FI != INT_MAX);
2568   if (!MFI->isFixedObjectIndex(FI))
2569     return false;
2570   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2571 }
2572
2573 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2574 /// for tail call optimization. Targets which want to do tail call
2575 /// optimization should implement this function.
2576 bool
2577 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2578                                                      CallingConv::ID CalleeCC,
2579                                                      bool isVarArg,
2580                                                      bool isCalleeStructRet,
2581                                                      bool isCallerStructRet,
2582                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2583                                     const SmallVectorImpl<SDValue> &OutVals,
2584                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2585                                                      SelectionDAG& DAG) const {
2586   if (!IsTailCallConvention(CalleeCC) &&
2587       CalleeCC != CallingConv::C)
2588     return false;
2589
2590   // If -tailcallopt is specified, make fastcc functions tail-callable.
2591   const MachineFunction &MF = DAG.getMachineFunction();
2592   const Function *CallerF = DAG.getMachineFunction().getFunction();
2593   CallingConv::ID CallerCC = CallerF->getCallingConv();
2594   bool CCMatch = CallerCC == CalleeCC;
2595
2596   if (GuaranteedTailCallOpt) {
2597     if (IsTailCallConvention(CalleeCC) && CCMatch)
2598       return true;
2599     return false;
2600   }
2601
2602   // Look for obvious safe cases to perform tail call optimization that do not
2603   // require ABI changes. This is what gcc calls sibcall.
2604
2605   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2606   // emit a special epilogue.
2607   if (RegInfo->needsStackRealignment(MF))
2608     return false;
2609
2610   // Also avoid sibcall optimization if either caller or callee uses struct
2611   // return semantics.
2612   if (isCalleeStructRet || isCallerStructRet)
2613     return false;
2614
2615   // An stdcall caller is expected to clean up its arguments; the callee
2616   // isn't going to do that.
2617   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2618     return false;
2619
2620   // Do not sibcall optimize vararg calls unless all arguments are passed via
2621   // registers.
2622   if (isVarArg && !Outs.empty()) {
2623
2624     // Optimizing for varargs on Win64 is unlikely to be safe without
2625     // additional testing.
2626     if (Subtarget->isTargetWin64())
2627       return false;
2628
2629     SmallVector<CCValAssign, 16> ArgLocs;
2630     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2631                    getTargetMachine(), ArgLocs, *DAG.getContext());
2632
2633     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2634     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2635       if (!ArgLocs[i].isRegLoc())
2636         return false;
2637   }
2638
2639   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2640   // Therefore if it's not used by the call it is not safe to optimize this into
2641   // a sibcall.
2642   bool Unused = false;
2643   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2644     if (!Ins[i].Used) {
2645       Unused = true;
2646       break;
2647     }
2648   }
2649   if (Unused) {
2650     SmallVector<CCValAssign, 16> RVLocs;
2651     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2652                    getTargetMachine(), RVLocs, *DAG.getContext());
2653     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2654     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2655       CCValAssign &VA = RVLocs[i];
2656       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2657         return false;
2658     }
2659   }
2660
2661   // If the calling conventions do not match, then we'd better make sure the
2662   // results are returned in the same way as what the caller expects.
2663   if (!CCMatch) {
2664     SmallVector<CCValAssign, 16> RVLocs1;
2665     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2666                     getTargetMachine(), RVLocs1, *DAG.getContext());
2667     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2668
2669     SmallVector<CCValAssign, 16> RVLocs2;
2670     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2671                     getTargetMachine(), RVLocs2, *DAG.getContext());
2672     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2673
2674     if (RVLocs1.size() != RVLocs2.size())
2675       return false;
2676     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2677       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2678         return false;
2679       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2680         return false;
2681       if (RVLocs1[i].isRegLoc()) {
2682         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2683           return false;
2684       } else {
2685         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2686           return false;
2687       }
2688     }
2689   }
2690
2691   // If the callee takes no arguments then go on to check the results of the
2692   // call.
2693   if (!Outs.empty()) {
2694     // Check if stack adjustment is needed. For now, do not do this if any
2695     // argument is passed on the stack.
2696     SmallVector<CCValAssign, 16> ArgLocs;
2697     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2698                    getTargetMachine(), ArgLocs, *DAG.getContext());
2699
2700     // Allocate shadow area for Win64
2701     if (Subtarget->isTargetWin64()) {
2702       CCInfo.AllocateStack(32, 8);
2703     }
2704
2705     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2706     if (CCInfo.getNextStackOffset()) {
2707       MachineFunction &MF = DAG.getMachineFunction();
2708       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2709         return false;
2710
2711       // Check if the arguments are already laid out in the right way as
2712       // the caller's fixed stack objects.
2713       MachineFrameInfo *MFI = MF.getFrameInfo();
2714       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2715       const X86InstrInfo *TII =
2716         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2717       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2718         CCValAssign &VA = ArgLocs[i];
2719         SDValue Arg = OutVals[i];
2720         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2721         if (VA.getLocInfo() == CCValAssign::Indirect)
2722           return false;
2723         if (!VA.isRegLoc()) {
2724           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2725                                    MFI, MRI, TII))
2726             return false;
2727         }
2728       }
2729     }
2730
2731     // If the tailcall address may be in a register, then make sure it's
2732     // possible to register allocate for it. In 32-bit, the call address can
2733     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2734     // callee-saved registers are restored. These happen to be the same
2735     // registers used to pass 'inreg' arguments so watch out for those.
2736     if (!Subtarget->is64Bit() &&
2737         !isa<GlobalAddressSDNode>(Callee) &&
2738         !isa<ExternalSymbolSDNode>(Callee)) {
2739       unsigned NumInRegs = 0;
2740       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2741         CCValAssign &VA = ArgLocs[i];
2742         if (!VA.isRegLoc())
2743           continue;
2744         unsigned Reg = VA.getLocReg();
2745         switch (Reg) {
2746         default: break;
2747         case X86::EAX: case X86::EDX: case X86::ECX:
2748           if (++NumInRegs == 3)
2749             return false;
2750           break;
2751         }
2752       }
2753     }
2754   }
2755
2756   return true;
2757 }
2758
2759 FastISel *
2760 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2761   return X86::createFastISel(funcInfo);
2762 }
2763
2764
2765 //===----------------------------------------------------------------------===//
2766 //                           Other Lowering Hooks
2767 //===----------------------------------------------------------------------===//
2768
2769 static bool MayFoldLoad(SDValue Op) {
2770   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2771 }
2772
2773 static bool MayFoldIntoStore(SDValue Op) {
2774   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2775 }
2776
2777 static bool isTargetShuffle(unsigned Opcode) {
2778   switch(Opcode) {
2779   default: return false;
2780   case X86ISD::PSHUFD:
2781   case X86ISD::PSHUFHW:
2782   case X86ISD::PSHUFLW:
2783   case X86ISD::SHUFPD:
2784   case X86ISD::PALIGN:
2785   case X86ISD::SHUFPS:
2786   case X86ISD::MOVLHPS:
2787   case X86ISD::MOVLHPD:
2788   case X86ISD::MOVHLPS:
2789   case X86ISD::MOVLPS:
2790   case X86ISD::MOVLPD:
2791   case X86ISD::MOVSHDUP:
2792   case X86ISD::MOVSLDUP:
2793   case X86ISD::MOVDDUP:
2794   case X86ISD::MOVSS:
2795   case X86ISD::MOVSD:
2796   case X86ISD::UNPCKLPS:
2797   case X86ISD::UNPCKLPD:
2798   case X86ISD::VUNPCKLPSY:
2799   case X86ISD::VUNPCKLPDY:
2800   case X86ISD::PUNPCKLWD:
2801   case X86ISD::PUNPCKLBW:
2802   case X86ISD::PUNPCKLDQ:
2803   case X86ISD::PUNPCKLQDQ:
2804   case X86ISD::UNPCKHPS:
2805   case X86ISD::UNPCKHPD:
2806   case X86ISD::VUNPCKHPSY:
2807   case X86ISD::VUNPCKHPDY:
2808   case X86ISD::PUNPCKHWD:
2809   case X86ISD::PUNPCKHBW:
2810   case X86ISD::PUNPCKHDQ:
2811   case X86ISD::PUNPCKHQDQ:
2812   case X86ISD::VPERMILPS:
2813   case X86ISD::VPERMILPSY:
2814   case X86ISD::VPERMILPD:
2815   case X86ISD::VPERMILPDY:
2816   case X86ISD::VPERM2F128:
2817     return true;
2818   }
2819   return false;
2820 }
2821
2822 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2823                                                SDValue V1, SelectionDAG &DAG) {
2824   switch(Opc) {
2825   default: llvm_unreachable("Unknown x86 shuffle node");
2826   case X86ISD::MOVSHDUP:
2827   case X86ISD::MOVSLDUP:
2828   case X86ISD::MOVDDUP:
2829     return DAG.getNode(Opc, dl, VT, V1);
2830   }
2831
2832   return SDValue();
2833 }
2834
2835 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2836                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2837   switch(Opc) {
2838   default: llvm_unreachable("Unknown x86 shuffle node");
2839   case X86ISD::PSHUFD:
2840   case X86ISD::PSHUFHW:
2841   case X86ISD::PSHUFLW:
2842   case X86ISD::VPERMILPS:
2843   case X86ISD::VPERMILPSY:
2844   case X86ISD::VPERMILPD:
2845   case X86ISD::VPERMILPDY:
2846     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2847   }
2848
2849   return SDValue();
2850 }
2851
2852 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2853                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2854   switch(Opc) {
2855   default: llvm_unreachable("Unknown x86 shuffle node");
2856   case X86ISD::PALIGN:
2857   case X86ISD::SHUFPD:
2858   case X86ISD::SHUFPS:
2859   case X86ISD::VPERM2F128:
2860     return DAG.getNode(Opc, dl, VT, V1, V2,
2861                        DAG.getConstant(TargetMask, MVT::i8));
2862   }
2863   return SDValue();
2864 }
2865
2866 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2867                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2868   switch(Opc) {
2869   default: llvm_unreachable("Unknown x86 shuffle node");
2870   case X86ISD::MOVLHPS:
2871   case X86ISD::MOVLHPD:
2872   case X86ISD::MOVHLPS:
2873   case X86ISD::MOVLPS:
2874   case X86ISD::MOVLPD:
2875   case X86ISD::MOVSS:
2876   case X86ISD::MOVSD:
2877   case X86ISD::UNPCKLPS:
2878   case X86ISD::UNPCKLPD:
2879   case X86ISD::VUNPCKLPSY:
2880   case X86ISD::VUNPCKLPDY:
2881   case X86ISD::PUNPCKLWD:
2882   case X86ISD::PUNPCKLBW:
2883   case X86ISD::PUNPCKLDQ:
2884   case X86ISD::PUNPCKLQDQ:
2885   case X86ISD::UNPCKHPS:
2886   case X86ISD::UNPCKHPD:
2887   case X86ISD::VUNPCKHPSY:
2888   case X86ISD::VUNPCKHPDY:
2889   case X86ISD::PUNPCKHWD:
2890   case X86ISD::PUNPCKHBW:
2891   case X86ISD::PUNPCKHDQ:
2892   case X86ISD::PUNPCKHQDQ:
2893     return DAG.getNode(Opc, dl, VT, V1, V2);
2894   }
2895   return SDValue();
2896 }
2897
2898 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2899   MachineFunction &MF = DAG.getMachineFunction();
2900   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2901   int ReturnAddrIndex = FuncInfo->getRAIndex();
2902
2903   if (ReturnAddrIndex == 0) {
2904     // Set up a frame object for the return address.
2905     uint64_t SlotSize = TD->getPointerSize();
2906     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2907                                                            false);
2908     FuncInfo->setRAIndex(ReturnAddrIndex);
2909   }
2910
2911   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2912 }
2913
2914
2915 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2916                                        bool hasSymbolicDisplacement) {
2917   // Offset should fit into 32 bit immediate field.
2918   if (!isInt<32>(Offset))
2919     return false;
2920
2921   // If we don't have a symbolic displacement - we don't have any extra
2922   // restrictions.
2923   if (!hasSymbolicDisplacement)
2924     return true;
2925
2926   // FIXME: Some tweaks might be needed for medium code model.
2927   if (M != CodeModel::Small && M != CodeModel::Kernel)
2928     return false;
2929
2930   // For small code model we assume that latest object is 16MB before end of 31
2931   // bits boundary. We may also accept pretty large negative constants knowing
2932   // that all objects are in the positive half of address space.
2933   if (M == CodeModel::Small && Offset < 16*1024*1024)
2934     return true;
2935
2936   // For kernel code model we know that all object resist in the negative half
2937   // of 32bits address space. We may not accept negative offsets, since they may
2938   // be just off and we may accept pretty large positive ones.
2939   if (M == CodeModel::Kernel && Offset > 0)
2940     return true;
2941
2942   return false;
2943 }
2944
2945 /// isCalleePop - Determines whether the callee is required to pop its
2946 /// own arguments. Callee pop is necessary to support tail calls.
2947 bool X86::isCalleePop(CallingConv::ID CallingConv,
2948                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2949   if (IsVarArg)
2950     return false;
2951
2952   switch (CallingConv) {
2953   default:
2954     return false;
2955   case CallingConv::X86_StdCall:
2956     return !is64Bit;
2957   case CallingConv::X86_FastCall:
2958     return !is64Bit;
2959   case CallingConv::X86_ThisCall:
2960     return !is64Bit;
2961   case CallingConv::Fast:
2962     return TailCallOpt;
2963   case CallingConv::GHC:
2964     return TailCallOpt;
2965   }
2966 }
2967
2968 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2969 /// specific condition code, returning the condition code and the LHS/RHS of the
2970 /// comparison to make.
2971 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2972                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2973   if (!isFP) {
2974     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2975       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2976         // X > -1   -> X == 0, jump !sign.
2977         RHS = DAG.getConstant(0, RHS.getValueType());
2978         return X86::COND_NS;
2979       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2980         // X < 0   -> X == 0, jump on sign.
2981         return X86::COND_S;
2982       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2983         // X < 1   -> X <= 0
2984         RHS = DAG.getConstant(0, RHS.getValueType());
2985         return X86::COND_LE;
2986       }
2987     }
2988
2989     switch (SetCCOpcode) {
2990     default: llvm_unreachable("Invalid integer condition!");
2991     case ISD::SETEQ:  return X86::COND_E;
2992     case ISD::SETGT:  return X86::COND_G;
2993     case ISD::SETGE:  return X86::COND_GE;
2994     case ISD::SETLT:  return X86::COND_L;
2995     case ISD::SETLE:  return X86::COND_LE;
2996     case ISD::SETNE:  return X86::COND_NE;
2997     case ISD::SETULT: return X86::COND_B;
2998     case ISD::SETUGT: return X86::COND_A;
2999     case ISD::SETULE: return X86::COND_BE;
3000     case ISD::SETUGE: return X86::COND_AE;
3001     }
3002   }
3003
3004   // First determine if it is required or is profitable to flip the operands.
3005
3006   // If LHS is a foldable load, but RHS is not, flip the condition.
3007   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3008       !ISD::isNON_EXTLoad(RHS.getNode())) {
3009     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3010     std::swap(LHS, RHS);
3011   }
3012
3013   switch (SetCCOpcode) {
3014   default: break;
3015   case ISD::SETOLT:
3016   case ISD::SETOLE:
3017   case ISD::SETUGT:
3018   case ISD::SETUGE:
3019     std::swap(LHS, RHS);
3020     break;
3021   }
3022
3023   // On a floating point condition, the flags are set as follows:
3024   // ZF  PF  CF   op
3025   //  0 | 0 | 0 | X > Y
3026   //  0 | 0 | 1 | X < Y
3027   //  1 | 0 | 0 | X == Y
3028   //  1 | 1 | 1 | unordered
3029   switch (SetCCOpcode) {
3030   default: llvm_unreachable("Condcode should be pre-legalized away");
3031   case ISD::SETUEQ:
3032   case ISD::SETEQ:   return X86::COND_E;
3033   case ISD::SETOLT:              // flipped
3034   case ISD::SETOGT:
3035   case ISD::SETGT:   return X86::COND_A;
3036   case ISD::SETOLE:              // flipped
3037   case ISD::SETOGE:
3038   case ISD::SETGE:   return X86::COND_AE;
3039   case ISD::SETUGT:              // flipped
3040   case ISD::SETULT:
3041   case ISD::SETLT:   return X86::COND_B;
3042   case ISD::SETUGE:              // flipped
3043   case ISD::SETULE:
3044   case ISD::SETLE:   return X86::COND_BE;
3045   case ISD::SETONE:
3046   case ISD::SETNE:   return X86::COND_NE;
3047   case ISD::SETUO:   return X86::COND_P;
3048   case ISD::SETO:    return X86::COND_NP;
3049   case ISD::SETOEQ:
3050   case ISD::SETUNE:  return X86::COND_INVALID;
3051   }
3052 }
3053
3054 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3055 /// code. Current x86 isa includes the following FP cmov instructions:
3056 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3057 static bool hasFPCMov(unsigned X86CC) {
3058   switch (X86CC) {
3059   default:
3060     return false;
3061   case X86::COND_B:
3062   case X86::COND_BE:
3063   case X86::COND_E:
3064   case X86::COND_P:
3065   case X86::COND_A:
3066   case X86::COND_AE:
3067   case X86::COND_NE:
3068   case X86::COND_NP:
3069     return true;
3070   }
3071 }
3072
3073 /// isFPImmLegal - Returns true if the target can instruction select the
3074 /// specified FP immediate natively. If false, the legalizer will
3075 /// materialize the FP immediate as a load from a constant pool.
3076 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3077   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3078     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3079       return true;
3080   }
3081   return false;
3082 }
3083
3084 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3085 /// the specified range (L, H].
3086 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3087   return (Val < 0) || (Val >= Low && Val < Hi);
3088 }
3089
3090 /// isUndefOrInRange - Return true if every element in Mask, begining
3091 /// from position Pos and ending in Pos+Size, falls within the specified
3092 /// range (L, L+Pos]. or is undef.
3093 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3094                              int Pos, int Size, int Low, int Hi) {
3095   for (int i = Pos, e = Pos+Size; i != e; ++i)
3096     if (!isUndefOrInRange(Mask[i], Low, Hi))
3097       return false;
3098   return true;
3099 }
3100
3101 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3102 /// specified value.
3103 static bool isUndefOrEqual(int Val, int CmpVal) {
3104   if (Val < 0 || Val == CmpVal)
3105     return true;
3106   return false;
3107 }
3108
3109 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3110 /// from position Pos and ending in Pos+Size, falls within the specified
3111 /// sequential range (L, L+Pos]. or is undef.
3112 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3113                                        int Pos, int Size, int Low) {
3114   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3115     if (!isUndefOrEqual(Mask[i], Low))
3116       return false;
3117   return true;
3118 }
3119
3120 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3121 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3122 /// the second operand.
3123 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3124   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3125     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3126   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3127     return (Mask[0] < 2 && Mask[1] < 2);
3128   return false;
3129 }
3130
3131 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3132   SmallVector<int, 8> M;
3133   N->getMask(M);
3134   return ::isPSHUFDMask(M, N->getValueType(0));
3135 }
3136
3137 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3138 /// is suitable for input to PSHUFHW.
3139 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3140   if (VT != MVT::v8i16)
3141     return false;
3142
3143   // Lower quadword copied in order or undef.
3144   for (int i = 0; i != 4; ++i)
3145     if (Mask[i] >= 0 && Mask[i] != i)
3146       return false;
3147
3148   // Upper quadword shuffled.
3149   for (int i = 4; i != 8; ++i)
3150     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3151       return false;
3152
3153   return true;
3154 }
3155
3156 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3157   SmallVector<int, 8> M;
3158   N->getMask(M);
3159   return ::isPSHUFHWMask(M, N->getValueType(0));
3160 }
3161
3162 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3163 /// is suitable for input to PSHUFLW.
3164 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3165   if (VT != MVT::v8i16)
3166     return false;
3167
3168   // Upper quadword copied in order.
3169   for (int i = 4; i != 8; ++i)
3170     if (Mask[i] >= 0 && Mask[i] != i)
3171       return false;
3172
3173   // Lower quadword shuffled.
3174   for (int i = 0; i != 4; ++i)
3175     if (Mask[i] >= 4)
3176       return false;
3177
3178   return true;
3179 }
3180
3181 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3182   SmallVector<int, 8> M;
3183   N->getMask(M);
3184   return ::isPSHUFLWMask(M, N->getValueType(0));
3185 }
3186
3187 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3188 /// is suitable for input to PALIGNR.
3189 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3190                           bool hasSSSE3OrAVX) {
3191   int i, e = VT.getVectorNumElements();
3192   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3193     return false;
3194
3195   // Do not handle v2i64 / v2f64 shuffles with palignr.
3196   if (e < 4 || !hasSSSE3OrAVX)
3197     return false;
3198
3199   for (i = 0; i != e; ++i)
3200     if (Mask[i] >= 0)
3201       break;
3202
3203   // All undef, not a palignr.
3204   if (i == e)
3205     return false;
3206
3207   // Make sure we're shifting in the right direction.
3208   if (Mask[i] <= i)
3209     return false;
3210
3211   int s = Mask[i] - i;
3212
3213   // Check the rest of the elements to see if they are consecutive.
3214   for (++i; i != e; ++i) {
3215     int m = Mask[i];
3216     if (m >= 0 && m != s+i)
3217       return false;
3218   }
3219   return true;
3220 }
3221
3222 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3223 /// specifies a shuffle of elements that is suitable for input to 256-bit
3224 /// VSHUFPSY.
3225 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3226                           const X86Subtarget *Subtarget) {
3227   int NumElems = VT.getVectorNumElements();
3228
3229   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3230     return false;
3231
3232   if (NumElems != 8)
3233     return false;
3234
3235   // VSHUFPSY divides the resulting vector into 4 chunks.
3236   // The sources are also splitted into 4 chunks, and each destination
3237   // chunk must come from a different source chunk.
3238   //
3239   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3240   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3241   //
3242   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3243   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3244   //
3245   int QuarterSize = NumElems/4;
3246   int HalfSize = QuarterSize*2;
3247   for (int i = 0; i < QuarterSize; ++i)
3248     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3249       return false;
3250   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3251     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3252       return false;
3253
3254   // The mask of the second half must be the same as the first but with
3255   // the appropriate offsets. This works in the same way as VPERMILPS
3256   // works with masks.
3257   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3258     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3259       return false;
3260     int FstHalfIdx = i-HalfSize;
3261     if (Mask[FstHalfIdx] < 0)
3262       continue;
3263     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3264       return false;
3265   }
3266   for (int i = QuarterSize*3; i < NumElems; ++i) {
3267     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3268       return false;
3269     int FstHalfIdx = i-HalfSize;
3270     if (Mask[FstHalfIdx] < 0)
3271       continue;
3272     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3273       return false;
3274
3275   }
3276
3277   return true;
3278 }
3279
3280 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3281 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3282 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3283   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3284   EVT VT = SVOp->getValueType(0);
3285   int NumElems = VT.getVectorNumElements();
3286
3287   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3288          "Only supports v8i32 and v8f32 types");
3289
3290   int HalfSize = NumElems/2;
3291   unsigned Mask = 0;
3292   for (int i = 0; i != NumElems ; ++i) {
3293     if (SVOp->getMaskElt(i) < 0)
3294       continue;
3295     // The mask of the first half must be equal to the second one.
3296     unsigned Shamt = (i%HalfSize)*2;
3297     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3298     Mask |= Elt << Shamt;
3299   }
3300
3301   return Mask;
3302 }
3303
3304 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3305 /// specifies a shuffle of elements that is suitable for input to 256-bit
3306 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3307 /// version and the mask of the second half isn't binded with the first
3308 /// one.
3309 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3310                            const X86Subtarget *Subtarget) {
3311   int NumElems = VT.getVectorNumElements();
3312
3313   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3314     return false;
3315
3316   if (NumElems != 4)
3317     return false;
3318
3319   // VSHUFPSY divides the resulting vector into 4 chunks.
3320   // The sources are also splitted into 4 chunks, and each destination
3321   // chunk must come from a different source chunk.
3322   //
3323   //  SRC1 =>      X3       X2       X1       X0
3324   //  SRC2 =>      Y3       Y2       Y1       Y0
3325   //
3326   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3327   //
3328   int QuarterSize = NumElems/4;
3329   int HalfSize = QuarterSize*2;
3330   for (int i = 0; i < QuarterSize; ++i)
3331     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3332       return false;
3333   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3334     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3335       return false;
3336   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3337     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3338       return false;
3339   for (int i = QuarterSize*3; i < NumElems; ++i)
3340     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3341       return false;
3342
3343   return true;
3344 }
3345
3346 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3347 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3348 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3349   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3350   EVT VT = SVOp->getValueType(0);
3351   int NumElems = VT.getVectorNumElements();
3352
3353   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3354          "Only supports v4i64 and v4f64 types");
3355
3356   int HalfSize = NumElems/2;
3357   unsigned Mask = 0;
3358   for (int i = 0; i != NumElems ; ++i) {
3359     if (SVOp->getMaskElt(i) < 0)
3360       continue;
3361     int Elt = SVOp->getMaskElt(i) % HalfSize;
3362     Mask |= Elt << i;
3363   }
3364
3365   return Mask;
3366 }
3367
3368 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3369 /// specifies a shuffle of elements that is suitable for input to 128-bit
3370 /// SHUFPS and SHUFPD.
3371 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3372   int NumElems = VT.getVectorNumElements();
3373
3374   if (VT.getSizeInBits() != 128)
3375     return false;
3376
3377   if (NumElems != 2 && NumElems != 4)
3378     return false;
3379
3380   int Half = NumElems / 2;
3381   for (int i = 0; i < Half; ++i)
3382     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3383       return false;
3384   for (int i = Half; i < NumElems; ++i)
3385     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3386       return false;
3387
3388   return true;
3389 }
3390
3391 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3392   SmallVector<int, 8> M;
3393   N->getMask(M);
3394   return ::isSHUFPMask(M, N->getValueType(0));
3395 }
3396
3397 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3398 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3399 /// half elements to come from vector 1 (which would equal the dest.) and
3400 /// the upper half to come from vector 2.
3401 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3402   int NumElems = VT.getVectorNumElements();
3403
3404   if (NumElems != 2 && NumElems != 4)
3405     return false;
3406
3407   int Half = NumElems / 2;
3408   for (int i = 0; i < Half; ++i)
3409     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3410       return false;
3411   for (int i = Half; i < NumElems; ++i)
3412     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3413       return false;
3414   return true;
3415 }
3416
3417 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3418   SmallVector<int, 8> M;
3419   N->getMask(M);
3420   return isCommutedSHUFPMask(M, N->getValueType(0));
3421 }
3422
3423 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3424 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3425 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3426   EVT VT = N->getValueType(0);
3427   unsigned NumElems = VT.getVectorNumElements();
3428
3429   if (VT.getSizeInBits() != 128)
3430     return false;
3431
3432   if (NumElems != 4)
3433     return false;
3434
3435   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3436   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3437          isUndefOrEqual(N->getMaskElt(1), 7) &&
3438          isUndefOrEqual(N->getMaskElt(2), 2) &&
3439          isUndefOrEqual(N->getMaskElt(3), 3);
3440 }
3441
3442 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3443 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3444 /// <2, 3, 2, 3>
3445 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3446   EVT VT = N->getValueType(0);
3447   unsigned NumElems = VT.getVectorNumElements();
3448
3449   if (VT.getSizeInBits() != 128)
3450     return false;
3451
3452   if (NumElems != 4)
3453     return false;
3454
3455   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3456          isUndefOrEqual(N->getMaskElt(1), 3) &&
3457          isUndefOrEqual(N->getMaskElt(2), 2) &&
3458          isUndefOrEqual(N->getMaskElt(3), 3);
3459 }
3460
3461 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3462 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3463 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3464   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3465
3466   if (NumElems != 2 && NumElems != 4)
3467     return false;
3468
3469   for (unsigned i = 0; i < NumElems/2; ++i)
3470     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3471       return false;
3472
3473   for (unsigned i = NumElems/2; i < NumElems; ++i)
3474     if (!isUndefOrEqual(N->getMaskElt(i), i))
3475       return false;
3476
3477   return true;
3478 }
3479
3480 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3481 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3482 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3483   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3484
3485   if ((NumElems != 2 && NumElems != 4)
3486       || N->getValueType(0).getSizeInBits() > 128)
3487     return false;
3488
3489   for (unsigned i = 0; i < NumElems/2; ++i)
3490     if (!isUndefOrEqual(N->getMaskElt(i), i))
3491       return false;
3492
3493   for (unsigned i = 0; i < NumElems/2; ++i)
3494     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3495       return false;
3496
3497   return true;
3498 }
3499
3500 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3501 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3502 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3503                          bool V2IsSplat = false) {
3504   int NumElts = VT.getVectorNumElements();
3505
3506   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3507          "Unsupported vector type for unpckh");
3508
3509   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3510     return false;
3511
3512   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3513   // independently on 128-bit lanes.
3514   unsigned NumLanes = VT.getSizeInBits()/128;
3515   unsigned NumLaneElts = NumElts/NumLanes;
3516
3517   unsigned Start = 0;
3518   unsigned End = NumLaneElts;
3519   for (unsigned s = 0; s < NumLanes; ++s) {
3520     for (unsigned i = Start, j = s * NumLaneElts;
3521          i != End;
3522          i += 2, ++j) {
3523       int BitI  = Mask[i];
3524       int BitI1 = Mask[i+1];
3525       if (!isUndefOrEqual(BitI, j))
3526         return false;
3527       if (V2IsSplat) {
3528         if (!isUndefOrEqual(BitI1, NumElts))
3529           return false;
3530       } else {
3531         if (!isUndefOrEqual(BitI1, j + NumElts))
3532           return false;
3533       }
3534     }
3535     // Process the next 128 bits.
3536     Start += NumLaneElts;
3537     End += NumLaneElts;
3538   }
3539
3540   return true;
3541 }
3542
3543 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3544   SmallVector<int, 8> M;
3545   N->getMask(M);
3546   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3547 }
3548
3549 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3550 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3551 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3552                          bool V2IsSplat = false) {
3553   int NumElts = VT.getVectorNumElements();
3554
3555   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3556          "Unsupported vector type for unpckh");
3557
3558   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3559     return false;
3560
3561   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3562   // independently on 128-bit lanes.
3563   unsigned NumLanes = VT.getSizeInBits()/128;
3564   unsigned NumLaneElts = NumElts/NumLanes;
3565
3566   unsigned Start = 0;
3567   unsigned End = NumLaneElts;
3568   for (unsigned l = 0; l != NumLanes; ++l) {
3569     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3570                              i != End; i += 2, ++j) {
3571       int BitI  = Mask[i];
3572       int BitI1 = Mask[i+1];
3573       if (!isUndefOrEqual(BitI, j))
3574         return false;
3575       if (V2IsSplat) {
3576         if (isUndefOrEqual(BitI1, NumElts))
3577           return false;
3578       } else {
3579         if (!isUndefOrEqual(BitI1, j+NumElts))
3580           return false;
3581       }
3582     }
3583     // Process the next 128 bits.
3584     Start += NumLaneElts;
3585     End += NumLaneElts;
3586   }
3587   return true;
3588 }
3589
3590 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3591   SmallVector<int, 8> M;
3592   N->getMask(M);
3593   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3594 }
3595
3596 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3597 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3598 /// <0, 0, 1, 1>
3599 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3600   int NumElems = VT.getVectorNumElements();
3601   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3602     return false;
3603
3604   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3605   // FIXME: Need a better way to get rid of this, there's no latency difference
3606   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3607   // the former later. We should also remove the "_undef" special mask.
3608   if (NumElems == 4 && VT.getSizeInBits() == 256)
3609     return false;
3610
3611   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3612   // independently on 128-bit lanes.
3613   unsigned NumLanes = VT.getSizeInBits() / 128;
3614   unsigned NumLaneElts = NumElems / NumLanes;
3615
3616   for (unsigned s = 0; s < NumLanes; ++s) {
3617     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3618          i != NumLaneElts * (s + 1);
3619          i += 2, ++j) {
3620       int BitI  = Mask[i];
3621       int BitI1 = Mask[i+1];
3622
3623       if (!isUndefOrEqual(BitI, j))
3624         return false;
3625       if (!isUndefOrEqual(BitI1, j))
3626         return false;
3627     }
3628   }
3629
3630   return true;
3631 }
3632
3633 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3634   SmallVector<int, 8> M;
3635   N->getMask(M);
3636   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3637 }
3638
3639 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3640 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3641 /// <2, 2, 3, 3>
3642 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3643   int NumElems = VT.getVectorNumElements();
3644   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3645     return false;
3646
3647   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3648     int BitI  = Mask[i];
3649     int BitI1 = Mask[i+1];
3650     if (!isUndefOrEqual(BitI, j))
3651       return false;
3652     if (!isUndefOrEqual(BitI1, j))
3653       return false;
3654   }
3655   return true;
3656 }
3657
3658 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3659   SmallVector<int, 8> M;
3660   N->getMask(M);
3661   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3662 }
3663
3664 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3665 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3666 /// MOVSD, and MOVD, i.e. setting the lowest element.
3667 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3668   if (VT.getVectorElementType().getSizeInBits() < 32)
3669     return false;
3670
3671   int NumElts = VT.getVectorNumElements();
3672
3673   if (!isUndefOrEqual(Mask[0], NumElts))
3674     return false;
3675
3676   for (int i = 1; i < NumElts; ++i)
3677     if (!isUndefOrEqual(Mask[i], i))
3678       return false;
3679
3680   return true;
3681 }
3682
3683 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3684   SmallVector<int, 8> M;
3685   N->getMask(M);
3686   return ::isMOVLMask(M, N->getValueType(0));
3687 }
3688
3689 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3690 /// as permutations between 128-bit chunks or halves. As an example: this
3691 /// shuffle bellow:
3692 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3693 /// The first half comes from the second half of V1 and the second half from the
3694 /// the second half of V2.
3695 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3696                              const X86Subtarget *Subtarget) {
3697   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3698     return false;
3699
3700   // The shuffle result is divided into half A and half B. In total the two
3701   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3702   // B must come from C, D, E or F.
3703   int HalfSize = VT.getVectorNumElements()/2;
3704   bool MatchA = false, MatchB = false;
3705
3706   // Check if A comes from one of C, D, E, F.
3707   for (int Half = 0; Half < 4; ++Half) {
3708     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3709       MatchA = true;
3710       break;
3711     }
3712   }
3713
3714   // Check if B comes from one of C, D, E, F.
3715   for (int Half = 0; Half < 4; ++Half) {
3716     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3717       MatchB = true;
3718       break;
3719     }
3720   }
3721
3722   return MatchA && MatchB;
3723 }
3724
3725 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3726 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3727 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3728   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3729   EVT VT = SVOp->getValueType(0);
3730
3731   int HalfSize = VT.getVectorNumElements()/2;
3732
3733   int FstHalf = 0, SndHalf = 0;
3734   for (int i = 0; i < HalfSize; ++i) {
3735     if (SVOp->getMaskElt(i) > 0) {
3736       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3737       break;
3738     }
3739   }
3740   for (int i = HalfSize; i < HalfSize*2; ++i) {
3741     if (SVOp->getMaskElt(i) > 0) {
3742       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3743       break;
3744     }
3745   }
3746
3747   return (FstHalf | (SndHalf << 4));
3748 }
3749
3750 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3751 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3752 /// Note that VPERMIL mask matching is different depending whether theunderlying
3753 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3754 /// to the same elements of the low, but to the higher half of the source.
3755 /// In VPERMILPD the two lanes could be shuffled independently of each other
3756 /// with the same restriction that lanes can't be crossed.
3757 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3758                             const X86Subtarget *Subtarget) {
3759   int NumElts = VT.getVectorNumElements();
3760   int NumLanes = VT.getSizeInBits()/128;
3761
3762   if (!Subtarget->hasAVX())
3763     return false;
3764
3765   // Only match 256-bit with 64-bit types
3766   if (VT.getSizeInBits() != 256 || NumElts != 4)
3767     return false;
3768
3769   // The mask on the high lane is independent of the low. Both can match
3770   // any element in inside its own lane, but can't cross.
3771   int LaneSize = NumElts/NumLanes;
3772   for (int l = 0; l < NumLanes; ++l)
3773     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3774       int LaneStart = l*LaneSize;
3775       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3776         return false;
3777     }
3778
3779   return true;
3780 }
3781
3782 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3783 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3784 /// Note that VPERMIL mask matching is different depending whether theunderlying
3785 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3786 /// to the same elements of the low, but to the higher half of the source.
3787 /// In VPERMILPD the two lanes could be shuffled independently of each other
3788 /// with the same restriction that lanes can't be crossed.
3789 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3790                             const X86Subtarget *Subtarget) {
3791   unsigned NumElts = VT.getVectorNumElements();
3792   unsigned NumLanes = VT.getSizeInBits()/128;
3793
3794   if (!Subtarget->hasAVX())
3795     return false;
3796
3797   // Only match 256-bit with 32-bit types
3798   if (VT.getSizeInBits() != 256 || NumElts != 8)
3799     return false;
3800
3801   // The mask on the high lane should be the same as the low. Actually,
3802   // they can differ if any of the corresponding index in a lane is undef
3803   // and the other stays in range.
3804   int LaneSize = NumElts/NumLanes;
3805   for (int i = 0; i < LaneSize; ++i) {
3806     int HighElt = i+LaneSize;
3807     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3808     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3809
3810     if (!HighValid || !LowValid)
3811       return false;
3812     if (Mask[i] < 0 || Mask[HighElt] < 0)
3813       continue;
3814     if (Mask[HighElt]-Mask[i] != LaneSize)
3815       return false;
3816   }
3817
3818   return true;
3819 }
3820
3821 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3822 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3823 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3824   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3825   EVT VT = SVOp->getValueType(0);
3826
3827   int NumElts = VT.getVectorNumElements();
3828   int NumLanes = VT.getSizeInBits()/128;
3829   int LaneSize = NumElts/NumLanes;
3830
3831   // Although the mask is equal for both lanes do it twice to get the cases
3832   // where a mask will match because the same mask element is undef on the
3833   // first half but valid on the second. This would get pathological cases
3834   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3835   unsigned Mask = 0;
3836   for (int l = 0; l < NumLanes; ++l) {
3837     for (int i = 0; i < LaneSize; ++i) {
3838       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3839       if (MaskElt < 0)
3840         continue;
3841       if (MaskElt >= LaneSize)
3842         MaskElt -= LaneSize;
3843       Mask |= MaskElt << (i*2);
3844     }
3845   }
3846
3847   return Mask;
3848 }
3849
3850 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3851 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3852 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3853   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3854   EVT VT = SVOp->getValueType(0);
3855
3856   int NumElts = VT.getVectorNumElements();
3857   int NumLanes = VT.getSizeInBits()/128;
3858
3859   unsigned Mask = 0;
3860   int LaneSize = NumElts/NumLanes;
3861   for (int l = 0; l < NumLanes; ++l)
3862     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3863       int MaskElt = SVOp->getMaskElt(i);
3864       if (MaskElt < 0)
3865         continue;
3866       Mask |= (MaskElt-l*LaneSize) << i;
3867     }
3868
3869   return Mask;
3870 }
3871
3872 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3873 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3874 /// element of vector 2 and the other elements to come from vector 1 in order.
3875 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3876                                bool V2IsSplat = false, bool V2IsUndef = false) {
3877   int NumOps = VT.getVectorNumElements();
3878   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3879     return false;
3880
3881   if (!isUndefOrEqual(Mask[0], 0))
3882     return false;
3883
3884   for (int i = 1; i < NumOps; ++i)
3885     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3886           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3887           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3888       return false;
3889
3890   return true;
3891 }
3892
3893 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3894                            bool V2IsUndef = false) {
3895   SmallVector<int, 8> M;
3896   N->getMask(M);
3897   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3898 }
3899
3900 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3901 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3902 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3903 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3904                          const X86Subtarget *Subtarget) {
3905   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3906     return false;
3907
3908   // The second vector must be undef
3909   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3910     return false;
3911
3912   EVT VT = N->getValueType(0);
3913   unsigned NumElems = VT.getVectorNumElements();
3914
3915   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3916       (VT.getSizeInBits() == 256 && NumElems != 8))
3917     return false;
3918
3919   // "i+1" is the value the indexed mask element must have
3920   for (unsigned i = 0; i < NumElems; i += 2)
3921     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3922         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3923       return false;
3924
3925   return true;
3926 }
3927
3928 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3930 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3931 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3932                          const X86Subtarget *Subtarget) {
3933   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3934     return false;
3935
3936   // The second vector must be undef
3937   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3938     return false;
3939
3940   EVT VT = N->getValueType(0);
3941   unsigned NumElems = VT.getVectorNumElements();
3942
3943   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3944       (VT.getSizeInBits() == 256 && NumElems != 8))
3945     return false;
3946
3947   // "i" is the value the indexed mask element must have
3948   for (unsigned i = 0; i < NumElems; i += 2)
3949     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3950         !isUndefOrEqual(N->getMaskElt(i+1), i))
3951       return false;
3952
3953   return true;
3954 }
3955
3956 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3957 /// specifies a shuffle of elements that is suitable for input to 256-bit
3958 /// version of MOVDDUP.
3959 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3960                            const X86Subtarget *Subtarget) {
3961   EVT VT = N->getValueType(0);
3962   int NumElts = VT.getVectorNumElements();
3963   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3964
3965   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3966       !V2IsUndef || NumElts != 4)
3967     return false;
3968
3969   for (int i = 0; i != NumElts/2; ++i)
3970     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3971       return false;
3972   for (int i = NumElts/2; i != NumElts; ++i)
3973     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3974       return false;
3975   return true;
3976 }
3977
3978 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to 128-bit
3980 /// version of MOVDDUP.
3981 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3982   EVT VT = N->getValueType(0);
3983
3984   if (VT.getSizeInBits() != 128)
3985     return false;
3986
3987   int e = VT.getVectorNumElements() / 2;
3988   for (int i = 0; i < e; ++i)
3989     if (!isUndefOrEqual(N->getMaskElt(i), i))
3990       return false;
3991   for (int i = 0; i < e; ++i)
3992     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3993       return false;
3994   return true;
3995 }
3996
3997 /// isVEXTRACTF128Index - Return true if the specified
3998 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3999 /// suitable for input to VEXTRACTF128.
4000 bool X86::isVEXTRACTF128Index(SDNode *N) {
4001   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4002     return false;
4003
4004   // The index should be aligned on a 128-bit boundary.
4005   uint64_t Index =
4006     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4007
4008   unsigned VL = N->getValueType(0).getVectorNumElements();
4009   unsigned VBits = N->getValueType(0).getSizeInBits();
4010   unsigned ElSize = VBits / VL;
4011   bool Result = (Index * ElSize) % 128 == 0;
4012
4013   return Result;
4014 }
4015
4016 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4017 /// operand specifies a subvector insert that is suitable for input to
4018 /// VINSERTF128.
4019 bool X86::isVINSERTF128Index(SDNode *N) {
4020   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4021     return false;
4022
4023   // The index should be aligned on a 128-bit boundary.
4024   uint64_t Index =
4025     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4026
4027   unsigned VL = N->getValueType(0).getVectorNumElements();
4028   unsigned VBits = N->getValueType(0).getSizeInBits();
4029   unsigned ElSize = VBits / VL;
4030   bool Result = (Index * ElSize) % 128 == 0;
4031
4032   return Result;
4033 }
4034
4035 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4036 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4037 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4038   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4039   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4040
4041   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4042   unsigned Mask = 0;
4043   for (int i = 0; i < NumOperands; ++i) {
4044     int Val = SVOp->getMaskElt(NumOperands-i-1);
4045     if (Val < 0) Val = 0;
4046     if (Val >= NumOperands) Val -= NumOperands;
4047     Mask |= Val;
4048     if (i != NumOperands - 1)
4049       Mask <<= Shift;
4050   }
4051   return Mask;
4052 }
4053
4054 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4055 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4056 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4057   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4058   unsigned Mask = 0;
4059   // 8 nodes, but we only care about the last 4.
4060   for (unsigned i = 7; i >= 4; --i) {
4061     int Val = SVOp->getMaskElt(i);
4062     if (Val >= 0)
4063       Mask |= (Val - 4);
4064     if (i != 4)
4065       Mask <<= 2;
4066   }
4067   return Mask;
4068 }
4069
4070 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4071 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4072 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4073   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4074   unsigned Mask = 0;
4075   // 8 nodes, but we only care about the first 4.
4076   for (int i = 3; i >= 0; --i) {
4077     int Val = SVOp->getMaskElt(i);
4078     if (Val >= 0)
4079       Mask |= Val;
4080     if (i != 0)
4081       Mask <<= 2;
4082   }
4083   return Mask;
4084 }
4085
4086 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4087 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4088 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4089   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4090   EVT VVT = N->getValueType(0);
4091   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4092   int Val = 0;
4093
4094   unsigned i, e;
4095   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4096     Val = SVOp->getMaskElt(i);
4097     if (Val >= 0)
4098       break;
4099   }
4100   assert(Val - i > 0 && "PALIGNR imm should be positive");
4101   return (Val - i) * EltSize;
4102 }
4103
4104 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4105 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4106 /// instructions.
4107 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4108   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4109     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4110
4111   uint64_t Index =
4112     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4113
4114   EVT VecVT = N->getOperand(0).getValueType();
4115   EVT ElVT = VecVT.getVectorElementType();
4116
4117   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4118   return Index / NumElemsPerChunk;
4119 }
4120
4121 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4122 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4123 /// instructions.
4124 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4125   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4126     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4127
4128   uint64_t Index =
4129     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4130
4131   EVT VecVT = N->getValueType(0);
4132   EVT ElVT = VecVT.getVectorElementType();
4133
4134   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4135   return Index / NumElemsPerChunk;
4136 }
4137
4138 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4139 /// constant +0.0.
4140 bool X86::isZeroNode(SDValue Elt) {
4141   return ((isa<ConstantSDNode>(Elt) &&
4142            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4143           (isa<ConstantFPSDNode>(Elt) &&
4144            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4145 }
4146
4147 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4148 /// their permute mask.
4149 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4150                                     SelectionDAG &DAG) {
4151   EVT VT = SVOp->getValueType(0);
4152   unsigned NumElems = VT.getVectorNumElements();
4153   SmallVector<int, 8> MaskVec;
4154
4155   for (unsigned i = 0; i != NumElems; ++i) {
4156     int idx = SVOp->getMaskElt(i);
4157     if (idx < 0)
4158       MaskVec.push_back(idx);
4159     else if (idx < (int)NumElems)
4160       MaskVec.push_back(idx + NumElems);
4161     else
4162       MaskVec.push_back(idx - NumElems);
4163   }
4164   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4165                               SVOp->getOperand(0), &MaskVec[0]);
4166 }
4167
4168 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4169 /// the two vector operands have swapped position.
4170 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4171   unsigned NumElems = VT.getVectorNumElements();
4172   for (unsigned i = 0; i != NumElems; ++i) {
4173     int idx = Mask[i];
4174     if (idx < 0)
4175       continue;
4176     else if (idx < (int)NumElems)
4177       Mask[i] = idx + NumElems;
4178     else
4179       Mask[i] = idx - NumElems;
4180   }
4181 }
4182
4183 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4184 /// match movhlps. The lower half elements should come from upper half of
4185 /// V1 (and in order), and the upper half elements should come from the upper
4186 /// half of V2 (and in order).
4187 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4188   EVT VT = Op->getValueType(0);
4189   if (VT.getSizeInBits() != 128)
4190     return false;
4191   if (VT.getVectorNumElements() != 4)
4192     return false;
4193   for (unsigned i = 0, e = 2; i != e; ++i)
4194     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4195       return false;
4196   for (unsigned i = 2; i != 4; ++i)
4197     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4198       return false;
4199   return true;
4200 }
4201
4202 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4203 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4204 /// required.
4205 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4206   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4207     return false;
4208   N = N->getOperand(0).getNode();
4209   if (!ISD::isNON_EXTLoad(N))
4210     return false;
4211   if (LD)
4212     *LD = cast<LoadSDNode>(N);
4213   return true;
4214 }
4215
4216 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4217 /// match movlp{s|d}. The lower half elements should come from lower half of
4218 /// V1 (and in order), and the upper half elements should come from the upper
4219 /// half of V2 (and in order). And since V1 will become the source of the
4220 /// MOVLP, it must be either a vector load or a scalar load to vector.
4221 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4222                                ShuffleVectorSDNode *Op) {
4223   EVT VT = Op->getValueType(0);
4224   if (VT.getSizeInBits() != 128)
4225     return false;
4226
4227   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4228     return false;
4229   // Is V2 is a vector load, don't do this transformation. We will try to use
4230   // load folding shufps op.
4231   if (ISD::isNON_EXTLoad(V2))
4232     return false;
4233
4234   unsigned NumElems = VT.getVectorNumElements();
4235
4236   if (NumElems != 2 && NumElems != 4)
4237     return false;
4238   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4239     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4240       return false;
4241   for (unsigned i = NumElems/2; i != NumElems; ++i)
4242     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4243       return false;
4244   return true;
4245 }
4246
4247 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4248 /// all the same.
4249 static bool isSplatVector(SDNode *N) {
4250   if (N->getOpcode() != ISD::BUILD_VECTOR)
4251     return false;
4252
4253   SDValue SplatValue = N->getOperand(0);
4254   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4255     if (N->getOperand(i) != SplatValue)
4256       return false;
4257   return true;
4258 }
4259
4260 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4261 /// to an zero vector.
4262 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4263 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4264   SDValue V1 = N->getOperand(0);
4265   SDValue V2 = N->getOperand(1);
4266   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4267   for (unsigned i = 0; i != NumElems; ++i) {
4268     int Idx = N->getMaskElt(i);
4269     if (Idx >= (int)NumElems) {
4270       unsigned Opc = V2.getOpcode();
4271       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4272         continue;
4273       if (Opc != ISD::BUILD_VECTOR ||
4274           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4275         return false;
4276     } else if (Idx >= 0) {
4277       unsigned Opc = V1.getOpcode();
4278       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4279         continue;
4280       if (Opc != ISD::BUILD_VECTOR ||
4281           !X86::isZeroNode(V1.getOperand(Idx)))
4282         return false;
4283     }
4284   }
4285   return true;
4286 }
4287
4288 /// getZeroVector - Returns a vector of specified type with all zero elements.
4289 ///
4290 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4291                              DebugLoc dl) {
4292   assert(VT.isVector() && "Expected a vector type");
4293
4294   // Always build SSE zero vectors as <4 x i32> bitcasted
4295   // to their dest type. This ensures they get CSE'd.
4296   SDValue Vec;
4297   if (VT.getSizeInBits() == 128) {  // SSE
4298     if (HasXMMInt) {  // SSE2
4299       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4300       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4301     } else { // SSE1
4302       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4303       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4304     }
4305   } else if (VT.getSizeInBits() == 256) { // AVX
4306     // 256-bit logic and arithmetic instructions in AVX are
4307     // all floating-point, no support for integer ops. Default
4308     // to emitting fp zeroed vectors then.
4309     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4310     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4311     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4312   }
4313   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4314 }
4315
4316 /// getOnesVector - Returns a vector of specified type with all bits set.
4317 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4318 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4319 /// original type, ensuring they get CSE'd.
4320 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4321   assert(VT.isVector() && "Expected a vector type");
4322   assert((VT.is128BitVector() || VT.is256BitVector())
4323          && "Expected a 128-bit or 256-bit vector type");
4324
4325   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4326   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4327                             Cst, Cst, Cst, Cst);
4328
4329   if (VT.is256BitVector()) {
4330     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4331                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4332     Vec = Insert128BitVector(InsV, Vec,
4333                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4334   }
4335
4336   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4337 }
4338
4339 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4340 /// that point to V2 points to its first element.
4341 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4342   EVT VT = SVOp->getValueType(0);
4343   unsigned NumElems = VT.getVectorNumElements();
4344
4345   bool Changed = false;
4346   SmallVector<int, 8> MaskVec;
4347   SVOp->getMask(MaskVec);
4348
4349   for (unsigned i = 0; i != NumElems; ++i) {
4350     if (MaskVec[i] > (int)NumElems) {
4351       MaskVec[i] = NumElems;
4352       Changed = true;
4353     }
4354   }
4355   if (Changed)
4356     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4357                                 SVOp->getOperand(1), &MaskVec[0]);
4358   return SDValue(SVOp, 0);
4359 }
4360
4361 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4362 /// operation of specified width.
4363 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4364                        SDValue V2) {
4365   unsigned NumElems = VT.getVectorNumElements();
4366   SmallVector<int, 8> Mask;
4367   Mask.push_back(NumElems);
4368   for (unsigned i = 1; i != NumElems; ++i)
4369     Mask.push_back(i);
4370   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4371 }
4372
4373 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4374 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4375                           SDValue V2) {
4376   unsigned NumElems = VT.getVectorNumElements();
4377   SmallVector<int, 8> Mask;
4378   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4379     Mask.push_back(i);
4380     Mask.push_back(i + NumElems);
4381   }
4382   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4383 }
4384
4385 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4386 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4387                           SDValue V2) {
4388   unsigned NumElems = VT.getVectorNumElements();
4389   unsigned Half = NumElems/2;
4390   SmallVector<int, 8> Mask;
4391   for (unsigned i = 0; i != Half; ++i) {
4392     Mask.push_back(i + Half);
4393     Mask.push_back(i + NumElems + Half);
4394   }
4395   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4396 }
4397
4398 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4399 // a generic shuffle instruction because the target has no such instructions.
4400 // Generate shuffles which repeat i16 and i8 several times until they can be
4401 // represented by v4f32 and then be manipulated by target suported shuffles.
4402 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4403   EVT VT = V.getValueType();
4404   int NumElems = VT.getVectorNumElements();
4405   DebugLoc dl = V.getDebugLoc();
4406
4407   while (NumElems > 4) {
4408     if (EltNo < NumElems/2) {
4409       V = getUnpackl(DAG, dl, VT, V, V);
4410     } else {
4411       V = getUnpackh(DAG, dl, VT, V, V);
4412       EltNo -= NumElems/2;
4413     }
4414     NumElems >>= 1;
4415   }
4416   return V;
4417 }
4418
4419 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4420 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4421   EVT VT = V.getValueType();
4422   DebugLoc dl = V.getDebugLoc();
4423   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4424          && "Vector size not supported");
4425
4426   if (VT.getSizeInBits() == 128) {
4427     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4428     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4429     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4430                              &SplatMask[0]);
4431   } else {
4432     // To use VPERMILPS to splat scalars, the second half of indicies must
4433     // refer to the higher part, which is a duplication of the lower one,
4434     // because VPERMILPS can only handle in-lane permutations.
4435     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4436                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4437
4438     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4439     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4440                              &SplatMask[0]);
4441   }
4442
4443   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4444 }
4445
4446 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4447 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4448   EVT SrcVT = SV->getValueType(0);
4449   SDValue V1 = SV->getOperand(0);
4450   DebugLoc dl = SV->getDebugLoc();
4451
4452   int EltNo = SV->getSplatIndex();
4453   int NumElems = SrcVT.getVectorNumElements();
4454   unsigned Size = SrcVT.getSizeInBits();
4455
4456   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4457           "Unknown how to promote splat for type");
4458
4459   // Extract the 128-bit part containing the splat element and update
4460   // the splat element index when it refers to the higher register.
4461   if (Size == 256) {
4462     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4463     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4464     if (Idx > 0)
4465       EltNo -= NumElems/2;
4466   }
4467
4468   // All i16 and i8 vector types can't be used directly by a generic shuffle
4469   // instruction because the target has no such instruction. Generate shuffles
4470   // which repeat i16 and i8 several times until they fit in i32, and then can
4471   // be manipulated by target suported shuffles.
4472   EVT EltVT = SrcVT.getVectorElementType();
4473   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4474     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4475
4476   // Recreate the 256-bit vector and place the same 128-bit vector
4477   // into the low and high part. This is necessary because we want
4478   // to use VPERM* to shuffle the vectors
4479   if (Size == 256) {
4480     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4481                          DAG.getConstant(0, MVT::i32), DAG, dl);
4482     V1 = Insert128BitVector(InsV, V1,
4483                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4484   }
4485
4486   return getLegalSplat(DAG, V1, EltNo);
4487 }
4488
4489 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4490 /// vector of zero or undef vector.  This produces a shuffle where the low
4491 /// element of V2 is swizzled into the zero/undef vector, landing at element
4492 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4493 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4494                                            bool isZero, bool HasXMMInt,
4495                                            SelectionDAG &DAG) {
4496   EVT VT = V2.getValueType();
4497   SDValue V1 = isZero
4498     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4499   unsigned NumElems = VT.getVectorNumElements();
4500   SmallVector<int, 16> MaskVec;
4501   for (unsigned i = 0; i != NumElems; ++i)
4502     // If this is the insertion idx, put the low elt of V2 here.
4503     MaskVec.push_back(i == Idx ? NumElems : i);
4504   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4505 }
4506
4507 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4508 /// element of the result of the vector shuffle.
4509 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4510                                    unsigned Depth) {
4511   if (Depth == 6)
4512     return SDValue();  // Limit search depth.
4513
4514   SDValue V = SDValue(N, 0);
4515   EVT VT = V.getValueType();
4516   unsigned Opcode = V.getOpcode();
4517
4518   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4519   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4520     Index = SV->getMaskElt(Index);
4521
4522     if (Index < 0)
4523       return DAG.getUNDEF(VT.getVectorElementType());
4524
4525     int NumElems = VT.getVectorNumElements();
4526     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4527     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4528   }
4529
4530   // Recurse into target specific vector shuffles to find scalars.
4531   if (isTargetShuffle(Opcode)) {
4532     int NumElems = VT.getVectorNumElements();
4533     SmallVector<unsigned, 16> ShuffleMask;
4534     SDValue ImmN;
4535
4536     switch(Opcode) {
4537     case X86ISD::SHUFPS:
4538     case X86ISD::SHUFPD:
4539       ImmN = N->getOperand(N->getNumOperands()-1);
4540       DecodeSHUFPSMask(NumElems,
4541                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4542                        ShuffleMask);
4543       break;
4544     case X86ISD::PUNPCKHBW:
4545     case X86ISD::PUNPCKHWD:
4546     case X86ISD::PUNPCKHDQ:
4547     case X86ISD::PUNPCKHQDQ:
4548       DecodePUNPCKHMask(NumElems, ShuffleMask);
4549       break;
4550     case X86ISD::UNPCKHPS:
4551     case X86ISD::UNPCKHPD:
4552     case X86ISD::VUNPCKHPSY:
4553     case X86ISD::VUNPCKHPDY:
4554       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4555       break;
4556     case X86ISD::PUNPCKLBW:
4557     case X86ISD::PUNPCKLWD:
4558     case X86ISD::PUNPCKLDQ:
4559     case X86ISD::PUNPCKLQDQ:
4560       DecodePUNPCKLMask(VT, ShuffleMask);
4561       break;
4562     case X86ISD::UNPCKLPS:
4563     case X86ISD::UNPCKLPD:
4564     case X86ISD::VUNPCKLPSY:
4565     case X86ISD::VUNPCKLPDY:
4566       DecodeUNPCKLPMask(VT, ShuffleMask);
4567       break;
4568     case X86ISD::MOVHLPS:
4569       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4570       break;
4571     case X86ISD::MOVLHPS:
4572       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4573       break;
4574     case X86ISD::PSHUFD:
4575       ImmN = N->getOperand(N->getNumOperands()-1);
4576       DecodePSHUFMask(NumElems,
4577                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4578                       ShuffleMask);
4579       break;
4580     case X86ISD::PSHUFHW:
4581       ImmN = N->getOperand(N->getNumOperands()-1);
4582       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4583                         ShuffleMask);
4584       break;
4585     case X86ISD::PSHUFLW:
4586       ImmN = N->getOperand(N->getNumOperands()-1);
4587       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4588                         ShuffleMask);
4589       break;
4590     case X86ISD::MOVSS:
4591     case X86ISD::MOVSD: {
4592       // The index 0 always comes from the first element of the second source,
4593       // this is why MOVSS and MOVSD are used in the first place. The other
4594       // elements come from the other positions of the first source vector.
4595       unsigned OpNum = (Index == 0) ? 1 : 0;
4596       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4597                                  Depth+1);
4598     }
4599     case X86ISD::VPERMILPS:
4600       ImmN = N->getOperand(N->getNumOperands()-1);
4601       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4602                         ShuffleMask);
4603       break;
4604     case X86ISD::VPERMILPSY:
4605       ImmN = N->getOperand(N->getNumOperands()-1);
4606       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4607                         ShuffleMask);
4608       break;
4609     case X86ISD::VPERMILPD:
4610       ImmN = N->getOperand(N->getNumOperands()-1);
4611       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4612                         ShuffleMask);
4613       break;
4614     case X86ISD::VPERMILPDY:
4615       ImmN = N->getOperand(N->getNumOperands()-1);
4616       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4617                         ShuffleMask);
4618       break;
4619     case X86ISD::VPERM2F128:
4620       ImmN = N->getOperand(N->getNumOperands()-1);
4621       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4622                            ShuffleMask);
4623       break;
4624     case X86ISD::MOVDDUP:
4625     case X86ISD::MOVLHPD:
4626     case X86ISD::MOVLPD:
4627     case X86ISD::MOVLPS:
4628     case X86ISD::MOVSHDUP:
4629     case X86ISD::MOVSLDUP:
4630     case X86ISD::PALIGN:
4631       return SDValue(); // Not yet implemented.
4632     default:
4633       assert(0 && "unknown target shuffle node");
4634       return SDValue();
4635     }
4636
4637     Index = ShuffleMask[Index];
4638     if (Index < 0)
4639       return DAG.getUNDEF(VT.getVectorElementType());
4640
4641     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4642     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4643                                Depth+1);
4644   }
4645
4646   // Actual nodes that may contain scalar elements
4647   if (Opcode == ISD::BITCAST) {
4648     V = V.getOperand(0);
4649     EVT SrcVT = V.getValueType();
4650     unsigned NumElems = VT.getVectorNumElements();
4651
4652     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4653       return SDValue();
4654   }
4655
4656   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4657     return (Index == 0) ? V.getOperand(0)
4658                           : DAG.getUNDEF(VT.getVectorElementType());
4659
4660   if (V.getOpcode() == ISD::BUILD_VECTOR)
4661     return V.getOperand(Index);
4662
4663   return SDValue();
4664 }
4665
4666 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4667 /// shuffle operation which come from a consecutively from a zero. The
4668 /// search can start in two different directions, from left or right.
4669 static
4670 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4671                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4672   int i = 0;
4673
4674   while (i < NumElems) {
4675     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4676     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4677     if (!(Elt.getNode() &&
4678          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4679       break;
4680     ++i;
4681   }
4682
4683   return i;
4684 }
4685
4686 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4687 /// MaskE correspond consecutively to elements from one of the vector operands,
4688 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4689 static
4690 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4691                               int OpIdx, int NumElems, unsigned &OpNum) {
4692   bool SeenV1 = false;
4693   bool SeenV2 = false;
4694
4695   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4696     int Idx = SVOp->getMaskElt(i);
4697     // Ignore undef indicies
4698     if (Idx < 0)
4699       continue;
4700
4701     if (Idx < NumElems)
4702       SeenV1 = true;
4703     else
4704       SeenV2 = true;
4705
4706     // Only accept consecutive elements from the same vector
4707     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4708       return false;
4709   }
4710
4711   OpNum = SeenV1 ? 0 : 1;
4712   return true;
4713 }
4714
4715 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4716 /// logical left shift of a vector.
4717 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4718                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4719   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4720   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4721               false /* check zeros from right */, DAG);
4722   unsigned OpSrc;
4723
4724   if (!NumZeros)
4725     return false;
4726
4727   // Considering the elements in the mask that are not consecutive zeros,
4728   // check if they consecutively come from only one of the source vectors.
4729   //
4730   //               V1 = {X, A, B, C}     0
4731   //                         \  \  \    /
4732   //   vector_shuffle V1, V2 <1, 2, 3, X>
4733   //
4734   if (!isShuffleMaskConsecutive(SVOp,
4735             0,                   // Mask Start Index
4736             NumElems-NumZeros-1, // Mask End Index
4737             NumZeros,            // Where to start looking in the src vector
4738             NumElems,            // Number of elements in vector
4739             OpSrc))              // Which source operand ?
4740     return false;
4741
4742   isLeft = false;
4743   ShAmt = NumZeros;
4744   ShVal = SVOp->getOperand(OpSrc);
4745   return true;
4746 }
4747
4748 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4749 /// logical left shift of a vector.
4750 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4751                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4752   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4753   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4754               true /* check zeros from left */, DAG);
4755   unsigned OpSrc;
4756
4757   if (!NumZeros)
4758     return false;
4759
4760   // Considering the elements in the mask that are not consecutive zeros,
4761   // check if they consecutively come from only one of the source vectors.
4762   //
4763   //                           0    { A, B, X, X } = V2
4764   //                          / \    /  /
4765   //   vector_shuffle V1, V2 <X, X, 4, 5>
4766   //
4767   if (!isShuffleMaskConsecutive(SVOp,
4768             NumZeros,     // Mask Start Index
4769             NumElems-1,   // Mask End Index
4770             0,            // Where to start looking in the src vector
4771             NumElems,     // Number of elements in vector
4772             OpSrc))       // Which source operand ?
4773     return false;
4774
4775   isLeft = true;
4776   ShAmt = NumZeros;
4777   ShVal = SVOp->getOperand(OpSrc);
4778   return true;
4779 }
4780
4781 /// isVectorShift - Returns true if the shuffle can be implemented as a
4782 /// logical left or right shift of a vector.
4783 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4784                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4785   // Although the logic below support any bitwidth size, there are no
4786   // shift instructions which handle more than 128-bit vectors.
4787   if (SVOp->getValueType(0).getSizeInBits() > 128)
4788     return false;
4789
4790   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4791       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4792     return true;
4793
4794   return false;
4795 }
4796
4797 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4798 ///
4799 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4800                                        unsigned NumNonZero, unsigned NumZero,
4801                                        SelectionDAG &DAG,
4802                                        const TargetLowering &TLI) {
4803   if (NumNonZero > 8)
4804     return SDValue();
4805
4806   DebugLoc dl = Op.getDebugLoc();
4807   SDValue V(0, 0);
4808   bool First = true;
4809   for (unsigned i = 0; i < 16; ++i) {
4810     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4811     if (ThisIsNonZero && First) {
4812       if (NumZero)
4813         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4814       else
4815         V = DAG.getUNDEF(MVT::v8i16);
4816       First = false;
4817     }
4818
4819     if ((i & 1) != 0) {
4820       SDValue ThisElt(0, 0), LastElt(0, 0);
4821       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4822       if (LastIsNonZero) {
4823         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4824                               MVT::i16, Op.getOperand(i-1));
4825       }
4826       if (ThisIsNonZero) {
4827         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4828         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4829                               ThisElt, DAG.getConstant(8, MVT::i8));
4830         if (LastIsNonZero)
4831           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4832       } else
4833         ThisElt = LastElt;
4834
4835       if (ThisElt.getNode())
4836         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4837                         DAG.getIntPtrConstant(i/2));
4838     }
4839   }
4840
4841   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4842 }
4843
4844 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4845 ///
4846 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4847                                      unsigned NumNonZero, unsigned NumZero,
4848                                      SelectionDAG &DAG,
4849                                      const TargetLowering &TLI) {
4850   if (NumNonZero > 4)
4851     return SDValue();
4852
4853   DebugLoc dl = Op.getDebugLoc();
4854   SDValue V(0, 0);
4855   bool First = true;
4856   for (unsigned i = 0; i < 8; ++i) {
4857     bool isNonZero = (NonZeros & (1 << i)) != 0;
4858     if (isNonZero) {
4859       if (First) {
4860         if (NumZero)
4861           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4862         else
4863           V = DAG.getUNDEF(MVT::v8i16);
4864         First = false;
4865       }
4866       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4867                       MVT::v8i16, V, Op.getOperand(i),
4868                       DAG.getIntPtrConstant(i));
4869     }
4870   }
4871
4872   return V;
4873 }
4874
4875 /// getVShift - Return a vector logical shift node.
4876 ///
4877 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4878                          unsigned NumBits, SelectionDAG &DAG,
4879                          const TargetLowering &TLI, DebugLoc dl) {
4880   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4881   EVT ShVT = MVT::v2i64;
4882   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4883   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4884   return DAG.getNode(ISD::BITCAST, dl, VT,
4885                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4886                              DAG.getConstant(NumBits,
4887                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4888 }
4889
4890 SDValue
4891 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4892                                           SelectionDAG &DAG) const {
4893
4894   // Check if the scalar load can be widened into a vector load. And if
4895   // the address is "base + cst" see if the cst can be "absorbed" into
4896   // the shuffle mask.
4897   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4898     SDValue Ptr = LD->getBasePtr();
4899     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4900       return SDValue();
4901     EVT PVT = LD->getValueType(0);
4902     if (PVT != MVT::i32 && PVT != MVT::f32)
4903       return SDValue();
4904
4905     int FI = -1;
4906     int64_t Offset = 0;
4907     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4908       FI = FINode->getIndex();
4909       Offset = 0;
4910     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4911                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4912       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4913       Offset = Ptr.getConstantOperandVal(1);
4914       Ptr = Ptr.getOperand(0);
4915     } else {
4916       return SDValue();
4917     }
4918
4919     // FIXME: 256-bit vector instructions don't require a strict alignment,
4920     // improve this code to support it better.
4921     unsigned RequiredAlign = VT.getSizeInBits()/8;
4922     SDValue Chain = LD->getChain();
4923     // Make sure the stack object alignment is at least 16 or 32.
4924     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4925     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4926       if (MFI->isFixedObjectIndex(FI)) {
4927         // Can't change the alignment. FIXME: It's possible to compute
4928         // the exact stack offset and reference FI + adjust offset instead.
4929         // If someone *really* cares about this. That's the way to implement it.
4930         return SDValue();
4931       } else {
4932         MFI->setObjectAlignment(FI, RequiredAlign);
4933       }
4934     }
4935
4936     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4937     // Ptr + (Offset & ~15).
4938     if (Offset < 0)
4939       return SDValue();
4940     if ((Offset % RequiredAlign) & 3)
4941       return SDValue();
4942     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4943     if (StartOffset)
4944       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4945                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4946
4947     int EltNo = (Offset - StartOffset) >> 2;
4948     int NumElems = VT.getVectorNumElements();
4949
4950     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4951     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4952     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4953                              LD->getPointerInfo().getWithOffset(StartOffset),
4954                              false, false, 0);
4955
4956     // Canonicalize it to a v4i32 or v8i32 shuffle.
4957     SmallVector<int, 8> Mask;
4958     for (int i = 0; i < NumElems; ++i)
4959       Mask.push_back(EltNo);
4960
4961     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4962     return DAG.getNode(ISD::BITCAST, dl, NVT,
4963                        DAG.getVectorShuffle(CanonVT, dl, V1,
4964                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4965   }
4966
4967   return SDValue();
4968 }
4969
4970 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4971 /// vector of type 'VT', see if the elements can be replaced by a single large
4972 /// load which has the same value as a build_vector whose operands are 'elts'.
4973 ///
4974 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4975 ///
4976 /// FIXME: we'd also like to handle the case where the last elements are zero
4977 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4978 /// There's even a handy isZeroNode for that purpose.
4979 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4980                                         DebugLoc &DL, SelectionDAG &DAG) {
4981   EVT EltVT = VT.getVectorElementType();
4982   unsigned NumElems = Elts.size();
4983
4984   LoadSDNode *LDBase = NULL;
4985   unsigned LastLoadedElt = -1U;
4986
4987   // For each element in the initializer, see if we've found a load or an undef.
4988   // If we don't find an initial load element, or later load elements are
4989   // non-consecutive, bail out.
4990   for (unsigned i = 0; i < NumElems; ++i) {
4991     SDValue Elt = Elts[i];
4992
4993     if (!Elt.getNode() ||
4994         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4995       return SDValue();
4996     if (!LDBase) {
4997       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4998         return SDValue();
4999       LDBase = cast<LoadSDNode>(Elt.getNode());
5000       LastLoadedElt = i;
5001       continue;
5002     }
5003     if (Elt.getOpcode() == ISD::UNDEF)
5004       continue;
5005
5006     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5007     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5008       return SDValue();
5009     LastLoadedElt = i;
5010   }
5011
5012   // If we have found an entire vector of loads and undefs, then return a large
5013   // load of the entire vector width starting at the base pointer.  If we found
5014   // consecutive loads for the low half, generate a vzext_load node.
5015   if (LastLoadedElt == NumElems - 1) {
5016     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5017       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5018                          LDBase->getPointerInfo(),
5019                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5020     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5021                        LDBase->getPointerInfo(),
5022                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5023                        LDBase->getAlignment());
5024   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5025              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5026     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5027     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5028     SDValue ResNode =
5029         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5030                                 LDBase->getPointerInfo(),
5031                                 LDBase->getAlignment(),
5032                                 false/*isVolatile*/, true/*ReadMem*/,
5033                                 false/*WriteMem*/);
5034     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5035   }
5036   return SDValue();
5037 }
5038
5039 SDValue
5040 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5041   DebugLoc dl = Op.getDebugLoc();
5042
5043   EVT VT = Op.getValueType();
5044   EVT ExtVT = VT.getVectorElementType();
5045   unsigned NumElems = Op.getNumOperands();
5046
5047   // Vectors containing all zeros can be matched by pxor and xorps later
5048   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5049     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5050     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5051     if (Op.getValueType() == MVT::v4i32 ||
5052         Op.getValueType() == MVT::v8i32)
5053       return Op;
5054
5055     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5056   }
5057
5058   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5059   // vectors or broken into v4i32 operations on 256-bit vectors.
5060   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5061     if (Op.getValueType() == MVT::v4i32)
5062       return Op;
5063
5064     return getOnesVector(Op.getValueType(), DAG, dl);
5065   }
5066
5067   unsigned EVTBits = ExtVT.getSizeInBits();
5068
5069   unsigned NumZero  = 0;
5070   unsigned NumNonZero = 0;
5071   unsigned NonZeros = 0;
5072   bool IsAllConstants = true;
5073   SmallSet<SDValue, 8> Values;
5074   for (unsigned i = 0; i < NumElems; ++i) {
5075     SDValue Elt = Op.getOperand(i);
5076     if (Elt.getOpcode() == ISD::UNDEF)
5077       continue;
5078     Values.insert(Elt);
5079     if (Elt.getOpcode() != ISD::Constant &&
5080         Elt.getOpcode() != ISD::ConstantFP)
5081       IsAllConstants = false;
5082     if (X86::isZeroNode(Elt))
5083       NumZero++;
5084     else {
5085       NonZeros |= (1 << i);
5086       NumNonZero++;
5087     }
5088   }
5089
5090   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5091   if (NumNonZero == 0)
5092     return DAG.getUNDEF(VT);
5093
5094   // Special case for single non-zero, non-undef, element.
5095   if (NumNonZero == 1) {
5096     unsigned Idx = CountTrailingZeros_32(NonZeros);
5097     SDValue Item = Op.getOperand(Idx);
5098
5099     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5100     // the value are obviously zero, truncate the value to i32 and do the
5101     // insertion that way.  Only do this if the value is non-constant or if the
5102     // value is a constant being inserted into element 0.  It is cheaper to do
5103     // a constant pool load than it is to do a movd + shuffle.
5104     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5105         (!IsAllConstants || Idx == 0)) {
5106       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5107         // Handle SSE only.
5108         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5109         EVT VecVT = MVT::v4i32;
5110         unsigned VecElts = 4;
5111
5112         // Truncate the value (which may itself be a constant) to i32, and
5113         // convert it to a vector with movd (S2V+shuffle to zero extend).
5114         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5115         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5116         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5117                                            Subtarget->hasXMMInt(), DAG);
5118
5119         // Now we have our 32-bit value zero extended in the low element of
5120         // a vector.  If Idx != 0, swizzle it into place.
5121         if (Idx != 0) {
5122           SmallVector<int, 4> Mask;
5123           Mask.push_back(Idx);
5124           for (unsigned i = 1; i != VecElts; ++i)
5125             Mask.push_back(i);
5126           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5127                                       DAG.getUNDEF(Item.getValueType()),
5128                                       &Mask[0]);
5129         }
5130         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5131       }
5132     }
5133
5134     // If we have a constant or non-constant insertion into the low element of
5135     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5136     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5137     // depending on what the source datatype is.
5138     if (Idx == 0) {
5139       if (NumZero == 0) {
5140         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5141       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5142           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5143         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5144         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5145         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5146                                            DAG);
5147       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5148         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5149         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5150         EVT MiddleVT = MVT::v4i32;
5151         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5152         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5153                                            Subtarget->hasXMMInt(), DAG);
5154         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5155       }
5156     }
5157
5158     // Is it a vector logical left shift?
5159     if (NumElems == 2 && Idx == 1 &&
5160         X86::isZeroNode(Op.getOperand(0)) &&
5161         !X86::isZeroNode(Op.getOperand(1))) {
5162       unsigned NumBits = VT.getSizeInBits();
5163       return getVShift(true, VT,
5164                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5165                                    VT, Op.getOperand(1)),
5166                        NumBits/2, DAG, *this, dl);
5167     }
5168
5169     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5170       return SDValue();
5171
5172     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5173     // is a non-constant being inserted into an element other than the low one,
5174     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5175     // movd/movss) to move this into the low element, then shuffle it into
5176     // place.
5177     if (EVTBits == 32) {
5178       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5179
5180       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5181       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5182                                          Subtarget->hasXMMInt(), DAG);
5183       SmallVector<int, 8> MaskVec;
5184       for (unsigned i = 0; i < NumElems; i++)
5185         MaskVec.push_back(i == Idx ? 0 : 1);
5186       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5187     }
5188   }
5189
5190   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5191   if (Values.size() == 1) {
5192     if (EVTBits == 32) {
5193       // Instead of a shuffle like this:
5194       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5195       // Check if it's possible to issue this instead.
5196       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5197       unsigned Idx = CountTrailingZeros_32(NonZeros);
5198       SDValue Item = Op.getOperand(Idx);
5199       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5200         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5201     }
5202     return SDValue();
5203   }
5204
5205   // A vector full of immediates; various special cases are already
5206   // handled, so this is best done with a single constant-pool load.
5207   if (IsAllConstants)
5208     return SDValue();
5209
5210   // For AVX-length vectors, build the individual 128-bit pieces and use
5211   // shuffles to put them in place.
5212   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5213     SmallVector<SDValue, 32> V;
5214     for (unsigned i = 0; i < NumElems; ++i)
5215       V.push_back(Op.getOperand(i));
5216
5217     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5218
5219     // Build both the lower and upper subvector.
5220     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5221     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5222                                 NumElems/2);
5223
5224     // Recreate the wider vector with the lower and upper part.
5225     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5226                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5227     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5228                               DAG, dl);
5229   }
5230
5231   // Let legalizer expand 2-wide build_vectors.
5232   if (EVTBits == 64) {
5233     if (NumNonZero == 1) {
5234       // One half is zero or undef.
5235       unsigned Idx = CountTrailingZeros_32(NonZeros);
5236       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5237                                  Op.getOperand(Idx));
5238       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5239                                          Subtarget->hasXMMInt(), DAG);
5240     }
5241     return SDValue();
5242   }
5243
5244   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5245   if (EVTBits == 8 && NumElems == 16) {
5246     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5247                                         *this);
5248     if (V.getNode()) return V;
5249   }
5250
5251   if (EVTBits == 16 && NumElems == 8) {
5252     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5253                                       *this);
5254     if (V.getNode()) return V;
5255   }
5256
5257   // If element VT is == 32 bits, turn it into a number of shuffles.
5258   SmallVector<SDValue, 8> V;
5259   V.resize(NumElems);
5260   if (NumElems == 4 && NumZero > 0) {
5261     for (unsigned i = 0; i < 4; ++i) {
5262       bool isZero = !(NonZeros & (1 << i));
5263       if (isZero)
5264         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5265       else
5266         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5267     }
5268
5269     for (unsigned i = 0; i < 2; ++i) {
5270       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5271         default: break;
5272         case 0:
5273           V[i] = V[i*2];  // Must be a zero vector.
5274           break;
5275         case 1:
5276           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5277           break;
5278         case 2:
5279           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5280           break;
5281         case 3:
5282           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5283           break;
5284       }
5285     }
5286
5287     SmallVector<int, 8> MaskVec;
5288     bool Reverse = (NonZeros & 0x3) == 2;
5289     for (unsigned i = 0; i < 2; ++i)
5290       MaskVec.push_back(Reverse ? 1-i : i);
5291     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5292     for (unsigned i = 0; i < 2; ++i)
5293       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5294     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5295   }
5296
5297   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5298     // Check for a build vector of consecutive loads.
5299     for (unsigned i = 0; i < NumElems; ++i)
5300       V[i] = Op.getOperand(i);
5301
5302     // Check for elements which are consecutive loads.
5303     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5304     if (LD.getNode())
5305       return LD;
5306
5307     // For SSE 4.1, use insertps to put the high elements into the low element.
5308     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5309       SDValue Result;
5310       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5311         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5312       else
5313         Result = DAG.getUNDEF(VT);
5314
5315       for (unsigned i = 1; i < NumElems; ++i) {
5316         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5317         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5318                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5319       }
5320       return Result;
5321     }
5322
5323     // Otherwise, expand into a number of unpckl*, start by extending each of
5324     // our (non-undef) elements to the full vector width with the element in the
5325     // bottom slot of the vector (which generates no code for SSE).
5326     for (unsigned i = 0; i < NumElems; ++i) {
5327       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5328         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5329       else
5330         V[i] = DAG.getUNDEF(VT);
5331     }
5332
5333     // Next, we iteratively mix elements, e.g. for v4f32:
5334     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5335     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5336     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5337     unsigned EltStride = NumElems >> 1;
5338     while (EltStride != 0) {
5339       for (unsigned i = 0; i < EltStride; ++i) {
5340         // If V[i+EltStride] is undef and this is the first round of mixing,
5341         // then it is safe to just drop this shuffle: V[i] is already in the
5342         // right place, the one element (since it's the first round) being
5343         // inserted as undef can be dropped.  This isn't safe for successive
5344         // rounds because they will permute elements within both vectors.
5345         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5346             EltStride == NumElems/2)
5347           continue;
5348
5349         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5350       }
5351       EltStride >>= 1;
5352     }
5353     return V[0];
5354   }
5355   return SDValue();
5356 }
5357
5358 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5359 // them in a MMX register.  This is better than doing a stack convert.
5360 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5361   DebugLoc dl = Op.getDebugLoc();
5362   EVT ResVT = Op.getValueType();
5363
5364   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5365          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5366   int Mask[2];
5367   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5368   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5369   InVec = Op.getOperand(1);
5370   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5371     unsigned NumElts = ResVT.getVectorNumElements();
5372     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5373     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5374                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5375   } else {
5376     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5377     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5378     Mask[0] = 0; Mask[1] = 2;
5379     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5380   }
5381   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5382 }
5383
5384 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5385 // to create 256-bit vectors from two other 128-bit ones.
5386 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5387   DebugLoc dl = Op.getDebugLoc();
5388   EVT ResVT = Op.getValueType();
5389
5390   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5391
5392   SDValue V1 = Op.getOperand(0);
5393   SDValue V2 = Op.getOperand(1);
5394   unsigned NumElems = ResVT.getVectorNumElements();
5395
5396   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5397                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5398   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5399                             DAG, dl);
5400 }
5401
5402 SDValue
5403 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5404   EVT ResVT = Op.getValueType();
5405
5406   assert(Op.getNumOperands() == 2);
5407   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5408          "Unsupported CONCAT_VECTORS for value type");
5409
5410   // We support concatenate two MMX registers and place them in a MMX register.
5411   // This is better than doing a stack convert.
5412   if (ResVT.is128BitVector())
5413     return LowerMMXCONCAT_VECTORS(Op, DAG);
5414
5415   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5416   // from two other 128-bit ones.
5417   return LowerAVXCONCAT_VECTORS(Op, DAG);
5418 }
5419
5420 // v8i16 shuffles - Prefer shuffles in the following order:
5421 // 1. [all]   pshuflw, pshufhw, optional move
5422 // 2. [ssse3] 1 x pshufb
5423 // 3. [ssse3] 2 x pshufb + 1 x por
5424 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5425 SDValue
5426 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5427                                             SelectionDAG &DAG) const {
5428   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5429   SDValue V1 = SVOp->getOperand(0);
5430   SDValue V2 = SVOp->getOperand(1);
5431   DebugLoc dl = SVOp->getDebugLoc();
5432   SmallVector<int, 8> MaskVals;
5433
5434   // Determine if more than 1 of the words in each of the low and high quadwords
5435   // of the result come from the same quadword of one of the two inputs.  Undef
5436   // mask values count as coming from any quadword, for better codegen.
5437   SmallVector<unsigned, 4> LoQuad(4);
5438   SmallVector<unsigned, 4> HiQuad(4);
5439   BitVector InputQuads(4);
5440   for (unsigned i = 0; i < 8; ++i) {
5441     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5442     int EltIdx = SVOp->getMaskElt(i);
5443     MaskVals.push_back(EltIdx);
5444     if (EltIdx < 0) {
5445       ++Quad[0];
5446       ++Quad[1];
5447       ++Quad[2];
5448       ++Quad[3];
5449       continue;
5450     }
5451     ++Quad[EltIdx / 4];
5452     InputQuads.set(EltIdx / 4);
5453   }
5454
5455   int BestLoQuad = -1;
5456   unsigned MaxQuad = 1;
5457   for (unsigned i = 0; i < 4; ++i) {
5458     if (LoQuad[i] > MaxQuad) {
5459       BestLoQuad = i;
5460       MaxQuad = LoQuad[i];
5461     }
5462   }
5463
5464   int BestHiQuad = -1;
5465   MaxQuad = 1;
5466   for (unsigned i = 0; i < 4; ++i) {
5467     if (HiQuad[i] > MaxQuad) {
5468       BestHiQuad = i;
5469       MaxQuad = HiQuad[i];
5470     }
5471   }
5472
5473   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5474   // of the two input vectors, shuffle them into one input vector so only a
5475   // single pshufb instruction is necessary. If There are more than 2 input
5476   // quads, disable the next transformation since it does not help SSSE3.
5477   bool V1Used = InputQuads[0] || InputQuads[1];
5478   bool V2Used = InputQuads[2] || InputQuads[3];
5479   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5480     if (InputQuads.count() == 2 && V1Used && V2Used) {
5481       BestLoQuad = InputQuads.find_first();
5482       BestHiQuad = InputQuads.find_next(BestLoQuad);
5483     }
5484     if (InputQuads.count() > 2) {
5485       BestLoQuad = -1;
5486       BestHiQuad = -1;
5487     }
5488   }
5489
5490   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5491   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5492   // words from all 4 input quadwords.
5493   SDValue NewV;
5494   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5495     SmallVector<int, 8> MaskV;
5496     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5497     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5498     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5499                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5500                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5501     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5502
5503     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5504     // source words for the shuffle, to aid later transformations.
5505     bool AllWordsInNewV = true;
5506     bool InOrder[2] = { true, true };
5507     for (unsigned i = 0; i != 8; ++i) {
5508       int idx = MaskVals[i];
5509       if (idx != (int)i)
5510         InOrder[i/4] = false;
5511       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5512         continue;
5513       AllWordsInNewV = false;
5514       break;
5515     }
5516
5517     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5518     if (AllWordsInNewV) {
5519       for (int i = 0; i != 8; ++i) {
5520         int idx = MaskVals[i];
5521         if (idx < 0)
5522           continue;
5523         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5524         if ((idx != i) && idx < 4)
5525           pshufhw = false;
5526         if ((idx != i) && idx > 3)
5527           pshuflw = false;
5528       }
5529       V1 = NewV;
5530       V2Used = false;
5531       BestLoQuad = 0;
5532       BestHiQuad = 1;
5533     }
5534
5535     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5536     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5537     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5538       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5539       unsigned TargetMask = 0;
5540       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5541                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5542       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5543                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5544       V1 = NewV.getOperand(0);
5545       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5546     }
5547   }
5548
5549   // If we have SSSE3, and all words of the result are from 1 input vector,
5550   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5551   // is present, fall back to case 4.
5552   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5553     SmallVector<SDValue,16> pshufbMask;
5554
5555     // If we have elements from both input vectors, set the high bit of the
5556     // shuffle mask element to zero out elements that come from V2 in the V1
5557     // mask, and elements that come from V1 in the V2 mask, so that the two
5558     // results can be OR'd together.
5559     bool TwoInputs = V1Used && V2Used;
5560     for (unsigned i = 0; i != 8; ++i) {
5561       int EltIdx = MaskVals[i] * 2;
5562       if (TwoInputs && (EltIdx >= 16)) {
5563         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5564         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5565         continue;
5566       }
5567       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5568       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5569     }
5570     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5571     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5572                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5573                                  MVT::v16i8, &pshufbMask[0], 16));
5574     if (!TwoInputs)
5575       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5576
5577     // Calculate the shuffle mask for the second input, shuffle it, and
5578     // OR it with the first shuffled input.
5579     pshufbMask.clear();
5580     for (unsigned i = 0; i != 8; ++i) {
5581       int EltIdx = MaskVals[i] * 2;
5582       if (EltIdx < 16) {
5583         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5584         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5585         continue;
5586       }
5587       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5588       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5589     }
5590     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5591     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5592                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5593                                  MVT::v16i8, &pshufbMask[0], 16));
5594     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5595     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5596   }
5597
5598   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5599   // and update MaskVals with new element order.
5600   BitVector InOrder(8);
5601   if (BestLoQuad >= 0) {
5602     SmallVector<int, 8> MaskV;
5603     for (int i = 0; i != 4; ++i) {
5604       int idx = MaskVals[i];
5605       if (idx < 0) {
5606         MaskV.push_back(-1);
5607         InOrder.set(i);
5608       } else if ((idx / 4) == BestLoQuad) {
5609         MaskV.push_back(idx & 3);
5610         InOrder.set(i);
5611       } else {
5612         MaskV.push_back(-1);
5613       }
5614     }
5615     for (unsigned i = 4; i != 8; ++i)
5616       MaskV.push_back(i);
5617     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5618                                 &MaskV[0]);
5619
5620     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5621         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5622       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5623                                NewV.getOperand(0),
5624                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5625                                DAG);
5626   }
5627
5628   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5629   // and update MaskVals with the new element order.
5630   if (BestHiQuad >= 0) {
5631     SmallVector<int, 8> MaskV;
5632     for (unsigned i = 0; i != 4; ++i)
5633       MaskV.push_back(i);
5634     for (unsigned i = 4; i != 8; ++i) {
5635       int idx = MaskVals[i];
5636       if (idx < 0) {
5637         MaskV.push_back(-1);
5638         InOrder.set(i);
5639       } else if ((idx / 4) == BestHiQuad) {
5640         MaskV.push_back((idx & 3) + 4);
5641         InOrder.set(i);
5642       } else {
5643         MaskV.push_back(-1);
5644       }
5645     }
5646     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5647                                 &MaskV[0]);
5648
5649     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5650         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5651       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5652                               NewV.getOperand(0),
5653                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5654                               DAG);
5655   }
5656
5657   // In case BestHi & BestLo were both -1, which means each quadword has a word
5658   // from each of the four input quadwords, calculate the InOrder bitvector now
5659   // before falling through to the insert/extract cleanup.
5660   if (BestLoQuad == -1 && BestHiQuad == -1) {
5661     NewV = V1;
5662     for (int i = 0; i != 8; ++i)
5663       if (MaskVals[i] < 0 || MaskVals[i] == i)
5664         InOrder.set(i);
5665   }
5666
5667   // The other elements are put in the right place using pextrw and pinsrw.
5668   for (unsigned i = 0; i != 8; ++i) {
5669     if (InOrder[i])
5670       continue;
5671     int EltIdx = MaskVals[i];
5672     if (EltIdx < 0)
5673       continue;
5674     SDValue ExtOp = (EltIdx < 8)
5675     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5676                   DAG.getIntPtrConstant(EltIdx))
5677     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5678                   DAG.getIntPtrConstant(EltIdx - 8));
5679     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5680                        DAG.getIntPtrConstant(i));
5681   }
5682   return NewV;
5683 }
5684
5685 // v16i8 shuffles - Prefer shuffles in the following order:
5686 // 1. [ssse3] 1 x pshufb
5687 // 2. [ssse3] 2 x pshufb + 1 x por
5688 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5689 static
5690 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5691                                  SelectionDAG &DAG,
5692                                  const X86TargetLowering &TLI) {
5693   SDValue V1 = SVOp->getOperand(0);
5694   SDValue V2 = SVOp->getOperand(1);
5695   DebugLoc dl = SVOp->getDebugLoc();
5696   SmallVector<int, 16> MaskVals;
5697   SVOp->getMask(MaskVals);
5698
5699   // If we have SSSE3, case 1 is generated when all result bytes come from
5700   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5701   // present, fall back to case 3.
5702   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5703   bool V1Only = true;
5704   bool V2Only = true;
5705   for (unsigned i = 0; i < 16; ++i) {
5706     int EltIdx = MaskVals[i];
5707     if (EltIdx < 0)
5708       continue;
5709     if (EltIdx < 16)
5710       V2Only = false;
5711     else
5712       V1Only = false;
5713   }
5714
5715   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5716   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5717     SmallVector<SDValue,16> pshufbMask;
5718
5719     // If all result elements are from one input vector, then only translate
5720     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5721     //
5722     // Otherwise, we have elements from both input vectors, and must zero out
5723     // elements that come from V2 in the first mask, and V1 in the second mask
5724     // so that we can OR them together.
5725     bool TwoInputs = !(V1Only || V2Only);
5726     for (unsigned i = 0; i != 16; ++i) {
5727       int EltIdx = MaskVals[i];
5728       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5729         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5730         continue;
5731       }
5732       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5733     }
5734     // If all the elements are from V2, assign it to V1 and return after
5735     // building the first pshufb.
5736     if (V2Only)
5737       V1 = V2;
5738     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5739                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5740                                  MVT::v16i8, &pshufbMask[0], 16));
5741     if (!TwoInputs)
5742       return V1;
5743
5744     // Calculate the shuffle mask for the second input, shuffle it, and
5745     // OR it with the first shuffled input.
5746     pshufbMask.clear();
5747     for (unsigned i = 0; i != 16; ++i) {
5748       int EltIdx = MaskVals[i];
5749       if (EltIdx < 16) {
5750         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5751         continue;
5752       }
5753       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5754     }
5755     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5756                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5757                                  MVT::v16i8, &pshufbMask[0], 16));
5758     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5759   }
5760
5761   // No SSSE3 - Calculate in place words and then fix all out of place words
5762   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5763   // the 16 different words that comprise the two doublequadword input vectors.
5764   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5765   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5766   SDValue NewV = V2Only ? V2 : V1;
5767   for (int i = 0; i != 8; ++i) {
5768     int Elt0 = MaskVals[i*2];
5769     int Elt1 = MaskVals[i*2+1];
5770
5771     // This word of the result is all undef, skip it.
5772     if (Elt0 < 0 && Elt1 < 0)
5773       continue;
5774
5775     // This word of the result is already in the correct place, skip it.
5776     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5777       continue;
5778     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5779       continue;
5780
5781     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5782     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5783     SDValue InsElt;
5784
5785     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5786     // using a single extract together, load it and store it.
5787     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5788       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5789                            DAG.getIntPtrConstant(Elt1 / 2));
5790       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5791                         DAG.getIntPtrConstant(i));
5792       continue;
5793     }
5794
5795     // If Elt1 is defined, extract it from the appropriate source.  If the
5796     // source byte is not also odd, shift the extracted word left 8 bits
5797     // otherwise clear the bottom 8 bits if we need to do an or.
5798     if (Elt1 >= 0) {
5799       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5800                            DAG.getIntPtrConstant(Elt1 / 2));
5801       if ((Elt1 & 1) == 0)
5802         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5803                              DAG.getConstant(8,
5804                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5805       else if (Elt0 >= 0)
5806         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5807                              DAG.getConstant(0xFF00, MVT::i16));
5808     }
5809     // If Elt0 is defined, extract it from the appropriate source.  If the
5810     // source byte is not also even, shift the extracted word right 8 bits. If
5811     // Elt1 was also defined, OR the extracted values together before
5812     // inserting them in the result.
5813     if (Elt0 >= 0) {
5814       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5815                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5816       if ((Elt0 & 1) != 0)
5817         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5818                               DAG.getConstant(8,
5819                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5820       else if (Elt1 >= 0)
5821         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5822                              DAG.getConstant(0x00FF, MVT::i16));
5823       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5824                          : InsElt0;
5825     }
5826     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5827                        DAG.getIntPtrConstant(i));
5828   }
5829   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5830 }
5831
5832 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5833 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5834 /// done when every pair / quad of shuffle mask elements point to elements in
5835 /// the right sequence. e.g.
5836 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5837 static
5838 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5839                                  SelectionDAG &DAG, DebugLoc dl) {
5840   EVT VT = SVOp->getValueType(0);
5841   SDValue V1 = SVOp->getOperand(0);
5842   SDValue V2 = SVOp->getOperand(1);
5843   unsigned NumElems = VT.getVectorNumElements();
5844   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5845   EVT NewVT;
5846   switch (VT.getSimpleVT().SimpleTy) {
5847   default: assert(false && "Unexpected!");
5848   case MVT::v4f32: NewVT = MVT::v2f64; break;
5849   case MVT::v4i32: NewVT = MVT::v2i64; break;
5850   case MVT::v8i16: NewVT = MVT::v4i32; break;
5851   case MVT::v16i8: NewVT = MVT::v4i32; break;
5852   }
5853
5854   int Scale = NumElems / NewWidth;
5855   SmallVector<int, 8> MaskVec;
5856   for (unsigned i = 0; i < NumElems; i += Scale) {
5857     int StartIdx = -1;
5858     for (int j = 0; j < Scale; ++j) {
5859       int EltIdx = SVOp->getMaskElt(i+j);
5860       if (EltIdx < 0)
5861         continue;
5862       if (StartIdx == -1)
5863         StartIdx = EltIdx - (EltIdx % Scale);
5864       if (EltIdx != StartIdx + j)
5865         return SDValue();
5866     }
5867     if (StartIdx == -1)
5868       MaskVec.push_back(-1);
5869     else
5870       MaskVec.push_back(StartIdx / Scale);
5871   }
5872
5873   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5874   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5875   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5876 }
5877
5878 /// getVZextMovL - Return a zero-extending vector move low node.
5879 ///
5880 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5881                             SDValue SrcOp, SelectionDAG &DAG,
5882                             const X86Subtarget *Subtarget, DebugLoc dl) {
5883   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5884     LoadSDNode *LD = NULL;
5885     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5886       LD = dyn_cast<LoadSDNode>(SrcOp);
5887     if (!LD) {
5888       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5889       // instead.
5890       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5891       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5892           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5893           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5894           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5895         // PR2108
5896         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5897         return DAG.getNode(ISD::BITCAST, dl, VT,
5898                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5899                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5900                                                    OpVT,
5901                                                    SrcOp.getOperand(0)
5902                                                           .getOperand(0))));
5903       }
5904     }
5905   }
5906
5907   return DAG.getNode(ISD::BITCAST, dl, VT,
5908                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5909                                  DAG.getNode(ISD::BITCAST, dl,
5910                                              OpVT, SrcOp)));
5911 }
5912
5913 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5914 /// shuffle node referes to only one lane in the sources.
5915 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5916   EVT VT = SVOp->getValueType(0);
5917   int NumElems = VT.getVectorNumElements();
5918   int HalfSize = NumElems/2;
5919   SmallVector<int, 16> M;
5920   SVOp->getMask(M);
5921   bool MatchA = false, MatchB = false;
5922
5923   for (int l = 0; l < NumElems*2; l += HalfSize) {
5924     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5925       MatchA = true;
5926       break;
5927     }
5928   }
5929
5930   for (int l = 0; l < NumElems*2; l += HalfSize) {
5931     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5932       MatchB = true;
5933       break;
5934     }
5935   }
5936
5937   return MatchA && MatchB;
5938 }
5939
5940 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5941 /// which could not be matched by any known target speficic shuffle
5942 static SDValue
5943 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5944   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5945     // If each half of a vector shuffle node referes to only one lane in the
5946     // source vectors, extract each used 128-bit lane and shuffle them using
5947     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5948     // the work to the legalizer.
5949     DebugLoc dl = SVOp->getDebugLoc();
5950     EVT VT = SVOp->getValueType(0);
5951     int NumElems = VT.getVectorNumElements();
5952     int HalfSize = NumElems/2;
5953
5954     // Extract the reference for each half
5955     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5956     int FstVecOpNum = 0, SndVecOpNum = 0;
5957     for (int i = 0; i < HalfSize; ++i) {
5958       int Elt = SVOp->getMaskElt(i);
5959       if (SVOp->getMaskElt(i) < 0)
5960         continue;
5961       FstVecOpNum = Elt/NumElems;
5962       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5963       break;
5964     }
5965     for (int i = HalfSize; i < NumElems; ++i) {
5966       int Elt = SVOp->getMaskElt(i);
5967       if (SVOp->getMaskElt(i) < 0)
5968         continue;
5969       SndVecOpNum = Elt/NumElems;
5970       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5971       break;
5972     }
5973
5974     // Extract the subvectors
5975     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5976                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5977     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5978                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5979
5980     // Generate 128-bit shuffles
5981     SmallVector<int, 16> MaskV1, MaskV2;
5982     for (int i = 0; i < HalfSize; ++i) {
5983       int Elt = SVOp->getMaskElt(i);
5984       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5985     }
5986     for (int i = HalfSize; i < NumElems; ++i) {
5987       int Elt = SVOp->getMaskElt(i);
5988       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5989     }
5990
5991     EVT NVT = V1.getValueType();
5992     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5993     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5994
5995     // Concatenate the result back
5996     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5997                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5998     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5999                               DAG, dl);
6000   }
6001
6002   return SDValue();
6003 }
6004
6005 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6006 /// 4 elements, and match them with several different shuffle types.
6007 static SDValue
6008 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6009   SDValue V1 = SVOp->getOperand(0);
6010   SDValue V2 = SVOp->getOperand(1);
6011   DebugLoc dl = SVOp->getDebugLoc();
6012   EVT VT = SVOp->getValueType(0);
6013
6014   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6015
6016   SmallVector<std::pair<int, int>, 8> Locs;
6017   Locs.resize(4);
6018   SmallVector<int, 8> Mask1(4U, -1);
6019   SmallVector<int, 8> PermMask;
6020   SVOp->getMask(PermMask);
6021
6022   unsigned NumHi = 0;
6023   unsigned NumLo = 0;
6024   for (unsigned i = 0; i != 4; ++i) {
6025     int Idx = PermMask[i];
6026     if (Idx < 0) {
6027       Locs[i] = std::make_pair(-1, -1);
6028     } else {
6029       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6030       if (Idx < 4) {
6031         Locs[i] = std::make_pair(0, NumLo);
6032         Mask1[NumLo] = Idx;
6033         NumLo++;
6034       } else {
6035         Locs[i] = std::make_pair(1, NumHi);
6036         if (2+NumHi < 4)
6037           Mask1[2+NumHi] = Idx;
6038         NumHi++;
6039       }
6040     }
6041   }
6042
6043   if (NumLo <= 2 && NumHi <= 2) {
6044     // If no more than two elements come from either vector. This can be
6045     // implemented with two shuffles. First shuffle gather the elements.
6046     // The second shuffle, which takes the first shuffle as both of its
6047     // vector operands, put the elements into the right order.
6048     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6049
6050     SmallVector<int, 8> Mask2(4U, -1);
6051
6052     for (unsigned i = 0; i != 4; ++i) {
6053       if (Locs[i].first == -1)
6054         continue;
6055       else {
6056         unsigned Idx = (i < 2) ? 0 : 4;
6057         Idx += Locs[i].first * 2 + Locs[i].second;
6058         Mask2[i] = Idx;
6059       }
6060     }
6061
6062     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6063   } else if (NumLo == 3 || NumHi == 3) {
6064     // Otherwise, we must have three elements from one vector, call it X, and
6065     // one element from the other, call it Y.  First, use a shufps to build an
6066     // intermediate vector with the one element from Y and the element from X
6067     // that will be in the same half in the final destination (the indexes don't
6068     // matter). Then, use a shufps to build the final vector, taking the half
6069     // containing the element from Y from the intermediate, and the other half
6070     // from X.
6071     if (NumHi == 3) {
6072       // Normalize it so the 3 elements come from V1.
6073       CommuteVectorShuffleMask(PermMask, VT);
6074       std::swap(V1, V2);
6075     }
6076
6077     // Find the element from V2.
6078     unsigned HiIndex;
6079     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6080       int Val = PermMask[HiIndex];
6081       if (Val < 0)
6082         continue;
6083       if (Val >= 4)
6084         break;
6085     }
6086
6087     Mask1[0] = PermMask[HiIndex];
6088     Mask1[1] = -1;
6089     Mask1[2] = PermMask[HiIndex^1];
6090     Mask1[3] = -1;
6091     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6092
6093     if (HiIndex >= 2) {
6094       Mask1[0] = PermMask[0];
6095       Mask1[1] = PermMask[1];
6096       Mask1[2] = HiIndex & 1 ? 6 : 4;
6097       Mask1[3] = HiIndex & 1 ? 4 : 6;
6098       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6099     } else {
6100       Mask1[0] = HiIndex & 1 ? 2 : 0;
6101       Mask1[1] = HiIndex & 1 ? 0 : 2;
6102       Mask1[2] = PermMask[2];
6103       Mask1[3] = PermMask[3];
6104       if (Mask1[2] >= 0)
6105         Mask1[2] += 4;
6106       if (Mask1[3] >= 0)
6107         Mask1[3] += 4;
6108       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6109     }
6110   }
6111
6112   // Break it into (shuffle shuffle_hi, shuffle_lo).
6113   Locs.clear();
6114   Locs.resize(4);
6115   SmallVector<int,8> LoMask(4U, -1);
6116   SmallVector<int,8> HiMask(4U, -1);
6117
6118   SmallVector<int,8> *MaskPtr = &LoMask;
6119   unsigned MaskIdx = 0;
6120   unsigned LoIdx = 0;
6121   unsigned HiIdx = 2;
6122   for (unsigned i = 0; i != 4; ++i) {
6123     if (i == 2) {
6124       MaskPtr = &HiMask;
6125       MaskIdx = 1;
6126       LoIdx = 0;
6127       HiIdx = 2;
6128     }
6129     int Idx = PermMask[i];
6130     if (Idx < 0) {
6131       Locs[i] = std::make_pair(-1, -1);
6132     } else if (Idx < 4) {
6133       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6134       (*MaskPtr)[LoIdx] = Idx;
6135       LoIdx++;
6136     } else {
6137       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6138       (*MaskPtr)[HiIdx] = Idx;
6139       HiIdx++;
6140     }
6141   }
6142
6143   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6144   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6145   SmallVector<int, 8> MaskOps;
6146   for (unsigned i = 0; i != 4; ++i) {
6147     if (Locs[i].first == -1) {
6148       MaskOps.push_back(-1);
6149     } else {
6150       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6151       MaskOps.push_back(Idx);
6152     }
6153   }
6154   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6155 }
6156
6157 static bool MayFoldVectorLoad(SDValue V) {
6158   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6159     V = V.getOperand(0);
6160   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6161     V = V.getOperand(0);
6162   if (MayFoldLoad(V))
6163     return true;
6164   return false;
6165 }
6166
6167 // FIXME: the version above should always be used. Since there's
6168 // a bug where several vector shuffles can't be folded because the
6169 // DAG is not updated during lowering and a node claims to have two
6170 // uses while it only has one, use this version, and let isel match
6171 // another instruction if the load really happens to have more than
6172 // one use. Remove this version after this bug get fixed.
6173 // rdar://8434668, PR8156
6174 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6175   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6176     V = V.getOperand(0);
6177   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6178     V = V.getOperand(0);
6179   if (ISD::isNormalLoad(V.getNode()))
6180     return true;
6181   return false;
6182 }
6183
6184 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6185 /// a vector extract, and if both can be later optimized into a single load.
6186 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6187 /// here because otherwise a target specific shuffle node is going to be
6188 /// emitted for this shuffle, and the optimization not done.
6189 /// FIXME: This is probably not the best approach, but fix the problem
6190 /// until the right path is decided.
6191 static
6192 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6193                                          const TargetLowering &TLI) {
6194   EVT VT = V.getValueType();
6195   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6196
6197   // Be sure that the vector shuffle is present in a pattern like this:
6198   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6199   if (!V.hasOneUse())
6200     return false;
6201
6202   SDNode *N = *V.getNode()->use_begin();
6203   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6204     return false;
6205
6206   SDValue EltNo = N->getOperand(1);
6207   if (!isa<ConstantSDNode>(EltNo))
6208     return false;
6209
6210   // If the bit convert changed the number of elements, it is unsafe
6211   // to examine the mask.
6212   bool HasShuffleIntoBitcast = false;
6213   if (V.getOpcode() == ISD::BITCAST) {
6214     EVT SrcVT = V.getOperand(0).getValueType();
6215     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6216       return false;
6217     V = V.getOperand(0);
6218     HasShuffleIntoBitcast = true;
6219   }
6220
6221   // Select the input vector, guarding against out of range extract vector.
6222   unsigned NumElems = VT.getVectorNumElements();
6223   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6224   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6225   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6226
6227   // Skip one more bit_convert if necessary
6228   if (V.getOpcode() == ISD::BITCAST)
6229     V = V.getOperand(0);
6230
6231   if (ISD::isNormalLoad(V.getNode())) {
6232     // Is the original load suitable?
6233     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6234
6235     // FIXME: avoid the multi-use bug that is preventing lots of
6236     // of foldings to be detected, this is still wrong of course, but
6237     // give the temporary desired behavior, and if it happens that
6238     // the load has real more uses, during isel it will not fold, and
6239     // will generate poor code.
6240     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6241       return false;
6242
6243     if (!HasShuffleIntoBitcast)
6244       return true;
6245
6246     // If there's a bitcast before the shuffle, check if the load type and
6247     // alignment is valid.
6248     unsigned Align = LN0->getAlignment();
6249     unsigned NewAlign =
6250       TLI.getTargetData()->getABITypeAlignment(
6251                                     VT.getTypeForEVT(*DAG.getContext()));
6252
6253     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6254       return false;
6255   }
6256
6257   return true;
6258 }
6259
6260 static
6261 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6262   EVT VT = Op.getValueType();
6263
6264   // Canonizalize to v2f64.
6265   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6266   return DAG.getNode(ISD::BITCAST, dl, VT,
6267                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6268                                           V1, DAG));
6269 }
6270
6271 static
6272 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6273                         bool HasXMMInt) {
6274   SDValue V1 = Op.getOperand(0);
6275   SDValue V2 = Op.getOperand(1);
6276   EVT VT = Op.getValueType();
6277
6278   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6279
6280   if (HasXMMInt && VT == MVT::v2f64)
6281     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6282
6283   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6284   return DAG.getNode(ISD::BITCAST, dl, VT,
6285                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6286                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6287                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6288 }
6289
6290 static
6291 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6292   SDValue V1 = Op.getOperand(0);
6293   SDValue V2 = Op.getOperand(1);
6294   EVT VT = Op.getValueType();
6295
6296   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6297          "unsupported shuffle type");
6298
6299   if (V2.getOpcode() == ISD::UNDEF)
6300     V2 = V1;
6301
6302   // v4i32 or v4f32
6303   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6304 }
6305
6306 static inline unsigned getSHUFPOpcode(EVT VT) {
6307   switch(VT.getSimpleVT().SimpleTy) {
6308   case MVT::v8i32: // Use fp unit for int unpack.
6309   case MVT::v8f32:
6310   case MVT::v4i32: // Use fp unit for int unpack.
6311   case MVT::v4f32: return X86ISD::SHUFPS;
6312   case MVT::v4i64: // Use fp unit for int unpack.
6313   case MVT::v4f64:
6314   case MVT::v2i64: // Use fp unit for int unpack.
6315   case MVT::v2f64: return X86ISD::SHUFPD;
6316   default:
6317     llvm_unreachable("Unknown type for shufp*");
6318   }
6319   return 0;
6320 }
6321
6322 static
6323 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6324   SDValue V1 = Op.getOperand(0);
6325   SDValue V2 = Op.getOperand(1);
6326   EVT VT = Op.getValueType();
6327   unsigned NumElems = VT.getVectorNumElements();
6328
6329   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6330   // operand of these instructions is only memory, so check if there's a
6331   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6332   // same masks.
6333   bool CanFoldLoad = false;
6334
6335   // Trivial case, when V2 comes from a load.
6336   if (MayFoldVectorLoad(V2))
6337     CanFoldLoad = true;
6338
6339   // When V1 is a load, it can be folded later into a store in isel, example:
6340   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6341   //    turns into:
6342   //  (MOVLPSmr addr:$src1, VR128:$src2)
6343   // So, recognize this potential and also use MOVLPS or MOVLPD
6344   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6345     CanFoldLoad = true;
6346
6347   // Both of them can't be memory operations though.
6348   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6349     CanFoldLoad = false;
6350
6351   if (CanFoldLoad) {
6352     if (HasXMMInt && NumElems == 2)
6353       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6354
6355     if (NumElems == 4)
6356       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6357   }
6358
6359   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6360   // movl and movlp will both match v2i64, but v2i64 is never matched by
6361   // movl earlier because we make it strict to avoid messing with the movlp load
6362   // folding logic (see the code above getMOVLP call). Match it here then,
6363   // this is horrible, but will stay like this until we move all shuffle
6364   // matching to x86 specific nodes. Note that for the 1st condition all
6365   // types are matched with movsd.
6366   if (HasXMMInt) {
6367     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6368     // as to remove this logic from here, as much as possible
6369     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6370       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6371     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6372   }
6373
6374   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6375
6376   // Invert the operand order and use SHUFPS to match it.
6377   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6378                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6379 }
6380
6381 static inline unsigned getUNPCKLOpcode(EVT VT) {
6382   switch(VT.getSimpleVT().SimpleTy) {
6383   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6384   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6385   case MVT::v4f32: return X86ISD::UNPCKLPS;
6386   case MVT::v2f64: return X86ISD::UNPCKLPD;
6387   case MVT::v8i32: // Use fp unit for int unpack.
6388   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6389   case MVT::v4i64: // Use fp unit for int unpack.
6390   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6391   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6392   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6393   default:
6394     llvm_unreachable("Unknown type for unpckl");
6395   }
6396   return 0;
6397 }
6398
6399 static inline unsigned getUNPCKHOpcode(EVT VT) {
6400   switch(VT.getSimpleVT().SimpleTy) {
6401   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6402   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6403   case MVT::v4f32: return X86ISD::UNPCKHPS;
6404   case MVT::v2f64: return X86ISD::UNPCKHPD;
6405   case MVT::v8i32: // Use fp unit for int unpack.
6406   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6407   case MVT::v4i64: // Use fp unit for int unpack.
6408   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6409   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6410   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6411   default:
6412     llvm_unreachable("Unknown type for unpckh");
6413   }
6414   return 0;
6415 }
6416
6417 static inline unsigned getVPERMILOpcode(EVT VT) {
6418   switch(VT.getSimpleVT().SimpleTy) {
6419   case MVT::v4i32:
6420   case MVT::v4f32: return X86ISD::VPERMILPS;
6421   case MVT::v2i64:
6422   case MVT::v2f64: return X86ISD::VPERMILPD;
6423   case MVT::v8i32:
6424   case MVT::v8f32: return X86ISD::VPERMILPSY;
6425   case MVT::v4i64:
6426   case MVT::v4f64: return X86ISD::VPERMILPDY;
6427   default:
6428     llvm_unreachable("Unknown type for vpermil");
6429   }
6430   return 0;
6431 }
6432
6433 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6434 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6435 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6436 static bool isVectorBroadcast(SDValue &Op) {
6437   EVT VT = Op.getValueType();
6438   bool Is256 = VT.getSizeInBits() == 256;
6439
6440   assert((VT.getSizeInBits() == 128 || Is256) &&
6441          "Unsupported type for vbroadcast node");
6442
6443   SDValue V = Op;
6444   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6445     V = V.getOperand(0);
6446
6447   if (Is256 && !(V.hasOneUse() &&
6448                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6449                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6450     return false;
6451
6452   if (Is256)
6453     V = V.getOperand(1);
6454
6455   if (!V.hasOneUse())
6456     return false;
6457
6458   // Check the source scalar_to_vector type. 256-bit broadcasts are
6459   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6460   // for 32-bit scalars.
6461   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6462     return false;
6463
6464   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6465   if (ScalarSize != 32 && ScalarSize != 64)
6466     return false;
6467   if (!Is256 && ScalarSize == 64)
6468     return false;
6469
6470   V = V.getOperand(0);
6471   if (!MayFoldLoad(V))
6472     return false;
6473
6474   // Return the load node
6475   Op = V;
6476   return true;
6477 }
6478
6479 static
6480 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6481                                const TargetLowering &TLI,
6482                                const X86Subtarget *Subtarget) {
6483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6484   EVT VT = Op.getValueType();
6485   DebugLoc dl = Op.getDebugLoc();
6486   SDValue V1 = Op.getOperand(0);
6487   SDValue V2 = Op.getOperand(1);
6488
6489   if (isZeroShuffle(SVOp))
6490     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6491
6492   // Handle splat operations
6493   if (SVOp->isSplat()) {
6494     unsigned NumElem = VT.getVectorNumElements();
6495     int Size = VT.getSizeInBits();
6496     // Special case, this is the only place now where it's allowed to return
6497     // a vector_shuffle operation without using a target specific node, because
6498     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6499     // this be moved to DAGCombine instead?
6500     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6501       return Op;
6502
6503     // Use vbroadcast whenever the splat comes from a foldable load
6504     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6505       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6506
6507     // Handle splats by matching through known shuffle masks
6508     if ((Size == 128 && NumElem <= 4) ||
6509         (Size == 256 && NumElem < 8))
6510       return SDValue();
6511
6512     // All remaning splats are promoted to target supported vector shuffles.
6513     return PromoteSplat(SVOp, DAG);
6514   }
6515
6516   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6517   // do it!
6518   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6519     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6520     if (NewOp.getNode())
6521       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6522   } else if ((VT == MVT::v4i32 ||
6523              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6524     // FIXME: Figure out a cleaner way to do this.
6525     // Try to make use of movq to zero out the top part.
6526     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6527       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6528       if (NewOp.getNode()) {
6529         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6530           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6531                               DAG, Subtarget, dl);
6532       }
6533     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6534       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6535       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6536         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6537                             DAG, Subtarget, dl);
6538     }
6539   }
6540   return SDValue();
6541 }
6542
6543 SDValue
6544 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6545   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6546   SDValue V1 = Op.getOperand(0);
6547   SDValue V2 = Op.getOperand(1);
6548   EVT VT = Op.getValueType();
6549   DebugLoc dl = Op.getDebugLoc();
6550   unsigned NumElems = VT.getVectorNumElements();
6551   bool isMMX = VT.getSizeInBits() == 64;
6552   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6553   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6554   bool V1IsSplat = false;
6555   bool V2IsSplat = false;
6556   bool HasXMMInt = Subtarget->hasXMMInt();
6557   MachineFunction &MF = DAG.getMachineFunction();
6558   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6559
6560   // Shuffle operations on MMX not supported.
6561   if (isMMX)
6562     return Op;
6563
6564   // Vector shuffle lowering takes 3 steps:
6565   //
6566   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6567   //    narrowing and commutation of operands should be handled.
6568   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6569   //    shuffle nodes.
6570   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6571   //    so the shuffle can be broken into other shuffles and the legalizer can
6572   //    try the lowering again.
6573   //
6574   // The general ideia is that no vector_shuffle operation should be left to
6575   // be matched during isel, all of them must be converted to a target specific
6576   // node here.
6577
6578   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6579   // narrowing and commutation of operands should be handled. The actual code
6580   // doesn't include all of those, work in progress...
6581   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6582   if (NewOp.getNode())
6583     return NewOp;
6584
6585   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6586   // unpckh_undef). Only use pshufd if speed is more important than size.
6587   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6588     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6589   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6590     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6591
6592   if (X86::isMOVDDUPMask(SVOp) &&
6593       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6594       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6595     return getMOVDDup(Op, dl, V1, DAG);
6596
6597   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6598     return getMOVHighToLow(Op, dl, DAG);
6599
6600   // Use to match splats
6601   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6602       (VT == MVT::v2f64 || VT == MVT::v2i64))
6603     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6604
6605   if (X86::isPSHUFDMask(SVOp)) {
6606     // The actual implementation will match the mask in the if above and then
6607     // during isel it can match several different instructions, not only pshufd
6608     // as its name says, sad but true, emulate the behavior for now...
6609     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6610         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6611
6612     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6613
6614     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6615       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6616
6617     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6618                                 TargetMask, DAG);
6619   }
6620
6621   // Check if this can be converted into a logical shift.
6622   bool isLeft = false;
6623   unsigned ShAmt = 0;
6624   SDValue ShVal;
6625   bool isShift = getSubtarget()->hasXMMInt() &&
6626                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6627   if (isShift && ShVal.hasOneUse()) {
6628     // If the shifted value has multiple uses, it may be cheaper to use
6629     // v_set0 + movlhps or movhlps, etc.
6630     EVT EltVT = VT.getVectorElementType();
6631     ShAmt *= EltVT.getSizeInBits();
6632     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6633   }
6634
6635   if (X86::isMOVLMask(SVOp)) {
6636     if (V1IsUndef)
6637       return V2;
6638     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6639       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6640     if (!X86::isMOVLPMask(SVOp)) {
6641       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6642         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6643
6644       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6645         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6646     }
6647   }
6648
6649   // FIXME: fold these into legal mask.
6650   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6651     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6652
6653   if (X86::isMOVHLPSMask(SVOp))
6654     return getMOVHighToLow(Op, dl, DAG);
6655
6656   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6657     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6658
6659   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6660     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6661
6662   if (X86::isMOVLPMask(SVOp))
6663     return getMOVLP(Op, dl, DAG, HasXMMInt);
6664
6665   if (ShouldXformToMOVHLPS(SVOp) ||
6666       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6667     return CommuteVectorShuffle(SVOp, DAG);
6668
6669   if (isShift) {
6670     // No better options. Use a vshl / vsrl.
6671     EVT EltVT = VT.getVectorElementType();
6672     ShAmt *= EltVT.getSizeInBits();
6673     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6674   }
6675
6676   bool Commuted = false;
6677   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6678   // 1,1,1,1 -> v8i16 though.
6679   V1IsSplat = isSplatVector(V1.getNode());
6680   V2IsSplat = isSplatVector(V2.getNode());
6681
6682   // Canonicalize the splat or undef, if present, to be on the RHS.
6683   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6684     Op = CommuteVectorShuffle(SVOp, DAG);
6685     SVOp = cast<ShuffleVectorSDNode>(Op);
6686     V1 = SVOp->getOperand(0);
6687     V2 = SVOp->getOperand(1);
6688     std::swap(V1IsSplat, V2IsSplat);
6689     std::swap(V1IsUndef, V2IsUndef);
6690     Commuted = true;
6691   }
6692
6693   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6694     // Shuffling low element of v1 into undef, just return v1.
6695     if (V2IsUndef)
6696       return V1;
6697     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6698     // the instruction selector will not match, so get a canonical MOVL with
6699     // swapped operands to undo the commute.
6700     return getMOVL(DAG, dl, VT, V2, V1);
6701   }
6702
6703   if (X86::isUNPCKLMask(SVOp))
6704     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6705
6706   if (X86::isUNPCKHMask(SVOp))
6707     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6708
6709   if (V2IsSplat) {
6710     // Normalize mask so all entries that point to V2 points to its first
6711     // element then try to match unpck{h|l} again. If match, return a
6712     // new vector_shuffle with the corrected mask.
6713     SDValue NewMask = NormalizeMask(SVOp, DAG);
6714     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6715     if (NSVOp != SVOp) {
6716       if (X86::isUNPCKLMask(NSVOp, true)) {
6717         return NewMask;
6718       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6719         return NewMask;
6720       }
6721     }
6722   }
6723
6724   if (Commuted) {
6725     // Commute is back and try unpck* again.
6726     // FIXME: this seems wrong.
6727     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6728     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6729
6730     if (X86::isUNPCKLMask(NewSVOp))
6731       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6732
6733     if (X86::isUNPCKHMask(NewSVOp))
6734       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6735   }
6736
6737   // Normalize the node to match x86 shuffle ops if needed
6738   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6739     return CommuteVectorShuffle(SVOp, DAG);
6740
6741   // The checks below are all present in isShuffleMaskLegal, but they are
6742   // inlined here right now to enable us to directly emit target specific
6743   // nodes, and remove one by one until they don't return Op anymore.
6744   SmallVector<int, 16> M;
6745   SVOp->getMask(M);
6746
6747   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6748     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6749                                 X86::getShufflePALIGNRImmediate(SVOp),
6750                                 DAG);
6751
6752   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6753       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6754     if (VT == MVT::v2f64)
6755       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6756     if (VT == MVT::v2i64)
6757       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6758   }
6759
6760   if (isPSHUFHWMask(M, VT))
6761     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6762                                 X86::getShufflePSHUFHWImmediate(SVOp),
6763                                 DAG);
6764
6765   if (isPSHUFLWMask(M, VT))
6766     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6767                                 X86::getShufflePSHUFLWImmediate(SVOp),
6768                                 DAG);
6769
6770   if (isSHUFPMask(M, VT))
6771     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6772                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6773
6774   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6775     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6776   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6777     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6778
6779   //===--------------------------------------------------------------------===//
6780   // Generate target specific nodes for 128 or 256-bit shuffles only
6781   // supported in the AVX instruction set.
6782   //
6783
6784   // Handle VMOVDDUPY permutations
6785   if (isMOVDDUPYMask(SVOp, Subtarget))
6786     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6787
6788   // Handle VPERMILPS* permutations
6789   if (isVPERMILPSMask(M, VT, Subtarget))
6790     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6791                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6792
6793   // Handle VPERMILPD* permutations
6794   if (isVPERMILPDMask(M, VT, Subtarget))
6795     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6796                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6797
6798   // Handle VPERM2F128 permutations
6799   if (isVPERM2F128Mask(M, VT, Subtarget))
6800     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6801                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6802
6803   // Handle VSHUFPSY permutations
6804   if (isVSHUFPSYMask(M, VT, Subtarget))
6805     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6806                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6807
6808   // Handle VSHUFPDY permutations
6809   if (isVSHUFPDYMask(M, VT, Subtarget))
6810     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6811                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6812
6813   //===--------------------------------------------------------------------===//
6814   // Since no target specific shuffle was selected for this generic one,
6815   // lower it into other known shuffles. FIXME: this isn't true yet, but
6816   // this is the plan.
6817   //
6818
6819   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6820   if (VT == MVT::v8i16) {
6821     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6822     if (NewOp.getNode())
6823       return NewOp;
6824   }
6825
6826   if (VT == MVT::v16i8) {
6827     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6828     if (NewOp.getNode())
6829       return NewOp;
6830   }
6831
6832   // Handle all 128-bit wide vectors with 4 elements, and match them with
6833   // several different shuffle types.
6834   if (NumElems == 4 && VT.getSizeInBits() == 128)
6835     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6836
6837   // Handle general 256-bit shuffles
6838   if (VT.is256BitVector())
6839     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6840
6841   return SDValue();
6842 }
6843
6844 SDValue
6845 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6846                                                 SelectionDAG &DAG) const {
6847   EVT VT = Op.getValueType();
6848   DebugLoc dl = Op.getDebugLoc();
6849
6850   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6851     return SDValue();
6852
6853   if (VT.getSizeInBits() == 8) {
6854     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6855                                     Op.getOperand(0), Op.getOperand(1));
6856     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6857                                     DAG.getValueType(VT));
6858     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6859   } else if (VT.getSizeInBits() == 16) {
6860     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6861     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6862     if (Idx == 0)
6863       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6864                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6865                                      DAG.getNode(ISD::BITCAST, dl,
6866                                                  MVT::v4i32,
6867                                                  Op.getOperand(0)),
6868                                      Op.getOperand(1)));
6869     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6870                                     Op.getOperand(0), Op.getOperand(1));
6871     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6872                                     DAG.getValueType(VT));
6873     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6874   } else if (VT == MVT::f32) {
6875     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6876     // the result back to FR32 register. It's only worth matching if the
6877     // result has a single use which is a store or a bitcast to i32.  And in
6878     // the case of a store, it's not worth it if the index is a constant 0,
6879     // because a MOVSSmr can be used instead, which is smaller and faster.
6880     if (!Op.hasOneUse())
6881       return SDValue();
6882     SDNode *User = *Op.getNode()->use_begin();
6883     if ((User->getOpcode() != ISD::STORE ||
6884          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6885           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6886         (User->getOpcode() != ISD::BITCAST ||
6887          User->getValueType(0) != MVT::i32))
6888       return SDValue();
6889     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6890                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6891                                               Op.getOperand(0)),
6892                                               Op.getOperand(1));
6893     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6894   } else if (VT == MVT::i32) {
6895     // ExtractPS works with constant index.
6896     if (isa<ConstantSDNode>(Op.getOperand(1)))
6897       return Op;
6898   }
6899   return SDValue();
6900 }
6901
6902
6903 SDValue
6904 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6905                                            SelectionDAG &DAG) const {
6906   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6907     return SDValue();
6908
6909   SDValue Vec = Op.getOperand(0);
6910   EVT VecVT = Vec.getValueType();
6911
6912   // If this is a 256-bit vector result, first extract the 128-bit vector and
6913   // then extract the element from the 128-bit vector.
6914   if (VecVT.getSizeInBits() == 256) {
6915     DebugLoc dl = Op.getNode()->getDebugLoc();
6916     unsigned NumElems = VecVT.getVectorNumElements();
6917     SDValue Idx = Op.getOperand(1);
6918     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6919
6920     // Get the 128-bit vector.
6921     bool Upper = IdxVal >= NumElems/2;
6922     Vec = Extract128BitVector(Vec,
6923                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6924
6925     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6926                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6927   }
6928
6929   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6930
6931   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6932     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6933     if (Res.getNode())
6934       return Res;
6935   }
6936
6937   EVT VT = Op.getValueType();
6938   DebugLoc dl = Op.getDebugLoc();
6939   // TODO: handle v16i8.
6940   if (VT.getSizeInBits() == 16) {
6941     SDValue Vec = Op.getOperand(0);
6942     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6943     if (Idx == 0)
6944       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6945                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6946                                      DAG.getNode(ISD::BITCAST, dl,
6947                                                  MVT::v4i32, Vec),
6948                                      Op.getOperand(1)));
6949     // Transform it so it match pextrw which produces a 32-bit result.
6950     EVT EltVT = MVT::i32;
6951     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6952                                     Op.getOperand(0), Op.getOperand(1));
6953     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6954                                     DAG.getValueType(VT));
6955     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6956   } else if (VT.getSizeInBits() == 32) {
6957     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6958     if (Idx == 0)
6959       return Op;
6960
6961     // SHUFPS the element to the lowest double word, then movss.
6962     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6963     EVT VVT = Op.getOperand(0).getValueType();
6964     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6965                                        DAG.getUNDEF(VVT), Mask);
6966     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6967                        DAG.getIntPtrConstant(0));
6968   } else if (VT.getSizeInBits() == 64) {
6969     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6970     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6971     //        to match extract_elt for f64.
6972     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6973     if (Idx == 0)
6974       return Op;
6975
6976     // UNPCKHPD the element to the lowest double word, then movsd.
6977     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6978     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6979     int Mask[2] = { 1, -1 };
6980     EVT VVT = Op.getOperand(0).getValueType();
6981     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6982                                        DAG.getUNDEF(VVT), Mask);
6983     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6984                        DAG.getIntPtrConstant(0));
6985   }
6986
6987   return SDValue();
6988 }
6989
6990 SDValue
6991 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6992                                                SelectionDAG &DAG) const {
6993   EVT VT = Op.getValueType();
6994   EVT EltVT = VT.getVectorElementType();
6995   DebugLoc dl = Op.getDebugLoc();
6996
6997   SDValue N0 = Op.getOperand(0);
6998   SDValue N1 = Op.getOperand(1);
6999   SDValue N2 = Op.getOperand(2);
7000
7001   if (VT.getSizeInBits() == 256)
7002     return SDValue();
7003
7004   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7005       isa<ConstantSDNode>(N2)) {
7006     unsigned Opc;
7007     if (VT == MVT::v8i16)
7008       Opc = X86ISD::PINSRW;
7009     else if (VT == MVT::v16i8)
7010       Opc = X86ISD::PINSRB;
7011     else
7012       Opc = X86ISD::PINSRB;
7013
7014     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7015     // argument.
7016     if (N1.getValueType() != MVT::i32)
7017       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7018     if (N2.getValueType() != MVT::i32)
7019       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7020     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7021   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7022     // Bits [7:6] of the constant are the source select.  This will always be
7023     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7024     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7025     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7026     // Bits [5:4] of the constant are the destination select.  This is the
7027     //  value of the incoming immediate.
7028     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7029     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7030     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7031     // Create this as a scalar to vector..
7032     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7033     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7034   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7035     // PINSR* works with constant index.
7036     return Op;
7037   }
7038   return SDValue();
7039 }
7040
7041 SDValue
7042 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7043   EVT VT = Op.getValueType();
7044   EVT EltVT = VT.getVectorElementType();
7045
7046   DebugLoc dl = Op.getDebugLoc();
7047   SDValue N0 = Op.getOperand(0);
7048   SDValue N1 = Op.getOperand(1);
7049   SDValue N2 = Op.getOperand(2);
7050
7051   // If this is a 256-bit vector result, first extract the 128-bit vector,
7052   // insert the element into the extracted half and then place it back.
7053   if (VT.getSizeInBits() == 256) {
7054     if (!isa<ConstantSDNode>(N2))
7055       return SDValue();
7056
7057     // Get the desired 128-bit vector half.
7058     unsigned NumElems = VT.getVectorNumElements();
7059     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7060     bool Upper = IdxVal >= NumElems/2;
7061     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7062     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7063
7064     // Insert the element into the desired half.
7065     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7066                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7067
7068     // Insert the changed part back to the 256-bit vector
7069     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7070   }
7071
7072   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7073     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7074
7075   if (EltVT == MVT::i8)
7076     return SDValue();
7077
7078   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7079     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7080     // as its second argument.
7081     if (N1.getValueType() != MVT::i32)
7082       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7083     if (N2.getValueType() != MVT::i32)
7084       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7085     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7086   }
7087   return SDValue();
7088 }
7089
7090 SDValue
7091 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7092   LLVMContext *Context = DAG.getContext();
7093   DebugLoc dl = Op.getDebugLoc();
7094   EVT OpVT = Op.getValueType();
7095
7096   // If this is a 256-bit vector result, first insert into a 128-bit
7097   // vector and then insert into the 256-bit vector.
7098   if (OpVT.getSizeInBits() > 128) {
7099     // Insert into a 128-bit vector.
7100     EVT VT128 = EVT::getVectorVT(*Context,
7101                                  OpVT.getVectorElementType(),
7102                                  OpVT.getVectorNumElements() / 2);
7103
7104     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7105
7106     // Insert the 128-bit vector.
7107     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7108                               DAG.getConstant(0, MVT::i32),
7109                               DAG, dl);
7110   }
7111
7112   if (Op.getValueType() == MVT::v1i64 &&
7113       Op.getOperand(0).getValueType() == MVT::i64)
7114     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7115
7116   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7117   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7118          "Expected an SSE type!");
7119   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7120                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7121 }
7122
7123 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7124 // a simple subregister reference or explicit instructions to grab
7125 // upper bits of a vector.
7126 SDValue
7127 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7128   if (Subtarget->hasAVX()) {
7129     DebugLoc dl = Op.getNode()->getDebugLoc();
7130     SDValue Vec = Op.getNode()->getOperand(0);
7131     SDValue Idx = Op.getNode()->getOperand(1);
7132
7133     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7134         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7135         return Extract128BitVector(Vec, Idx, DAG, dl);
7136     }
7137   }
7138   return SDValue();
7139 }
7140
7141 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7142 // simple superregister reference or explicit instructions to insert
7143 // the upper bits of a vector.
7144 SDValue
7145 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7146   if (Subtarget->hasAVX()) {
7147     DebugLoc dl = Op.getNode()->getDebugLoc();
7148     SDValue Vec = Op.getNode()->getOperand(0);
7149     SDValue SubVec = Op.getNode()->getOperand(1);
7150     SDValue Idx = Op.getNode()->getOperand(2);
7151
7152     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7153         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7154       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7155     }
7156   }
7157   return SDValue();
7158 }
7159
7160 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7161 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7162 // one of the above mentioned nodes. It has to be wrapped because otherwise
7163 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7164 // be used to form addressing mode. These wrapped nodes will be selected
7165 // into MOV32ri.
7166 SDValue
7167 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7168   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7169
7170   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7171   // global base reg.
7172   unsigned char OpFlag = 0;
7173   unsigned WrapperKind = X86ISD::Wrapper;
7174   CodeModel::Model M = getTargetMachine().getCodeModel();
7175
7176   if (Subtarget->isPICStyleRIPRel() &&
7177       (M == CodeModel::Small || M == CodeModel::Kernel))
7178     WrapperKind = X86ISD::WrapperRIP;
7179   else if (Subtarget->isPICStyleGOT())
7180     OpFlag = X86II::MO_GOTOFF;
7181   else if (Subtarget->isPICStyleStubPIC())
7182     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7183
7184   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7185                                              CP->getAlignment(),
7186                                              CP->getOffset(), OpFlag);
7187   DebugLoc DL = CP->getDebugLoc();
7188   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7189   // With PIC, the address is actually $g + Offset.
7190   if (OpFlag) {
7191     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7192                          DAG.getNode(X86ISD::GlobalBaseReg,
7193                                      DebugLoc(), getPointerTy()),
7194                          Result);
7195   }
7196
7197   return Result;
7198 }
7199
7200 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7201   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7202
7203   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7204   // global base reg.
7205   unsigned char OpFlag = 0;
7206   unsigned WrapperKind = X86ISD::Wrapper;
7207   CodeModel::Model M = getTargetMachine().getCodeModel();
7208
7209   if (Subtarget->isPICStyleRIPRel() &&
7210       (M == CodeModel::Small || M == CodeModel::Kernel))
7211     WrapperKind = X86ISD::WrapperRIP;
7212   else if (Subtarget->isPICStyleGOT())
7213     OpFlag = X86II::MO_GOTOFF;
7214   else if (Subtarget->isPICStyleStubPIC())
7215     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7216
7217   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7218                                           OpFlag);
7219   DebugLoc DL = JT->getDebugLoc();
7220   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7221
7222   // With PIC, the address is actually $g + Offset.
7223   if (OpFlag)
7224     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7225                          DAG.getNode(X86ISD::GlobalBaseReg,
7226                                      DebugLoc(), getPointerTy()),
7227                          Result);
7228
7229   return Result;
7230 }
7231
7232 SDValue
7233 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7234   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7235
7236   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7237   // global base reg.
7238   unsigned char OpFlag = 0;
7239   unsigned WrapperKind = X86ISD::Wrapper;
7240   CodeModel::Model M = getTargetMachine().getCodeModel();
7241
7242   if (Subtarget->isPICStyleRIPRel() &&
7243       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7244     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7245       OpFlag = X86II::MO_GOTPCREL;
7246     WrapperKind = X86ISD::WrapperRIP;
7247   } else if (Subtarget->isPICStyleGOT()) {
7248     OpFlag = X86II::MO_GOT;
7249   } else if (Subtarget->isPICStyleStubPIC()) {
7250     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7251   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7252     OpFlag = X86II::MO_DARWIN_NONLAZY;
7253   }
7254
7255   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7256
7257   DebugLoc DL = Op.getDebugLoc();
7258   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7259
7260
7261   // With PIC, the address is actually $g + Offset.
7262   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7263       !Subtarget->is64Bit()) {
7264     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7265                          DAG.getNode(X86ISD::GlobalBaseReg,
7266                                      DebugLoc(), getPointerTy()),
7267                          Result);
7268   }
7269
7270   // For symbols that require a load from a stub to get the address, emit the
7271   // load.
7272   if (isGlobalStubReference(OpFlag))
7273     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7274                          MachinePointerInfo::getGOT(), false, false, 0);
7275
7276   return Result;
7277 }
7278
7279 SDValue
7280 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7281   // Create the TargetBlockAddressAddress node.
7282   unsigned char OpFlags =
7283     Subtarget->ClassifyBlockAddressReference();
7284   CodeModel::Model M = getTargetMachine().getCodeModel();
7285   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7286   DebugLoc dl = Op.getDebugLoc();
7287   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7288                                        /*isTarget=*/true, OpFlags);
7289
7290   if (Subtarget->isPICStyleRIPRel() &&
7291       (M == CodeModel::Small || M == CodeModel::Kernel))
7292     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7293   else
7294     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7295
7296   // With PIC, the address is actually $g + Offset.
7297   if (isGlobalRelativeToPICBase(OpFlags)) {
7298     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7299                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7300                          Result);
7301   }
7302
7303   return Result;
7304 }
7305
7306 SDValue
7307 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7308                                       int64_t Offset,
7309                                       SelectionDAG &DAG) const {
7310   // Create the TargetGlobalAddress node, folding in the constant
7311   // offset if it is legal.
7312   unsigned char OpFlags =
7313     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7314   CodeModel::Model M = getTargetMachine().getCodeModel();
7315   SDValue Result;
7316   if (OpFlags == X86II::MO_NO_FLAG &&
7317       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7318     // A direct static reference to a global.
7319     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7320     Offset = 0;
7321   } else {
7322     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7323   }
7324
7325   if (Subtarget->isPICStyleRIPRel() &&
7326       (M == CodeModel::Small || M == CodeModel::Kernel))
7327     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7328   else
7329     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7330
7331   // With PIC, the address is actually $g + Offset.
7332   if (isGlobalRelativeToPICBase(OpFlags)) {
7333     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7334                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7335                          Result);
7336   }
7337
7338   // For globals that require a load from a stub to get the address, emit the
7339   // load.
7340   if (isGlobalStubReference(OpFlags))
7341     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7342                          MachinePointerInfo::getGOT(), false, false, 0);
7343
7344   // If there was a non-zero offset that we didn't fold, create an explicit
7345   // addition for it.
7346   if (Offset != 0)
7347     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7348                          DAG.getConstant(Offset, getPointerTy()));
7349
7350   return Result;
7351 }
7352
7353 SDValue
7354 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7355   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7356   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7357   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7358 }
7359
7360 static SDValue
7361 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7362            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7363            unsigned char OperandFlags) {
7364   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7365   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7366   DebugLoc dl = GA->getDebugLoc();
7367   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7368                                            GA->getValueType(0),
7369                                            GA->getOffset(),
7370                                            OperandFlags);
7371   if (InFlag) {
7372     SDValue Ops[] = { Chain,  TGA, *InFlag };
7373     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7374   } else {
7375     SDValue Ops[]  = { Chain, TGA };
7376     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7377   }
7378
7379   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7380   MFI->setAdjustsStack(true);
7381
7382   SDValue Flag = Chain.getValue(1);
7383   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7384 }
7385
7386 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7387 static SDValue
7388 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7389                                 const EVT PtrVT) {
7390   SDValue InFlag;
7391   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7392   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7393                                      DAG.getNode(X86ISD::GlobalBaseReg,
7394                                                  DebugLoc(), PtrVT), InFlag);
7395   InFlag = Chain.getValue(1);
7396
7397   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7398 }
7399
7400 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7401 static SDValue
7402 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7403                                 const EVT PtrVT) {
7404   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7405                     X86::RAX, X86II::MO_TLSGD);
7406 }
7407
7408 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7409 // "local exec" model.
7410 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7411                                    const EVT PtrVT, TLSModel::Model model,
7412                                    bool is64Bit) {
7413   DebugLoc dl = GA->getDebugLoc();
7414
7415   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7416   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7417                                                          is64Bit ? 257 : 256));
7418
7419   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7420                                       DAG.getIntPtrConstant(0),
7421                                       MachinePointerInfo(Ptr), false, false, 0);
7422
7423   unsigned char OperandFlags = 0;
7424   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7425   // initialexec.
7426   unsigned WrapperKind = X86ISD::Wrapper;
7427   if (model == TLSModel::LocalExec) {
7428     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7429   } else if (is64Bit) {
7430     assert(model == TLSModel::InitialExec);
7431     OperandFlags = X86II::MO_GOTTPOFF;
7432     WrapperKind = X86ISD::WrapperRIP;
7433   } else {
7434     assert(model == TLSModel::InitialExec);
7435     OperandFlags = X86II::MO_INDNTPOFF;
7436   }
7437
7438   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7439   // exec)
7440   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7441                                            GA->getValueType(0),
7442                                            GA->getOffset(), OperandFlags);
7443   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7444
7445   if (model == TLSModel::InitialExec)
7446     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7447                          MachinePointerInfo::getGOT(), false, false, 0);
7448
7449   // The address of the thread local variable is the add of the thread
7450   // pointer with the offset of the variable.
7451   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7452 }
7453
7454 SDValue
7455 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7456
7457   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7458   const GlobalValue *GV = GA->getGlobal();
7459
7460   if (Subtarget->isTargetELF()) {
7461     // TODO: implement the "local dynamic" model
7462     // TODO: implement the "initial exec"model for pic executables
7463
7464     // If GV is an alias then use the aliasee for determining
7465     // thread-localness.
7466     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7467       GV = GA->resolveAliasedGlobal(false);
7468
7469     TLSModel::Model model
7470       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7471
7472     switch (model) {
7473       case TLSModel::GeneralDynamic:
7474       case TLSModel::LocalDynamic: // not implemented
7475         if (Subtarget->is64Bit())
7476           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7477         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7478
7479       case TLSModel::InitialExec:
7480       case TLSModel::LocalExec:
7481         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7482                                    Subtarget->is64Bit());
7483     }
7484   } else if (Subtarget->isTargetDarwin()) {
7485     // Darwin only has one model of TLS.  Lower to that.
7486     unsigned char OpFlag = 0;
7487     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7488                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7489
7490     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7491     // global base reg.
7492     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7493                   !Subtarget->is64Bit();
7494     if (PIC32)
7495       OpFlag = X86II::MO_TLVP_PIC_BASE;
7496     else
7497       OpFlag = X86II::MO_TLVP;
7498     DebugLoc DL = Op.getDebugLoc();
7499     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7500                                                 GA->getValueType(0),
7501                                                 GA->getOffset(), OpFlag);
7502     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7503
7504     // With PIC32, the address is actually $g + Offset.
7505     if (PIC32)
7506       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7507                            DAG.getNode(X86ISD::GlobalBaseReg,
7508                                        DebugLoc(), getPointerTy()),
7509                            Offset);
7510
7511     // Lowering the machine isd will make sure everything is in the right
7512     // location.
7513     SDValue Chain = DAG.getEntryNode();
7514     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7515     SDValue Args[] = { Chain, Offset };
7516     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7517
7518     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7519     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7520     MFI->setAdjustsStack(true);
7521
7522     // And our return value (tls address) is in the standard call return value
7523     // location.
7524     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7525     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7526   }
7527
7528   assert(false &&
7529          "TLS not implemented for this target.");
7530
7531   llvm_unreachable("Unreachable");
7532   return SDValue();
7533 }
7534
7535
7536 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7537 /// take a 2 x i32 value to shift plus a shift amount.
7538 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7539   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7540   EVT VT = Op.getValueType();
7541   unsigned VTBits = VT.getSizeInBits();
7542   DebugLoc dl = Op.getDebugLoc();
7543   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7544   SDValue ShOpLo = Op.getOperand(0);
7545   SDValue ShOpHi = Op.getOperand(1);
7546   SDValue ShAmt  = Op.getOperand(2);
7547   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7548                                      DAG.getConstant(VTBits - 1, MVT::i8))
7549                        : DAG.getConstant(0, VT);
7550
7551   SDValue Tmp2, Tmp3;
7552   if (Op.getOpcode() == ISD::SHL_PARTS) {
7553     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7554     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7555   } else {
7556     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7557     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7558   }
7559
7560   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7561                                 DAG.getConstant(VTBits, MVT::i8));
7562   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7563                              AndNode, DAG.getConstant(0, MVT::i8));
7564
7565   SDValue Hi, Lo;
7566   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7567   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7568   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7569
7570   if (Op.getOpcode() == ISD::SHL_PARTS) {
7571     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7572     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7573   } else {
7574     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7575     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7576   }
7577
7578   SDValue Ops[2] = { Lo, Hi };
7579   return DAG.getMergeValues(Ops, 2, dl);
7580 }
7581
7582 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7583                                            SelectionDAG &DAG) const {
7584   EVT SrcVT = Op.getOperand(0).getValueType();
7585
7586   if (SrcVT.isVector())
7587     return SDValue();
7588
7589   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7590          "Unknown SINT_TO_FP to lower!");
7591
7592   // These are really Legal; return the operand so the caller accepts it as
7593   // Legal.
7594   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7595     return Op;
7596   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7597       Subtarget->is64Bit()) {
7598     return Op;
7599   }
7600
7601   DebugLoc dl = Op.getDebugLoc();
7602   unsigned Size = SrcVT.getSizeInBits()/8;
7603   MachineFunction &MF = DAG.getMachineFunction();
7604   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7605   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7606   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7607                                StackSlot,
7608                                MachinePointerInfo::getFixedStack(SSFI),
7609                                false, false, 0);
7610   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7611 }
7612
7613 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7614                                      SDValue StackSlot,
7615                                      SelectionDAG &DAG) const {
7616   // Build the FILD
7617   DebugLoc DL = Op.getDebugLoc();
7618   SDVTList Tys;
7619   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7620   if (useSSE)
7621     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7622   else
7623     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7624
7625   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7626
7627   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7628   MachineMemOperand *MMO;
7629   if (FI) {
7630     int SSFI = FI->getIndex();
7631     MMO =
7632       DAG.getMachineFunction()
7633       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7634                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7635   } else {
7636     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7637     StackSlot = StackSlot.getOperand(1);
7638   }
7639   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7640   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7641                                            X86ISD::FILD, DL,
7642                                            Tys, Ops, array_lengthof(Ops),
7643                                            SrcVT, MMO);
7644
7645   if (useSSE) {
7646     Chain = Result.getValue(1);
7647     SDValue InFlag = Result.getValue(2);
7648
7649     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7650     // shouldn't be necessary except that RFP cannot be live across
7651     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7652     MachineFunction &MF = DAG.getMachineFunction();
7653     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7654     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7655     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7656     Tys = DAG.getVTList(MVT::Other);
7657     SDValue Ops[] = {
7658       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7659     };
7660     MachineMemOperand *MMO =
7661       DAG.getMachineFunction()
7662       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7663                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7664
7665     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7666                                     Ops, array_lengthof(Ops),
7667                                     Op.getValueType(), MMO);
7668     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7669                          MachinePointerInfo::getFixedStack(SSFI),
7670                          false, false, 0);
7671   }
7672
7673   return Result;
7674 }
7675
7676 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7677 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7678                                                SelectionDAG &DAG) const {
7679   // This algorithm is not obvious. Here it is in C code, more or less:
7680   /*
7681     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7682       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7683       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7684
7685       // Copy ints to xmm registers.
7686       __m128i xh = _mm_cvtsi32_si128( hi );
7687       __m128i xl = _mm_cvtsi32_si128( lo );
7688
7689       // Combine into low half of a single xmm register.
7690       __m128i x = _mm_unpacklo_epi32( xh, xl );
7691       __m128d d;
7692       double sd;
7693
7694       // Merge in appropriate exponents to give the integer bits the right
7695       // magnitude.
7696       x = _mm_unpacklo_epi32( x, exp );
7697
7698       // Subtract away the biases to deal with the IEEE-754 double precision
7699       // implicit 1.
7700       d = _mm_sub_pd( (__m128d) x, bias );
7701
7702       // All conversions up to here are exact. The correctly rounded result is
7703       // calculated using the current rounding mode using the following
7704       // horizontal add.
7705       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7706       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7707                                 // store doesn't really need to be here (except
7708                                 // maybe to zero the other double)
7709       return sd;
7710     }
7711   */
7712
7713   DebugLoc dl = Op.getDebugLoc();
7714   LLVMContext *Context = DAG.getContext();
7715
7716   // Build some magic constants.
7717   std::vector<Constant*> CV0;
7718   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7719   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7720   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7721   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7722   Constant *C0 = ConstantVector::get(CV0);
7723   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7724
7725   std::vector<Constant*> CV1;
7726   CV1.push_back(
7727     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7728   CV1.push_back(
7729     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7730   Constant *C1 = ConstantVector::get(CV1);
7731   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7732
7733   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7734                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7735                                         Op.getOperand(0),
7736                                         DAG.getIntPtrConstant(1)));
7737   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7738                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7739                                         Op.getOperand(0),
7740                                         DAG.getIntPtrConstant(0)));
7741   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7742   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7743                               MachinePointerInfo::getConstantPool(),
7744                               false, false, 16);
7745   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7746   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7747   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7748                               MachinePointerInfo::getConstantPool(),
7749                               false, false, 16);
7750   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7751
7752   // Add the halves; easiest way is to swap them into another reg first.
7753   int ShufMask[2] = { 1, -1 };
7754   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7755                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7756   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7757   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7758                      DAG.getIntPtrConstant(0));
7759 }
7760
7761 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7762 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7763                                                SelectionDAG &DAG) const {
7764   DebugLoc dl = Op.getDebugLoc();
7765   // FP constant to bias correct the final result.
7766   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7767                                    MVT::f64);
7768
7769   // Load the 32-bit value into an XMM register.
7770   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7771                              Op.getOperand(0));
7772
7773   // Zero out the upper parts of the register.
7774   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7775                                      DAG);
7776
7777   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7778                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7779                      DAG.getIntPtrConstant(0));
7780
7781   // Or the load with the bias.
7782   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7783                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7784                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7785                                                    MVT::v2f64, Load)),
7786                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7787                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7788                                                    MVT::v2f64, Bias)));
7789   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7790                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7791                    DAG.getIntPtrConstant(0));
7792
7793   // Subtract the bias.
7794   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7795
7796   // Handle final rounding.
7797   EVT DestVT = Op.getValueType();
7798
7799   if (DestVT.bitsLT(MVT::f64)) {
7800     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7801                        DAG.getIntPtrConstant(0));
7802   } else if (DestVT.bitsGT(MVT::f64)) {
7803     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7804   }
7805
7806   // Handle final rounding.
7807   return Sub;
7808 }
7809
7810 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7811                                            SelectionDAG &DAG) const {
7812   SDValue N0 = Op.getOperand(0);
7813   DebugLoc dl = Op.getDebugLoc();
7814
7815   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7816   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7817   // the optimization here.
7818   if (DAG.SignBitIsZero(N0))
7819     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7820
7821   EVT SrcVT = N0.getValueType();
7822   EVT DstVT = Op.getValueType();
7823   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7824     return LowerUINT_TO_FP_i64(Op, DAG);
7825   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7826     return LowerUINT_TO_FP_i32(Op, DAG);
7827
7828   // Make a 64-bit buffer, and use it to build an FILD.
7829   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7830   if (SrcVT == MVT::i32) {
7831     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7832     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7833                                      getPointerTy(), StackSlot, WordOff);
7834     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7835                                   StackSlot, MachinePointerInfo(),
7836                                   false, false, 0);
7837     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7838                                   OffsetSlot, MachinePointerInfo(),
7839                                   false, false, 0);
7840     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7841     return Fild;
7842   }
7843
7844   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7845   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7846                                 StackSlot, MachinePointerInfo(),
7847                                false, false, 0);
7848   // For i64 source, we need to add the appropriate power of 2 if the input
7849   // was negative.  This is the same as the optimization in
7850   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7851   // we must be careful to do the computation in x87 extended precision, not
7852   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7853   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7854   MachineMemOperand *MMO =
7855     DAG.getMachineFunction()
7856     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7857                           MachineMemOperand::MOLoad, 8, 8);
7858
7859   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7860   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7861   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7862                                          MVT::i64, MMO);
7863
7864   APInt FF(32, 0x5F800000ULL);
7865
7866   // Check whether the sign bit is set.
7867   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7868                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7869                                  ISD::SETLT);
7870
7871   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7872   SDValue FudgePtr = DAG.getConstantPool(
7873                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7874                                          getPointerTy());
7875
7876   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7877   SDValue Zero = DAG.getIntPtrConstant(0);
7878   SDValue Four = DAG.getIntPtrConstant(4);
7879   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7880                                Zero, Four);
7881   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7882
7883   // Load the value out, extending it from f32 to f80.
7884   // FIXME: Avoid the extend by constructing the right constant pool?
7885   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7886                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7887                                  MVT::f32, false, false, 4);
7888   // Extend everything to 80 bits to force it to be done on x87.
7889   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7890   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7891 }
7892
7893 std::pair<SDValue,SDValue> X86TargetLowering::
7894 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7895   DebugLoc DL = Op.getDebugLoc();
7896
7897   EVT DstTy = Op.getValueType();
7898
7899   if (!IsSigned) {
7900     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7901     DstTy = MVT::i64;
7902   }
7903
7904   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7905          DstTy.getSimpleVT() >= MVT::i16 &&
7906          "Unknown FP_TO_SINT to lower!");
7907
7908   // These are really Legal.
7909   if (DstTy == MVT::i32 &&
7910       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7911     return std::make_pair(SDValue(), SDValue());
7912   if (Subtarget->is64Bit() &&
7913       DstTy == MVT::i64 &&
7914       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7915     return std::make_pair(SDValue(), SDValue());
7916
7917   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7918   // stack slot.
7919   MachineFunction &MF = DAG.getMachineFunction();
7920   unsigned MemSize = DstTy.getSizeInBits()/8;
7921   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7922   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7923
7924
7925
7926   unsigned Opc;
7927   switch (DstTy.getSimpleVT().SimpleTy) {
7928   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7929   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7930   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7931   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7932   }
7933
7934   SDValue Chain = DAG.getEntryNode();
7935   SDValue Value = Op.getOperand(0);
7936   EVT TheVT = Op.getOperand(0).getValueType();
7937   if (isScalarFPTypeInSSEReg(TheVT)) {
7938     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7939     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7940                          MachinePointerInfo::getFixedStack(SSFI),
7941                          false, false, 0);
7942     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7943     SDValue Ops[] = {
7944       Chain, StackSlot, DAG.getValueType(TheVT)
7945     };
7946
7947     MachineMemOperand *MMO =
7948       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7949                               MachineMemOperand::MOLoad, MemSize, MemSize);
7950     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7951                                     DstTy, MMO);
7952     Chain = Value.getValue(1);
7953     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7954     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7955   }
7956
7957   MachineMemOperand *MMO =
7958     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7959                             MachineMemOperand::MOStore, MemSize, MemSize);
7960
7961   // Build the FP_TO_INT*_IN_MEM
7962   SDValue Ops[] = { Chain, Value, StackSlot };
7963   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7964                                          Ops, 3, DstTy, MMO);
7965
7966   return std::make_pair(FIST, StackSlot);
7967 }
7968
7969 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7970                                            SelectionDAG &DAG) const {
7971   if (Op.getValueType().isVector())
7972     return SDValue();
7973
7974   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7975   SDValue FIST = Vals.first, StackSlot = Vals.second;
7976   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7977   if (FIST.getNode() == 0) return Op;
7978
7979   // Load the result.
7980   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7981                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7982 }
7983
7984 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7985                                            SelectionDAG &DAG) const {
7986   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7987   SDValue FIST = Vals.first, StackSlot = Vals.second;
7988   assert(FIST.getNode() && "Unexpected failure");
7989
7990   // Load the result.
7991   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7992                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7993 }
7994
7995 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7996                                      SelectionDAG &DAG) const {
7997   LLVMContext *Context = DAG.getContext();
7998   DebugLoc dl = Op.getDebugLoc();
7999   EVT VT = Op.getValueType();
8000   EVT EltVT = VT;
8001   if (VT.isVector())
8002     EltVT = VT.getVectorElementType();
8003   std::vector<Constant*> CV;
8004   if (EltVT == MVT::f64) {
8005     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8006     CV.push_back(C);
8007     CV.push_back(C);
8008   } else {
8009     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8010     CV.push_back(C);
8011     CV.push_back(C);
8012     CV.push_back(C);
8013     CV.push_back(C);
8014   }
8015   Constant *C = ConstantVector::get(CV);
8016   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8017   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8018                              MachinePointerInfo::getConstantPool(),
8019                              false, false, 16);
8020   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8021 }
8022
8023 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8024   LLVMContext *Context = DAG.getContext();
8025   DebugLoc dl = Op.getDebugLoc();
8026   EVT VT = Op.getValueType();
8027   EVT EltVT = VT;
8028   if (VT.isVector())
8029     EltVT = VT.getVectorElementType();
8030   std::vector<Constant*> CV;
8031   if (EltVT == MVT::f64) {
8032     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8033     CV.push_back(C);
8034     CV.push_back(C);
8035   } else {
8036     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8037     CV.push_back(C);
8038     CV.push_back(C);
8039     CV.push_back(C);
8040     CV.push_back(C);
8041   }
8042   Constant *C = ConstantVector::get(CV);
8043   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8044   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8045                              MachinePointerInfo::getConstantPool(),
8046                              false, false, 16);
8047   if (VT.isVector()) {
8048     return DAG.getNode(ISD::BITCAST, dl, VT,
8049                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8050                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8051                                 Op.getOperand(0)),
8052                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8053   } else {
8054     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8055   }
8056 }
8057
8058 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8059   LLVMContext *Context = DAG.getContext();
8060   SDValue Op0 = Op.getOperand(0);
8061   SDValue Op1 = Op.getOperand(1);
8062   DebugLoc dl = Op.getDebugLoc();
8063   EVT VT = Op.getValueType();
8064   EVT SrcVT = Op1.getValueType();
8065
8066   // If second operand is smaller, extend it first.
8067   if (SrcVT.bitsLT(VT)) {
8068     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8069     SrcVT = VT;
8070   }
8071   // And if it is bigger, shrink it first.
8072   if (SrcVT.bitsGT(VT)) {
8073     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8074     SrcVT = VT;
8075   }
8076
8077   // At this point the operands and the result should have the same
8078   // type, and that won't be f80 since that is not custom lowered.
8079
8080   // First get the sign bit of second operand.
8081   std::vector<Constant*> CV;
8082   if (SrcVT == MVT::f64) {
8083     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8084     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8085   } else {
8086     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8087     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8088     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8089     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8090   }
8091   Constant *C = ConstantVector::get(CV);
8092   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8093   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8094                               MachinePointerInfo::getConstantPool(),
8095                               false, false, 16);
8096   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8097
8098   // Shift sign bit right or left if the two operands have different types.
8099   if (SrcVT.bitsGT(VT)) {
8100     // Op0 is MVT::f32, Op1 is MVT::f64.
8101     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8102     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8103                           DAG.getConstant(32, MVT::i32));
8104     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8105     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8106                           DAG.getIntPtrConstant(0));
8107   }
8108
8109   // Clear first operand sign bit.
8110   CV.clear();
8111   if (VT == MVT::f64) {
8112     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8113     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8114   } else {
8115     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8116     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8117     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8118     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8119   }
8120   C = ConstantVector::get(CV);
8121   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8122   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8123                               MachinePointerInfo::getConstantPool(),
8124                               false, false, 16);
8125   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8126
8127   // Or the value with the sign bit.
8128   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8129 }
8130
8131 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8132   SDValue N0 = Op.getOperand(0);
8133   DebugLoc dl = Op.getDebugLoc();
8134   EVT VT = Op.getValueType();
8135
8136   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8137   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8138                                   DAG.getConstant(1, VT));
8139   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8140 }
8141
8142 /// Emit nodes that will be selected as "test Op0,Op0", or something
8143 /// equivalent.
8144 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8145                                     SelectionDAG &DAG) const {
8146   DebugLoc dl = Op.getDebugLoc();
8147
8148   // CF and OF aren't always set the way we want. Determine which
8149   // of these we need.
8150   bool NeedCF = false;
8151   bool NeedOF = false;
8152   switch (X86CC) {
8153   default: break;
8154   case X86::COND_A: case X86::COND_AE:
8155   case X86::COND_B: case X86::COND_BE:
8156     NeedCF = true;
8157     break;
8158   case X86::COND_G: case X86::COND_GE:
8159   case X86::COND_L: case X86::COND_LE:
8160   case X86::COND_O: case X86::COND_NO:
8161     NeedOF = true;
8162     break;
8163   }
8164
8165   // See if we can use the EFLAGS value from the operand instead of
8166   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8167   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8168   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8169     // Emit a CMP with 0, which is the TEST pattern.
8170     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8171                        DAG.getConstant(0, Op.getValueType()));
8172
8173   unsigned Opcode = 0;
8174   unsigned NumOperands = 0;
8175   switch (Op.getNode()->getOpcode()) {
8176   case ISD::ADD:
8177     // Due to an isel shortcoming, be conservative if this add is likely to be
8178     // selected as part of a load-modify-store instruction. When the root node
8179     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8180     // uses of other nodes in the match, such as the ADD in this case. This
8181     // leads to the ADD being left around and reselected, with the result being
8182     // two adds in the output.  Alas, even if none our users are stores, that
8183     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8184     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8185     // climbing the DAG back to the root, and it doesn't seem to be worth the
8186     // effort.
8187     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8188            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8189       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8190         goto default_case;
8191
8192     if (ConstantSDNode *C =
8193         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8194       // An add of one will be selected as an INC.
8195       if (C->getAPIntValue() == 1) {
8196         Opcode = X86ISD::INC;
8197         NumOperands = 1;
8198         break;
8199       }
8200
8201       // An add of negative one (subtract of one) will be selected as a DEC.
8202       if (C->getAPIntValue().isAllOnesValue()) {
8203         Opcode = X86ISD::DEC;
8204         NumOperands = 1;
8205         break;
8206       }
8207     }
8208
8209     // Otherwise use a regular EFLAGS-setting add.
8210     Opcode = X86ISD::ADD;
8211     NumOperands = 2;
8212     break;
8213   case ISD::AND: {
8214     // If the primary and result isn't used, don't bother using X86ISD::AND,
8215     // because a TEST instruction will be better.
8216     bool NonFlagUse = false;
8217     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8218            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8219       SDNode *User = *UI;
8220       unsigned UOpNo = UI.getOperandNo();
8221       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8222         // Look pass truncate.
8223         UOpNo = User->use_begin().getOperandNo();
8224         User = *User->use_begin();
8225       }
8226
8227       if (User->getOpcode() != ISD::BRCOND &&
8228           User->getOpcode() != ISD::SETCC &&
8229           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8230         NonFlagUse = true;
8231         break;
8232       }
8233     }
8234
8235     if (!NonFlagUse)
8236       break;
8237   }
8238     // FALL THROUGH
8239   case ISD::SUB:
8240   case ISD::OR:
8241   case ISD::XOR:
8242     // Due to the ISEL shortcoming noted above, be conservative if this op is
8243     // likely to be selected as part of a load-modify-store instruction.
8244     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8245            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8246       if (UI->getOpcode() == ISD::STORE)
8247         goto default_case;
8248
8249     // Otherwise use a regular EFLAGS-setting instruction.
8250     switch (Op.getNode()->getOpcode()) {
8251     default: llvm_unreachable("unexpected operator!");
8252     case ISD::SUB: Opcode = X86ISD::SUB; break;
8253     case ISD::OR:  Opcode = X86ISD::OR;  break;
8254     case ISD::XOR: Opcode = X86ISD::XOR; break;
8255     case ISD::AND: Opcode = X86ISD::AND; break;
8256     }
8257
8258     NumOperands = 2;
8259     break;
8260   case X86ISD::ADD:
8261   case X86ISD::SUB:
8262   case X86ISD::INC:
8263   case X86ISD::DEC:
8264   case X86ISD::OR:
8265   case X86ISD::XOR:
8266   case X86ISD::AND:
8267     return SDValue(Op.getNode(), 1);
8268   default:
8269   default_case:
8270     break;
8271   }
8272
8273   if (Opcode == 0)
8274     // Emit a CMP with 0, which is the TEST pattern.
8275     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8276                        DAG.getConstant(0, Op.getValueType()));
8277
8278   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8279   SmallVector<SDValue, 4> Ops;
8280   for (unsigned i = 0; i != NumOperands; ++i)
8281     Ops.push_back(Op.getOperand(i));
8282
8283   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8284   DAG.ReplaceAllUsesWith(Op, New);
8285   return SDValue(New.getNode(), 1);
8286 }
8287
8288 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8289 /// equivalent.
8290 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8291                                    SelectionDAG &DAG) const {
8292   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8293     if (C->getAPIntValue() == 0)
8294       return EmitTest(Op0, X86CC, DAG);
8295
8296   DebugLoc dl = Op0.getDebugLoc();
8297   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8298 }
8299
8300 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8301 /// if it's possible.
8302 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8303                                      DebugLoc dl, SelectionDAG &DAG) const {
8304   SDValue Op0 = And.getOperand(0);
8305   SDValue Op1 = And.getOperand(1);
8306   if (Op0.getOpcode() == ISD::TRUNCATE)
8307     Op0 = Op0.getOperand(0);
8308   if (Op1.getOpcode() == ISD::TRUNCATE)
8309     Op1 = Op1.getOperand(0);
8310
8311   SDValue LHS, RHS;
8312   if (Op1.getOpcode() == ISD::SHL)
8313     std::swap(Op0, Op1);
8314   if (Op0.getOpcode() == ISD::SHL) {
8315     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8316       if (And00C->getZExtValue() == 1) {
8317         // If we looked past a truncate, check that it's only truncating away
8318         // known zeros.
8319         unsigned BitWidth = Op0.getValueSizeInBits();
8320         unsigned AndBitWidth = And.getValueSizeInBits();
8321         if (BitWidth > AndBitWidth) {
8322           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8323           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8324           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8325             return SDValue();
8326         }
8327         LHS = Op1;
8328         RHS = Op0.getOperand(1);
8329       }
8330   } else if (Op1.getOpcode() == ISD::Constant) {
8331     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8332     SDValue AndLHS = Op0;
8333     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8334       LHS = AndLHS.getOperand(0);
8335       RHS = AndLHS.getOperand(1);
8336     }
8337   }
8338
8339   if (LHS.getNode()) {
8340     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8341     // instruction.  Since the shift amount is in-range-or-undefined, we know
8342     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8343     // the encoding for the i16 version is larger than the i32 version.
8344     // Also promote i16 to i32 for performance / code size reason.
8345     if (LHS.getValueType() == MVT::i8 ||
8346         LHS.getValueType() == MVT::i16)
8347       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8348
8349     // If the operand types disagree, extend the shift amount to match.  Since
8350     // BT ignores high bits (like shifts) we can use anyextend.
8351     if (LHS.getValueType() != RHS.getValueType())
8352       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8353
8354     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8355     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8356     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8357                        DAG.getConstant(Cond, MVT::i8), BT);
8358   }
8359
8360   return SDValue();
8361 }
8362
8363 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8364
8365   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8366
8367   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8368   SDValue Op0 = Op.getOperand(0);
8369   SDValue Op1 = Op.getOperand(1);
8370   DebugLoc dl = Op.getDebugLoc();
8371   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8372
8373   // Optimize to BT if possible.
8374   // Lower (X & (1 << N)) == 0 to BT(X, N).
8375   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8376   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8377   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8378       Op1.getOpcode() == ISD::Constant &&
8379       cast<ConstantSDNode>(Op1)->isNullValue() &&
8380       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8381     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8382     if (NewSetCC.getNode())
8383       return NewSetCC;
8384   }
8385
8386   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8387   // these.
8388   if (Op1.getOpcode() == ISD::Constant &&
8389       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8390        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8391       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8392
8393     // If the input is a setcc, then reuse the input setcc or use a new one with
8394     // the inverted condition.
8395     if (Op0.getOpcode() == X86ISD::SETCC) {
8396       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8397       bool Invert = (CC == ISD::SETNE) ^
8398         cast<ConstantSDNode>(Op1)->isNullValue();
8399       if (!Invert) return Op0;
8400
8401       CCode = X86::GetOppositeBranchCondition(CCode);
8402       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8403                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8404     }
8405   }
8406
8407   bool isFP = Op1.getValueType().isFloatingPoint();
8408   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8409   if (X86CC == X86::COND_INVALID)
8410     return SDValue();
8411
8412   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8413   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8414                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8415 }
8416
8417 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8418 // ones, and then concatenate the result back.
8419 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8420   EVT VT = Op.getValueType();
8421
8422   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8423          "Unsupported value type for operation");
8424
8425   int NumElems = VT.getVectorNumElements();
8426   DebugLoc dl = Op.getDebugLoc();
8427   SDValue CC = Op.getOperand(2);
8428   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8429   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8430
8431   // Extract the LHS vectors
8432   SDValue LHS = Op.getOperand(0);
8433   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8434   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8435
8436   // Extract the RHS vectors
8437   SDValue RHS = Op.getOperand(1);
8438   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8439   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8440
8441   // Issue the operation on the smaller types and concatenate the result back
8442   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8443   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8444   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8445                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8446                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8447 }
8448
8449
8450 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8451   SDValue Cond;
8452   SDValue Op0 = Op.getOperand(0);
8453   SDValue Op1 = Op.getOperand(1);
8454   SDValue CC = Op.getOperand(2);
8455   EVT VT = Op.getValueType();
8456   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8457   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8458   DebugLoc dl = Op.getDebugLoc();
8459
8460   if (isFP) {
8461     unsigned SSECC = 8;
8462     EVT EltVT = Op0.getValueType().getVectorElementType();
8463     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8464
8465     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8466     bool Swap = false;
8467
8468     // SSE Condition code mapping:
8469     //  0 - EQ
8470     //  1 - LT
8471     //  2 - LE
8472     //  3 - UNORD
8473     //  4 - NEQ
8474     //  5 - NLT
8475     //  6 - NLE
8476     //  7 - ORD
8477     switch (SetCCOpcode) {
8478     default: break;
8479     case ISD::SETOEQ:
8480     case ISD::SETEQ:  SSECC = 0; break;
8481     case ISD::SETOGT:
8482     case ISD::SETGT: Swap = true; // Fallthrough
8483     case ISD::SETLT:
8484     case ISD::SETOLT: SSECC = 1; break;
8485     case ISD::SETOGE:
8486     case ISD::SETGE: Swap = true; // Fallthrough
8487     case ISD::SETLE:
8488     case ISD::SETOLE: SSECC = 2; break;
8489     case ISD::SETUO:  SSECC = 3; break;
8490     case ISD::SETUNE:
8491     case ISD::SETNE:  SSECC = 4; break;
8492     case ISD::SETULE: Swap = true;
8493     case ISD::SETUGE: SSECC = 5; break;
8494     case ISD::SETULT: Swap = true;
8495     case ISD::SETUGT: SSECC = 6; break;
8496     case ISD::SETO:   SSECC = 7; break;
8497     }
8498     if (Swap)
8499       std::swap(Op0, Op1);
8500
8501     // In the two special cases we can't handle, emit two comparisons.
8502     if (SSECC == 8) {
8503       if (SetCCOpcode == ISD::SETUEQ) {
8504         SDValue UNORD, EQ;
8505         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8506         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8507         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8508       }
8509       else if (SetCCOpcode == ISD::SETONE) {
8510         SDValue ORD, NEQ;
8511         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8512         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8513         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8514       }
8515       llvm_unreachable("Illegal FP comparison");
8516     }
8517     // Handle all other FP comparisons here.
8518     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8519   }
8520
8521   // Break 256-bit integer vector compare into smaller ones.
8522   if (!isFP && VT.getSizeInBits() == 256)
8523     return Lower256IntVSETCC(Op, DAG);
8524
8525   // We are handling one of the integer comparisons here.  Since SSE only has
8526   // GT and EQ comparisons for integer, swapping operands and multiple
8527   // operations may be required for some comparisons.
8528   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8529   bool Swap = false, Invert = false, FlipSigns = false;
8530
8531   switch (VT.getSimpleVT().SimpleTy) {
8532   default: break;
8533   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8534   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8535   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8536   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8537   }
8538
8539   switch (SetCCOpcode) {
8540   default: break;
8541   case ISD::SETNE:  Invert = true;
8542   case ISD::SETEQ:  Opc = EQOpc; break;
8543   case ISD::SETLT:  Swap = true;
8544   case ISD::SETGT:  Opc = GTOpc; break;
8545   case ISD::SETGE:  Swap = true;
8546   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8547   case ISD::SETULT: Swap = true;
8548   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8549   case ISD::SETUGE: Swap = true;
8550   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8551   }
8552   if (Swap)
8553     std::swap(Op0, Op1);
8554
8555   // Check that the operation in question is available (most are plain SSE2,
8556   // but PCMPGTQ and PCMPEQQ have different requirements).
8557   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8558     return SDValue();
8559   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8560     return SDValue();
8561
8562   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8563   // bits of the inputs before performing those operations.
8564   if (FlipSigns) {
8565     EVT EltVT = VT.getVectorElementType();
8566     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8567                                       EltVT);
8568     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8569     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8570                                     SignBits.size());
8571     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8572     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8573   }
8574
8575   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8576
8577   // If the logical-not of the result is required, perform that now.
8578   if (Invert)
8579     Result = DAG.getNOT(dl, Result, VT);
8580
8581   return Result;
8582 }
8583
8584 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8585 static bool isX86LogicalCmp(SDValue Op) {
8586   unsigned Opc = Op.getNode()->getOpcode();
8587   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8588     return true;
8589   if (Op.getResNo() == 1 &&
8590       (Opc == X86ISD::ADD ||
8591        Opc == X86ISD::SUB ||
8592        Opc == X86ISD::ADC ||
8593        Opc == X86ISD::SBB ||
8594        Opc == X86ISD::SMUL ||
8595        Opc == X86ISD::UMUL ||
8596        Opc == X86ISD::INC ||
8597        Opc == X86ISD::DEC ||
8598        Opc == X86ISD::OR ||
8599        Opc == X86ISD::XOR ||
8600        Opc == X86ISD::AND))
8601     return true;
8602
8603   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8604     return true;
8605
8606   return false;
8607 }
8608
8609 static bool isZero(SDValue V) {
8610   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8611   return C && C->isNullValue();
8612 }
8613
8614 static bool isAllOnes(SDValue V) {
8615   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8616   return C && C->isAllOnesValue();
8617 }
8618
8619 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8620   bool addTest = true;
8621   SDValue Cond  = Op.getOperand(0);
8622   SDValue Op1 = Op.getOperand(1);
8623   SDValue Op2 = Op.getOperand(2);
8624   DebugLoc DL = Op.getDebugLoc();
8625   SDValue CC;
8626
8627   if (Cond.getOpcode() == ISD::SETCC) {
8628     SDValue NewCond = LowerSETCC(Cond, DAG);
8629     if (NewCond.getNode())
8630       Cond = NewCond;
8631   }
8632
8633   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8634   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8635   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8636   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8637   if (Cond.getOpcode() == X86ISD::SETCC &&
8638       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8639       isZero(Cond.getOperand(1).getOperand(1))) {
8640     SDValue Cmp = Cond.getOperand(1);
8641
8642     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8643
8644     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8645         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8646       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8647
8648       SDValue CmpOp0 = Cmp.getOperand(0);
8649       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8650                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8651
8652       SDValue Res =   // Res = 0 or -1.
8653         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8654                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8655
8656       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8657         Res = DAG.getNOT(DL, Res, Res.getValueType());
8658
8659       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8660       if (N2C == 0 || !N2C->isNullValue())
8661         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8662       return Res;
8663     }
8664   }
8665
8666   // Look past (and (setcc_carry (cmp ...)), 1).
8667   if (Cond.getOpcode() == ISD::AND &&
8668       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8669     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8670     if (C && C->getAPIntValue() == 1)
8671       Cond = Cond.getOperand(0);
8672   }
8673
8674   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8675   // setting operand in place of the X86ISD::SETCC.
8676   if (Cond.getOpcode() == X86ISD::SETCC ||
8677       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8678     CC = Cond.getOperand(0);
8679
8680     SDValue Cmp = Cond.getOperand(1);
8681     unsigned Opc = Cmp.getOpcode();
8682     EVT VT = Op.getValueType();
8683
8684     bool IllegalFPCMov = false;
8685     if (VT.isFloatingPoint() && !VT.isVector() &&
8686         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8687       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8688
8689     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8690         Opc == X86ISD::BT) { // FIXME
8691       Cond = Cmp;
8692       addTest = false;
8693     }
8694   }
8695
8696   if (addTest) {
8697     // Look pass the truncate.
8698     if (Cond.getOpcode() == ISD::TRUNCATE)
8699       Cond = Cond.getOperand(0);
8700
8701     // We know the result of AND is compared against zero. Try to match
8702     // it to BT.
8703     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8704       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8705       if (NewSetCC.getNode()) {
8706         CC = NewSetCC.getOperand(0);
8707         Cond = NewSetCC.getOperand(1);
8708         addTest = false;
8709       }
8710     }
8711   }
8712
8713   if (addTest) {
8714     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8715     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8716   }
8717
8718   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8719   // a <  b ?  0 : -1 -> RES = setcc_carry
8720   // a >= b ? -1 :  0 -> RES = setcc_carry
8721   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8722   if (Cond.getOpcode() == X86ISD::CMP) {
8723     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8724
8725     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8726         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8727       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8728                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8729       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8730         return DAG.getNOT(DL, Res, Res.getValueType());
8731       return Res;
8732     }
8733   }
8734
8735   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8736   // condition is true.
8737   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8738   SDValue Ops[] = { Op2, Op1, CC, Cond };
8739   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8740 }
8741
8742 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8743 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8744 // from the AND / OR.
8745 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8746   Opc = Op.getOpcode();
8747   if (Opc != ISD::OR && Opc != ISD::AND)
8748     return false;
8749   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8750           Op.getOperand(0).hasOneUse() &&
8751           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8752           Op.getOperand(1).hasOneUse());
8753 }
8754
8755 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8756 // 1 and that the SETCC node has a single use.
8757 static bool isXor1OfSetCC(SDValue Op) {
8758   if (Op.getOpcode() != ISD::XOR)
8759     return false;
8760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8761   if (N1C && N1C->getAPIntValue() == 1) {
8762     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8763       Op.getOperand(0).hasOneUse();
8764   }
8765   return false;
8766 }
8767
8768 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8769   bool addTest = true;
8770   SDValue Chain = Op.getOperand(0);
8771   SDValue Cond  = Op.getOperand(1);
8772   SDValue Dest  = Op.getOperand(2);
8773   DebugLoc dl = Op.getDebugLoc();
8774   SDValue CC;
8775
8776   if (Cond.getOpcode() == ISD::SETCC) {
8777     SDValue NewCond = LowerSETCC(Cond, DAG);
8778     if (NewCond.getNode())
8779       Cond = NewCond;
8780   }
8781 #if 0
8782   // FIXME: LowerXALUO doesn't handle these!!
8783   else if (Cond.getOpcode() == X86ISD::ADD  ||
8784            Cond.getOpcode() == X86ISD::SUB  ||
8785            Cond.getOpcode() == X86ISD::SMUL ||
8786            Cond.getOpcode() == X86ISD::UMUL)
8787     Cond = LowerXALUO(Cond, DAG);
8788 #endif
8789
8790   // Look pass (and (setcc_carry (cmp ...)), 1).
8791   if (Cond.getOpcode() == ISD::AND &&
8792       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8793     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8794     if (C && C->getAPIntValue() == 1)
8795       Cond = Cond.getOperand(0);
8796   }
8797
8798   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8799   // setting operand in place of the X86ISD::SETCC.
8800   if (Cond.getOpcode() == X86ISD::SETCC ||
8801       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8802     CC = Cond.getOperand(0);
8803
8804     SDValue Cmp = Cond.getOperand(1);
8805     unsigned Opc = Cmp.getOpcode();
8806     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8807     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8808       Cond = Cmp;
8809       addTest = false;
8810     } else {
8811       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8812       default: break;
8813       case X86::COND_O:
8814       case X86::COND_B:
8815         // These can only come from an arithmetic instruction with overflow,
8816         // e.g. SADDO, UADDO.
8817         Cond = Cond.getNode()->getOperand(1);
8818         addTest = false;
8819         break;
8820       }
8821     }
8822   } else {
8823     unsigned CondOpc;
8824     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8825       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8826       if (CondOpc == ISD::OR) {
8827         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8828         // two branches instead of an explicit OR instruction with a
8829         // separate test.
8830         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8831             isX86LogicalCmp(Cmp)) {
8832           CC = Cond.getOperand(0).getOperand(0);
8833           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8834                               Chain, Dest, CC, Cmp);
8835           CC = Cond.getOperand(1).getOperand(0);
8836           Cond = Cmp;
8837           addTest = false;
8838         }
8839       } else { // ISD::AND
8840         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8841         // two branches instead of an explicit AND instruction with a
8842         // separate test. However, we only do this if this block doesn't
8843         // have a fall-through edge, because this requires an explicit
8844         // jmp when the condition is false.
8845         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8846             isX86LogicalCmp(Cmp) &&
8847             Op.getNode()->hasOneUse()) {
8848           X86::CondCode CCode =
8849             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8850           CCode = X86::GetOppositeBranchCondition(CCode);
8851           CC = DAG.getConstant(CCode, MVT::i8);
8852           SDNode *User = *Op.getNode()->use_begin();
8853           // Look for an unconditional branch following this conditional branch.
8854           // We need this because we need to reverse the successors in order
8855           // to implement FCMP_OEQ.
8856           if (User->getOpcode() == ISD::BR) {
8857             SDValue FalseBB = User->getOperand(1);
8858             SDNode *NewBR =
8859               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8860             assert(NewBR == User);
8861             (void)NewBR;
8862             Dest = FalseBB;
8863
8864             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8865                                 Chain, Dest, CC, Cmp);
8866             X86::CondCode CCode =
8867               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8868             CCode = X86::GetOppositeBranchCondition(CCode);
8869             CC = DAG.getConstant(CCode, MVT::i8);
8870             Cond = Cmp;
8871             addTest = false;
8872           }
8873         }
8874       }
8875     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8876       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8877       // It should be transformed during dag combiner except when the condition
8878       // is set by a arithmetics with overflow node.
8879       X86::CondCode CCode =
8880         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8881       CCode = X86::GetOppositeBranchCondition(CCode);
8882       CC = DAG.getConstant(CCode, MVT::i8);
8883       Cond = Cond.getOperand(0).getOperand(1);
8884       addTest = false;
8885     }
8886   }
8887
8888   if (addTest) {
8889     // Look pass the truncate.
8890     if (Cond.getOpcode() == ISD::TRUNCATE)
8891       Cond = Cond.getOperand(0);
8892
8893     // We know the result of AND is compared against zero. Try to match
8894     // it to BT.
8895     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8896       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8897       if (NewSetCC.getNode()) {
8898         CC = NewSetCC.getOperand(0);
8899         Cond = NewSetCC.getOperand(1);
8900         addTest = false;
8901       }
8902     }
8903   }
8904
8905   if (addTest) {
8906     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8907     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8908   }
8909   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8910                      Chain, Dest, CC, Cond);
8911 }
8912
8913
8914 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8915 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8916 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8917 // that the guard pages used by the OS virtual memory manager are allocated in
8918 // correct sequence.
8919 SDValue
8920 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8921                                            SelectionDAG &DAG) const {
8922   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8923           EnableSegmentedStacks) &&
8924          "This should be used only on Windows targets or when segmented stacks "
8925          "are being used");
8926   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8927   DebugLoc dl = Op.getDebugLoc();
8928
8929   // Get the inputs.
8930   SDValue Chain = Op.getOperand(0);
8931   SDValue Size  = Op.getOperand(1);
8932   // FIXME: Ensure alignment here
8933
8934   bool Is64Bit = Subtarget->is64Bit();
8935   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8936
8937   if (EnableSegmentedStacks) {
8938     MachineFunction &MF = DAG.getMachineFunction();
8939     MachineRegisterInfo &MRI = MF.getRegInfo();
8940
8941     if (Is64Bit) {
8942       // The 64 bit implementation of segmented stacks needs to clobber both r10
8943       // r11. This makes it impossible to use it along with nested parameters.
8944       const Function *F = MF.getFunction();
8945
8946       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8947            I != E; I++)
8948         if (I->hasNestAttr())
8949           report_fatal_error("Cannot use segmented stacks with functions that "
8950                              "have nested arguments.");
8951     }
8952
8953     const TargetRegisterClass *AddrRegClass =
8954       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8955     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8956     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8957     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8958                                 DAG.getRegister(Vreg, SPTy));
8959     SDValue Ops1[2] = { Value, Chain };
8960     return DAG.getMergeValues(Ops1, 2, dl);
8961   } else {
8962     SDValue Flag;
8963     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8964
8965     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8966     Flag = Chain.getValue(1);
8967     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8968
8969     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8970     Flag = Chain.getValue(1);
8971
8972     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8973
8974     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8975     return DAG.getMergeValues(Ops1, 2, dl);
8976   }
8977 }
8978
8979 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8980   MachineFunction &MF = DAG.getMachineFunction();
8981   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8982
8983   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8984   DebugLoc DL = Op.getDebugLoc();
8985
8986   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8987     // vastart just stores the address of the VarArgsFrameIndex slot into the
8988     // memory location argument.
8989     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8990                                    getPointerTy());
8991     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8992                         MachinePointerInfo(SV), false, false, 0);
8993   }
8994
8995   // __va_list_tag:
8996   //   gp_offset         (0 - 6 * 8)
8997   //   fp_offset         (48 - 48 + 8 * 16)
8998   //   overflow_arg_area (point to parameters coming in memory).
8999   //   reg_save_area
9000   SmallVector<SDValue, 8> MemOps;
9001   SDValue FIN = Op.getOperand(1);
9002   // Store gp_offset
9003   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9004                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9005                                                MVT::i32),
9006                                FIN, MachinePointerInfo(SV), false, false, 0);
9007   MemOps.push_back(Store);
9008
9009   // Store fp_offset
9010   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9011                     FIN, DAG.getIntPtrConstant(4));
9012   Store = DAG.getStore(Op.getOperand(0), DL,
9013                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9014                                        MVT::i32),
9015                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9016   MemOps.push_back(Store);
9017
9018   // Store ptr to overflow_arg_area
9019   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9020                     FIN, DAG.getIntPtrConstant(4));
9021   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9022                                     getPointerTy());
9023   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9024                        MachinePointerInfo(SV, 8),
9025                        false, false, 0);
9026   MemOps.push_back(Store);
9027
9028   // Store ptr to reg_save_area.
9029   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9030                     FIN, DAG.getIntPtrConstant(8));
9031   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9032                                     getPointerTy());
9033   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9034                        MachinePointerInfo(SV, 16), false, false, 0);
9035   MemOps.push_back(Store);
9036   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9037                      &MemOps[0], MemOps.size());
9038 }
9039
9040 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9041   assert(Subtarget->is64Bit() &&
9042          "LowerVAARG only handles 64-bit va_arg!");
9043   assert((Subtarget->isTargetLinux() ||
9044           Subtarget->isTargetDarwin()) &&
9045           "Unhandled target in LowerVAARG");
9046   assert(Op.getNode()->getNumOperands() == 4);
9047   SDValue Chain = Op.getOperand(0);
9048   SDValue SrcPtr = Op.getOperand(1);
9049   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9050   unsigned Align = Op.getConstantOperandVal(3);
9051   DebugLoc dl = Op.getDebugLoc();
9052
9053   EVT ArgVT = Op.getNode()->getValueType(0);
9054   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9055   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9056   uint8_t ArgMode;
9057
9058   // Decide which area this value should be read from.
9059   // TODO: Implement the AMD64 ABI in its entirety. This simple
9060   // selection mechanism works only for the basic types.
9061   if (ArgVT == MVT::f80) {
9062     llvm_unreachable("va_arg for f80 not yet implemented");
9063   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9064     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9065   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9066     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9067   } else {
9068     llvm_unreachable("Unhandled argument type in LowerVAARG");
9069   }
9070
9071   if (ArgMode == 2) {
9072     // Sanity Check: Make sure using fp_offset makes sense.
9073     assert(!UseSoftFloat &&
9074            !(DAG.getMachineFunction()
9075                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9076            Subtarget->hasXMM());
9077   }
9078
9079   // Insert VAARG_64 node into the DAG
9080   // VAARG_64 returns two values: Variable Argument Address, Chain
9081   SmallVector<SDValue, 11> InstOps;
9082   InstOps.push_back(Chain);
9083   InstOps.push_back(SrcPtr);
9084   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9085   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9086   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9087   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9088   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9089                                           VTs, &InstOps[0], InstOps.size(),
9090                                           MVT::i64,
9091                                           MachinePointerInfo(SV),
9092                                           /*Align=*/0,
9093                                           /*Volatile=*/false,
9094                                           /*ReadMem=*/true,
9095                                           /*WriteMem=*/true);
9096   Chain = VAARG.getValue(1);
9097
9098   // Load the next argument and return it
9099   return DAG.getLoad(ArgVT, dl,
9100                      Chain,
9101                      VAARG,
9102                      MachinePointerInfo(),
9103                      false, false, 0);
9104 }
9105
9106 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9107   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9108   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9109   SDValue Chain = Op.getOperand(0);
9110   SDValue DstPtr = Op.getOperand(1);
9111   SDValue SrcPtr = Op.getOperand(2);
9112   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9113   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9114   DebugLoc DL = Op.getDebugLoc();
9115
9116   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9117                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9118                        false,
9119                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9120 }
9121
9122 SDValue
9123 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9124   DebugLoc dl = Op.getDebugLoc();
9125   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9126   switch (IntNo) {
9127   default: return SDValue();    // Don't custom lower most intrinsics.
9128   // Comparison intrinsics.
9129   case Intrinsic::x86_sse_comieq_ss:
9130   case Intrinsic::x86_sse_comilt_ss:
9131   case Intrinsic::x86_sse_comile_ss:
9132   case Intrinsic::x86_sse_comigt_ss:
9133   case Intrinsic::x86_sse_comige_ss:
9134   case Intrinsic::x86_sse_comineq_ss:
9135   case Intrinsic::x86_sse_ucomieq_ss:
9136   case Intrinsic::x86_sse_ucomilt_ss:
9137   case Intrinsic::x86_sse_ucomile_ss:
9138   case Intrinsic::x86_sse_ucomigt_ss:
9139   case Intrinsic::x86_sse_ucomige_ss:
9140   case Intrinsic::x86_sse_ucomineq_ss:
9141   case Intrinsic::x86_sse2_comieq_sd:
9142   case Intrinsic::x86_sse2_comilt_sd:
9143   case Intrinsic::x86_sse2_comile_sd:
9144   case Intrinsic::x86_sse2_comigt_sd:
9145   case Intrinsic::x86_sse2_comige_sd:
9146   case Intrinsic::x86_sse2_comineq_sd:
9147   case Intrinsic::x86_sse2_ucomieq_sd:
9148   case Intrinsic::x86_sse2_ucomilt_sd:
9149   case Intrinsic::x86_sse2_ucomile_sd:
9150   case Intrinsic::x86_sse2_ucomigt_sd:
9151   case Intrinsic::x86_sse2_ucomige_sd:
9152   case Intrinsic::x86_sse2_ucomineq_sd: {
9153     unsigned Opc = 0;
9154     ISD::CondCode CC = ISD::SETCC_INVALID;
9155     switch (IntNo) {
9156     default: break;
9157     case Intrinsic::x86_sse_comieq_ss:
9158     case Intrinsic::x86_sse2_comieq_sd:
9159       Opc = X86ISD::COMI;
9160       CC = ISD::SETEQ;
9161       break;
9162     case Intrinsic::x86_sse_comilt_ss:
9163     case Intrinsic::x86_sse2_comilt_sd:
9164       Opc = X86ISD::COMI;
9165       CC = ISD::SETLT;
9166       break;
9167     case Intrinsic::x86_sse_comile_ss:
9168     case Intrinsic::x86_sse2_comile_sd:
9169       Opc = X86ISD::COMI;
9170       CC = ISD::SETLE;
9171       break;
9172     case Intrinsic::x86_sse_comigt_ss:
9173     case Intrinsic::x86_sse2_comigt_sd:
9174       Opc = X86ISD::COMI;
9175       CC = ISD::SETGT;
9176       break;
9177     case Intrinsic::x86_sse_comige_ss:
9178     case Intrinsic::x86_sse2_comige_sd:
9179       Opc = X86ISD::COMI;
9180       CC = ISD::SETGE;
9181       break;
9182     case Intrinsic::x86_sse_comineq_ss:
9183     case Intrinsic::x86_sse2_comineq_sd:
9184       Opc = X86ISD::COMI;
9185       CC = ISD::SETNE;
9186       break;
9187     case Intrinsic::x86_sse_ucomieq_ss:
9188     case Intrinsic::x86_sse2_ucomieq_sd:
9189       Opc = X86ISD::UCOMI;
9190       CC = ISD::SETEQ;
9191       break;
9192     case Intrinsic::x86_sse_ucomilt_ss:
9193     case Intrinsic::x86_sse2_ucomilt_sd:
9194       Opc = X86ISD::UCOMI;
9195       CC = ISD::SETLT;
9196       break;
9197     case Intrinsic::x86_sse_ucomile_ss:
9198     case Intrinsic::x86_sse2_ucomile_sd:
9199       Opc = X86ISD::UCOMI;
9200       CC = ISD::SETLE;
9201       break;
9202     case Intrinsic::x86_sse_ucomigt_ss:
9203     case Intrinsic::x86_sse2_ucomigt_sd:
9204       Opc = X86ISD::UCOMI;
9205       CC = ISD::SETGT;
9206       break;
9207     case Intrinsic::x86_sse_ucomige_ss:
9208     case Intrinsic::x86_sse2_ucomige_sd:
9209       Opc = X86ISD::UCOMI;
9210       CC = ISD::SETGE;
9211       break;
9212     case Intrinsic::x86_sse_ucomineq_ss:
9213     case Intrinsic::x86_sse2_ucomineq_sd:
9214       Opc = X86ISD::UCOMI;
9215       CC = ISD::SETNE;
9216       break;
9217     }
9218
9219     SDValue LHS = Op.getOperand(1);
9220     SDValue RHS = Op.getOperand(2);
9221     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9222     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9223     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9224     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9225                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9226     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9227   }
9228   // Arithmetic intrinsics.
9229   case Intrinsic::x86_sse3_hadd_ps:
9230   case Intrinsic::x86_sse3_hadd_pd:
9231   case Intrinsic::x86_avx_hadd_ps_256:
9232   case Intrinsic::x86_avx_hadd_pd_256:
9233     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9234                        Op.getOperand(1), Op.getOperand(2));
9235   case Intrinsic::x86_sse3_hsub_ps:
9236   case Intrinsic::x86_sse3_hsub_pd:
9237   case Intrinsic::x86_avx_hsub_ps_256:
9238   case Intrinsic::x86_avx_hsub_pd_256:
9239     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9240                        Op.getOperand(1), Op.getOperand(2));
9241   // ptest and testp intrinsics. The intrinsic these come from are designed to
9242   // return an integer value, not just an instruction so lower it to the ptest
9243   // or testp pattern and a setcc for the result.
9244   case Intrinsic::x86_sse41_ptestz:
9245   case Intrinsic::x86_sse41_ptestc:
9246   case Intrinsic::x86_sse41_ptestnzc:
9247   case Intrinsic::x86_avx_ptestz_256:
9248   case Intrinsic::x86_avx_ptestc_256:
9249   case Intrinsic::x86_avx_ptestnzc_256:
9250   case Intrinsic::x86_avx_vtestz_ps:
9251   case Intrinsic::x86_avx_vtestc_ps:
9252   case Intrinsic::x86_avx_vtestnzc_ps:
9253   case Intrinsic::x86_avx_vtestz_pd:
9254   case Intrinsic::x86_avx_vtestc_pd:
9255   case Intrinsic::x86_avx_vtestnzc_pd:
9256   case Intrinsic::x86_avx_vtestz_ps_256:
9257   case Intrinsic::x86_avx_vtestc_ps_256:
9258   case Intrinsic::x86_avx_vtestnzc_ps_256:
9259   case Intrinsic::x86_avx_vtestz_pd_256:
9260   case Intrinsic::x86_avx_vtestc_pd_256:
9261   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9262     bool IsTestPacked = false;
9263     unsigned X86CC = 0;
9264     switch (IntNo) {
9265     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9266     case Intrinsic::x86_avx_vtestz_ps:
9267     case Intrinsic::x86_avx_vtestz_pd:
9268     case Intrinsic::x86_avx_vtestz_ps_256:
9269     case Intrinsic::x86_avx_vtestz_pd_256:
9270       IsTestPacked = true; // Fallthrough
9271     case Intrinsic::x86_sse41_ptestz:
9272     case Intrinsic::x86_avx_ptestz_256:
9273       // ZF = 1
9274       X86CC = X86::COND_E;
9275       break;
9276     case Intrinsic::x86_avx_vtestc_ps:
9277     case Intrinsic::x86_avx_vtestc_pd:
9278     case Intrinsic::x86_avx_vtestc_ps_256:
9279     case Intrinsic::x86_avx_vtestc_pd_256:
9280       IsTestPacked = true; // Fallthrough
9281     case Intrinsic::x86_sse41_ptestc:
9282     case Intrinsic::x86_avx_ptestc_256:
9283       // CF = 1
9284       X86CC = X86::COND_B;
9285       break;
9286     case Intrinsic::x86_avx_vtestnzc_ps:
9287     case Intrinsic::x86_avx_vtestnzc_pd:
9288     case Intrinsic::x86_avx_vtestnzc_ps_256:
9289     case Intrinsic::x86_avx_vtestnzc_pd_256:
9290       IsTestPacked = true; // Fallthrough
9291     case Intrinsic::x86_sse41_ptestnzc:
9292     case Intrinsic::x86_avx_ptestnzc_256:
9293       // ZF and CF = 0
9294       X86CC = X86::COND_A;
9295       break;
9296     }
9297
9298     SDValue LHS = Op.getOperand(1);
9299     SDValue RHS = Op.getOperand(2);
9300     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9301     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9302     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9303     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9304     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9305   }
9306
9307   // Fix vector shift instructions where the last operand is a non-immediate
9308   // i32 value.
9309   case Intrinsic::x86_sse2_pslli_w:
9310   case Intrinsic::x86_sse2_pslli_d:
9311   case Intrinsic::x86_sse2_pslli_q:
9312   case Intrinsic::x86_sse2_psrli_w:
9313   case Intrinsic::x86_sse2_psrli_d:
9314   case Intrinsic::x86_sse2_psrli_q:
9315   case Intrinsic::x86_sse2_psrai_w:
9316   case Intrinsic::x86_sse2_psrai_d:
9317   case Intrinsic::x86_mmx_pslli_w:
9318   case Intrinsic::x86_mmx_pslli_d:
9319   case Intrinsic::x86_mmx_pslli_q:
9320   case Intrinsic::x86_mmx_psrli_w:
9321   case Intrinsic::x86_mmx_psrli_d:
9322   case Intrinsic::x86_mmx_psrli_q:
9323   case Intrinsic::x86_mmx_psrai_w:
9324   case Intrinsic::x86_mmx_psrai_d: {
9325     SDValue ShAmt = Op.getOperand(2);
9326     if (isa<ConstantSDNode>(ShAmt))
9327       return SDValue();
9328
9329     unsigned NewIntNo = 0;
9330     EVT ShAmtVT = MVT::v4i32;
9331     switch (IntNo) {
9332     case Intrinsic::x86_sse2_pslli_w:
9333       NewIntNo = Intrinsic::x86_sse2_psll_w;
9334       break;
9335     case Intrinsic::x86_sse2_pslli_d:
9336       NewIntNo = Intrinsic::x86_sse2_psll_d;
9337       break;
9338     case Intrinsic::x86_sse2_pslli_q:
9339       NewIntNo = Intrinsic::x86_sse2_psll_q;
9340       break;
9341     case Intrinsic::x86_sse2_psrli_w:
9342       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9343       break;
9344     case Intrinsic::x86_sse2_psrli_d:
9345       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9346       break;
9347     case Intrinsic::x86_sse2_psrli_q:
9348       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9349       break;
9350     case Intrinsic::x86_sse2_psrai_w:
9351       NewIntNo = Intrinsic::x86_sse2_psra_w;
9352       break;
9353     case Intrinsic::x86_sse2_psrai_d:
9354       NewIntNo = Intrinsic::x86_sse2_psra_d;
9355       break;
9356     default: {
9357       ShAmtVT = MVT::v2i32;
9358       switch (IntNo) {
9359       case Intrinsic::x86_mmx_pslli_w:
9360         NewIntNo = Intrinsic::x86_mmx_psll_w;
9361         break;
9362       case Intrinsic::x86_mmx_pslli_d:
9363         NewIntNo = Intrinsic::x86_mmx_psll_d;
9364         break;
9365       case Intrinsic::x86_mmx_pslli_q:
9366         NewIntNo = Intrinsic::x86_mmx_psll_q;
9367         break;
9368       case Intrinsic::x86_mmx_psrli_w:
9369         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9370         break;
9371       case Intrinsic::x86_mmx_psrli_d:
9372         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9373         break;
9374       case Intrinsic::x86_mmx_psrli_q:
9375         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9376         break;
9377       case Intrinsic::x86_mmx_psrai_w:
9378         NewIntNo = Intrinsic::x86_mmx_psra_w;
9379         break;
9380       case Intrinsic::x86_mmx_psrai_d:
9381         NewIntNo = Intrinsic::x86_mmx_psra_d;
9382         break;
9383       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9384       }
9385       break;
9386     }
9387     }
9388
9389     // The vector shift intrinsics with scalars uses 32b shift amounts but
9390     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9391     // to be zero.
9392     SDValue ShOps[4];
9393     ShOps[0] = ShAmt;
9394     ShOps[1] = DAG.getConstant(0, MVT::i32);
9395     if (ShAmtVT == MVT::v4i32) {
9396       ShOps[2] = DAG.getUNDEF(MVT::i32);
9397       ShOps[3] = DAG.getUNDEF(MVT::i32);
9398       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9399     } else {
9400       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9401 // FIXME this must be lowered to get rid of the invalid type.
9402     }
9403
9404     EVT VT = Op.getValueType();
9405     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9406     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9407                        DAG.getConstant(NewIntNo, MVT::i32),
9408                        Op.getOperand(1), ShAmt);
9409   }
9410   }
9411 }
9412
9413 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9414                                            SelectionDAG &DAG) const {
9415   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9416   MFI->setReturnAddressIsTaken(true);
9417
9418   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9419   DebugLoc dl = Op.getDebugLoc();
9420
9421   if (Depth > 0) {
9422     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9423     SDValue Offset =
9424       DAG.getConstant(TD->getPointerSize(),
9425                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9426     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9427                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9428                                    FrameAddr, Offset),
9429                        MachinePointerInfo(), false, false, 0);
9430   }
9431
9432   // Just load the return address.
9433   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9434   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9435                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9436 }
9437
9438 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9439   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9440   MFI->setFrameAddressIsTaken(true);
9441
9442   EVT VT = Op.getValueType();
9443   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9444   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9445   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9446   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9447   while (Depth--)
9448     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9449                             MachinePointerInfo(),
9450                             false, false, 0);
9451   return FrameAddr;
9452 }
9453
9454 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9455                                                      SelectionDAG &DAG) const {
9456   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9457 }
9458
9459 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9460   MachineFunction &MF = DAG.getMachineFunction();
9461   SDValue Chain     = Op.getOperand(0);
9462   SDValue Offset    = Op.getOperand(1);
9463   SDValue Handler   = Op.getOperand(2);
9464   DebugLoc dl       = Op.getDebugLoc();
9465
9466   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9467                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9468                                      getPointerTy());
9469   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9470
9471   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9472                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9473   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9474   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9475                        false, false, 0);
9476   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9477   MF.getRegInfo().addLiveOut(StoreAddrReg);
9478
9479   return DAG.getNode(X86ISD::EH_RETURN, dl,
9480                      MVT::Other,
9481                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9482 }
9483
9484 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9485                                                   SelectionDAG &DAG) const {
9486   return Op.getOperand(0);
9487 }
9488
9489 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9490                                                 SelectionDAG &DAG) const {
9491   SDValue Root = Op.getOperand(0);
9492   SDValue Trmp = Op.getOperand(1); // trampoline
9493   SDValue FPtr = Op.getOperand(2); // nested function
9494   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9495   DebugLoc dl  = Op.getDebugLoc();
9496
9497   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9498
9499   if (Subtarget->is64Bit()) {
9500     SDValue OutChains[6];
9501
9502     // Large code-model.
9503     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9504     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9505
9506     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9507     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9508
9509     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9510
9511     // Load the pointer to the nested function into R11.
9512     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9513     SDValue Addr = Trmp;
9514     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9515                                 Addr, MachinePointerInfo(TrmpAddr),
9516                                 false, false, 0);
9517
9518     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9519                        DAG.getConstant(2, MVT::i64));
9520     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9521                                 MachinePointerInfo(TrmpAddr, 2),
9522                                 false, false, 2);
9523
9524     // Load the 'nest' parameter value into R10.
9525     // R10 is specified in X86CallingConv.td
9526     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9527     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9528                        DAG.getConstant(10, MVT::i64));
9529     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9530                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9531                                 false, false, 0);
9532
9533     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9534                        DAG.getConstant(12, MVT::i64));
9535     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9536                                 MachinePointerInfo(TrmpAddr, 12),
9537                                 false, false, 2);
9538
9539     // Jump to the nested function.
9540     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9541     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9542                        DAG.getConstant(20, MVT::i64));
9543     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9544                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9545                                 false, false, 0);
9546
9547     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9549                        DAG.getConstant(22, MVT::i64));
9550     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9551                                 MachinePointerInfo(TrmpAddr, 22),
9552                                 false, false, 0);
9553
9554     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9555   } else {
9556     const Function *Func =
9557       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9558     CallingConv::ID CC = Func->getCallingConv();
9559     unsigned NestReg;
9560
9561     switch (CC) {
9562     default:
9563       llvm_unreachable("Unsupported calling convention");
9564     case CallingConv::C:
9565     case CallingConv::X86_StdCall: {
9566       // Pass 'nest' parameter in ECX.
9567       // Must be kept in sync with X86CallingConv.td
9568       NestReg = X86::ECX;
9569
9570       // Check that ECX wasn't needed by an 'inreg' parameter.
9571       FunctionType *FTy = Func->getFunctionType();
9572       const AttrListPtr &Attrs = Func->getAttributes();
9573
9574       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9575         unsigned InRegCount = 0;
9576         unsigned Idx = 1;
9577
9578         for (FunctionType::param_iterator I = FTy->param_begin(),
9579              E = FTy->param_end(); I != E; ++I, ++Idx)
9580           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9581             // FIXME: should only count parameters that are lowered to integers.
9582             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9583
9584         if (InRegCount > 2) {
9585           report_fatal_error("Nest register in use - reduce number of inreg"
9586                              " parameters!");
9587         }
9588       }
9589       break;
9590     }
9591     case CallingConv::X86_FastCall:
9592     case CallingConv::X86_ThisCall:
9593     case CallingConv::Fast:
9594       // Pass 'nest' parameter in EAX.
9595       // Must be kept in sync with X86CallingConv.td
9596       NestReg = X86::EAX;
9597       break;
9598     }
9599
9600     SDValue OutChains[4];
9601     SDValue Addr, Disp;
9602
9603     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9604                        DAG.getConstant(10, MVT::i32));
9605     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9606
9607     // This is storing the opcode for MOV32ri.
9608     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9609     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9610     OutChains[0] = DAG.getStore(Root, dl,
9611                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9612                                 Trmp, MachinePointerInfo(TrmpAddr),
9613                                 false, false, 0);
9614
9615     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9616                        DAG.getConstant(1, MVT::i32));
9617     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9618                                 MachinePointerInfo(TrmpAddr, 1),
9619                                 false, false, 1);
9620
9621     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9622     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9623                        DAG.getConstant(5, MVT::i32));
9624     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9625                                 MachinePointerInfo(TrmpAddr, 5),
9626                                 false, false, 1);
9627
9628     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9629                        DAG.getConstant(6, MVT::i32));
9630     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9631                                 MachinePointerInfo(TrmpAddr, 6),
9632                                 false, false, 1);
9633
9634     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9635   }
9636 }
9637
9638 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9639                                             SelectionDAG &DAG) const {
9640   /*
9641    The rounding mode is in bits 11:10 of FPSR, and has the following
9642    settings:
9643      00 Round to nearest
9644      01 Round to -inf
9645      10 Round to +inf
9646      11 Round to 0
9647
9648   FLT_ROUNDS, on the other hand, expects the following:
9649     -1 Undefined
9650      0 Round to 0
9651      1 Round to nearest
9652      2 Round to +inf
9653      3 Round to -inf
9654
9655   To perform the conversion, we do:
9656     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9657   */
9658
9659   MachineFunction &MF = DAG.getMachineFunction();
9660   const TargetMachine &TM = MF.getTarget();
9661   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9662   unsigned StackAlignment = TFI.getStackAlignment();
9663   EVT VT = Op.getValueType();
9664   DebugLoc DL = Op.getDebugLoc();
9665
9666   // Save FP Control Word to stack slot
9667   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9668   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9669
9670
9671   MachineMemOperand *MMO =
9672    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9673                            MachineMemOperand::MOStore, 2, 2);
9674
9675   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9676   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9677                                           DAG.getVTList(MVT::Other),
9678                                           Ops, 2, MVT::i16, MMO);
9679
9680   // Load FP Control Word from stack slot
9681   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9682                             MachinePointerInfo(), false, false, 0);
9683
9684   // Transform as necessary
9685   SDValue CWD1 =
9686     DAG.getNode(ISD::SRL, DL, MVT::i16,
9687                 DAG.getNode(ISD::AND, DL, MVT::i16,
9688                             CWD, DAG.getConstant(0x800, MVT::i16)),
9689                 DAG.getConstant(11, MVT::i8));
9690   SDValue CWD2 =
9691     DAG.getNode(ISD::SRL, DL, MVT::i16,
9692                 DAG.getNode(ISD::AND, DL, MVT::i16,
9693                             CWD, DAG.getConstant(0x400, MVT::i16)),
9694                 DAG.getConstant(9, MVT::i8));
9695
9696   SDValue RetVal =
9697     DAG.getNode(ISD::AND, DL, MVT::i16,
9698                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9699                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9700                             DAG.getConstant(1, MVT::i16)),
9701                 DAG.getConstant(3, MVT::i16));
9702
9703
9704   return DAG.getNode((VT.getSizeInBits() < 16 ?
9705                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9706 }
9707
9708 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9709   EVT VT = Op.getValueType();
9710   EVT OpVT = VT;
9711   unsigned NumBits = VT.getSizeInBits();
9712   DebugLoc dl = Op.getDebugLoc();
9713
9714   Op = Op.getOperand(0);
9715   if (VT == MVT::i8) {
9716     // Zero extend to i32 since there is not an i8 bsr.
9717     OpVT = MVT::i32;
9718     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9719   }
9720
9721   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9722   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9723   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9724
9725   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9726   SDValue Ops[] = {
9727     Op,
9728     DAG.getConstant(NumBits+NumBits-1, OpVT),
9729     DAG.getConstant(X86::COND_E, MVT::i8),
9730     Op.getValue(1)
9731   };
9732   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9733
9734   // Finally xor with NumBits-1.
9735   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9736
9737   if (VT == MVT::i8)
9738     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9739   return Op;
9740 }
9741
9742 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9743   EVT VT = Op.getValueType();
9744   EVT OpVT = VT;
9745   unsigned NumBits = VT.getSizeInBits();
9746   DebugLoc dl = Op.getDebugLoc();
9747
9748   Op = Op.getOperand(0);
9749   if (VT == MVT::i8) {
9750     OpVT = MVT::i32;
9751     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9752   }
9753
9754   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9755   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9756   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9757
9758   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9759   SDValue Ops[] = {
9760     Op,
9761     DAG.getConstant(NumBits, OpVT),
9762     DAG.getConstant(X86::COND_E, MVT::i8),
9763     Op.getValue(1)
9764   };
9765   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9766
9767   if (VT == MVT::i8)
9768     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9769   return Op;
9770 }
9771
9772 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9773 // ones, and then concatenate the result back.
9774 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9775   EVT VT = Op.getValueType();
9776
9777   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9778          "Unsupported value type for operation");
9779
9780   int NumElems = VT.getVectorNumElements();
9781   DebugLoc dl = Op.getDebugLoc();
9782   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9783   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9784
9785   // Extract the LHS vectors
9786   SDValue LHS = Op.getOperand(0);
9787   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9788   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9789
9790   // Extract the RHS vectors
9791   SDValue RHS = Op.getOperand(1);
9792   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9793   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9794
9795   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9796   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9797
9798   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9799                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9800                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9801 }
9802
9803 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9804   assert(Op.getValueType().getSizeInBits() == 256 &&
9805          Op.getValueType().isInteger() &&
9806          "Only handle AVX 256-bit vector integer operation");
9807   return Lower256IntArith(Op, DAG);
9808 }
9809
9810 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9811   assert(Op.getValueType().getSizeInBits() == 256 &&
9812          Op.getValueType().isInteger() &&
9813          "Only handle AVX 256-bit vector integer operation");
9814   return Lower256IntArith(Op, DAG);
9815 }
9816
9817 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9818   EVT VT = Op.getValueType();
9819
9820   // Decompose 256-bit ops into smaller 128-bit ops.
9821   if (VT.getSizeInBits() == 256)
9822     return Lower256IntArith(Op, DAG);
9823
9824   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9825   DebugLoc dl = Op.getDebugLoc();
9826
9827   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9828   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9829   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9830   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9831   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9832   //
9833   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9834   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9835   //  return AloBlo + AloBhi + AhiBlo;
9836
9837   SDValue A = Op.getOperand(0);
9838   SDValue B = Op.getOperand(1);
9839
9840   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9841                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9842                        A, DAG.getConstant(32, MVT::i32));
9843   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9844                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9845                        B, DAG.getConstant(32, MVT::i32));
9846   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9847                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9848                        A, B);
9849   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9850                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9851                        A, Bhi);
9852   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9853                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9854                        Ahi, B);
9855   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9856                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9857                        AloBhi, DAG.getConstant(32, MVT::i32));
9858   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9859                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9860                        AhiBlo, DAG.getConstant(32, MVT::i32));
9861   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9862   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9863   return Res;
9864 }
9865
9866 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9867
9868   EVT VT = Op.getValueType();
9869   DebugLoc dl = Op.getDebugLoc();
9870   SDValue R = Op.getOperand(0);
9871   SDValue Amt = Op.getOperand(1);
9872   LLVMContext *Context = DAG.getContext();
9873
9874   if (!Subtarget->hasXMMInt())
9875     return SDValue();
9876
9877   // Decompose 256-bit shifts into smaller 128-bit shifts.
9878   if (VT.getSizeInBits() == 256) {
9879     int NumElems = VT.getVectorNumElements();
9880     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9881     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9882
9883     // Extract the two vectors
9884     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9885     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9886                                      DAG, dl);
9887
9888     // Recreate the shift amount vectors
9889     SDValue Amt1, Amt2;
9890     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9891       // Constant shift amount
9892       SmallVector<SDValue, 4> Amt1Csts;
9893       SmallVector<SDValue, 4> Amt2Csts;
9894       for (int i = 0; i < NumElems/2; ++i)
9895         Amt1Csts.push_back(Amt->getOperand(i));
9896       for (int i = NumElems/2; i < NumElems; ++i)
9897         Amt2Csts.push_back(Amt->getOperand(i));
9898
9899       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9900                                  &Amt1Csts[0], NumElems/2);
9901       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9902                                  &Amt2Csts[0], NumElems/2);
9903     } else {
9904       // Variable shift amount
9905       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9906       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9907                                  DAG, dl);
9908     }
9909
9910     // Issue new vector shifts for the smaller types
9911     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9912     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9913
9914     // Concatenate the result back
9915     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9916   }
9917
9918   // Optimize shl/srl/sra with constant shift amount.
9919   if (isSplatVector(Amt.getNode())) {
9920     SDValue SclrAmt = Amt->getOperand(0);
9921     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9922       uint64_t ShiftAmt = C->getZExtValue();
9923
9924       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9925        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9926                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9927                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9928
9929       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9930        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9931                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9932                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9933
9934       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9935        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9936                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9937                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9938
9939       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9940        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9941                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9942                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9943
9944       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9945        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9946                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9947                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9948
9949       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9950        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9951                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9952                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9953
9954       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9955        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9956                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9957                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9958
9959       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9960        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9961                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9962                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9963     }
9964   }
9965
9966   // Lower SHL with variable shift amount.
9967   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9968     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9969                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9970                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9971
9972     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9973
9974     std::vector<Constant*> CV(4, CI);
9975     Constant *C = ConstantVector::get(CV);
9976     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9977     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9978                                  MachinePointerInfo::getConstantPool(),
9979                                  false, false, 16);
9980
9981     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9982     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9983     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9984     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9985   }
9986   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9987     // a = a << 5;
9988     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9989                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9990                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9991
9992     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9993     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9994
9995     std::vector<Constant*> CVM1(16, CM1);
9996     std::vector<Constant*> CVM2(16, CM2);
9997     Constant *C = ConstantVector::get(CVM1);
9998     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9999     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10000                             MachinePointerInfo::getConstantPool(),
10001                             false, false, 16);
10002
10003     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10004     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10005     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10006                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10007                     DAG.getConstant(4, MVT::i32));
10008     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10009     // a += a
10010     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10011
10012     C = ConstantVector::get(CVM2);
10013     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10014     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10015                     MachinePointerInfo::getConstantPool(),
10016                     false, false, 16);
10017
10018     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10019     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10020     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10021                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10022                     DAG.getConstant(2, MVT::i32));
10023     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10024     // a += a
10025     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10026
10027     // return pblendv(r, r+r, a);
10028     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10029                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10030     return R;
10031   }
10032   return SDValue();
10033 }
10034
10035 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10036   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10037   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10038   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10039   // has only one use.
10040   SDNode *N = Op.getNode();
10041   SDValue LHS = N->getOperand(0);
10042   SDValue RHS = N->getOperand(1);
10043   unsigned BaseOp = 0;
10044   unsigned Cond = 0;
10045   DebugLoc DL = Op.getDebugLoc();
10046   switch (Op.getOpcode()) {
10047   default: llvm_unreachable("Unknown ovf instruction!");
10048   case ISD::SADDO:
10049     // A subtract of one will be selected as a INC. Note that INC doesn't
10050     // set CF, so we can't do this for UADDO.
10051     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10052       if (C->isOne()) {
10053         BaseOp = X86ISD::INC;
10054         Cond = X86::COND_O;
10055         break;
10056       }
10057     BaseOp = X86ISD::ADD;
10058     Cond = X86::COND_O;
10059     break;
10060   case ISD::UADDO:
10061     BaseOp = X86ISD::ADD;
10062     Cond = X86::COND_B;
10063     break;
10064   case ISD::SSUBO:
10065     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10066     // set CF, so we can't do this for USUBO.
10067     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10068       if (C->isOne()) {
10069         BaseOp = X86ISD::DEC;
10070         Cond = X86::COND_O;
10071         break;
10072       }
10073     BaseOp = X86ISD::SUB;
10074     Cond = X86::COND_O;
10075     break;
10076   case ISD::USUBO:
10077     BaseOp = X86ISD::SUB;
10078     Cond = X86::COND_B;
10079     break;
10080   case ISD::SMULO:
10081     BaseOp = X86ISD::SMUL;
10082     Cond = X86::COND_O;
10083     break;
10084   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10085     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10086                                  MVT::i32);
10087     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10088
10089     SDValue SetCC =
10090       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10091                   DAG.getConstant(X86::COND_O, MVT::i32),
10092                   SDValue(Sum.getNode(), 2));
10093
10094     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10095   }
10096   }
10097
10098   // Also sets EFLAGS.
10099   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10100   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10101
10102   SDValue SetCC =
10103     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10104                 DAG.getConstant(Cond, MVT::i32),
10105                 SDValue(Sum.getNode(), 1));
10106
10107   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10108 }
10109
10110 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10111   DebugLoc dl = Op.getDebugLoc();
10112   SDNode* Node = Op.getNode();
10113   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10114   EVT VT = Node->getValueType(0);
10115   if (Subtarget->hasXMMInt() && VT.isVector()) {
10116     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10117                         ExtraVT.getScalarType().getSizeInBits();
10118     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10119
10120     unsigned SHLIntrinsicsID = 0;
10121     unsigned SRAIntrinsicsID = 0;
10122     switch (VT.getSimpleVT().SimpleTy) {
10123       default:
10124         return SDValue();
10125       case MVT::v4i32: {
10126         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10127         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10128         break;
10129       }
10130       case MVT::v8i16: {
10131         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10132         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10133         break;
10134       }
10135     }
10136
10137     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10138                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10139                          Node->getOperand(0), ShAmt);
10140
10141     // In case of 1 bit sext, no need to shr
10142     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10143
10144     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10145                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10146                        Tmp1, ShAmt);
10147   }
10148
10149   return SDValue();
10150 }
10151
10152
10153 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10154   DebugLoc dl = Op.getDebugLoc();
10155
10156   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10157   // There isn't any reason to disable it if the target processor supports it.
10158   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10159     SDValue Chain = Op.getOperand(0);
10160     SDValue Zero = DAG.getConstant(0, MVT::i32);
10161     SDValue Ops[] = {
10162       DAG.getRegister(X86::ESP, MVT::i32), // Base
10163       DAG.getTargetConstant(1, MVT::i8),   // Scale
10164       DAG.getRegister(0, MVT::i32),        // Index
10165       DAG.getTargetConstant(0, MVT::i32),  // Disp
10166       DAG.getRegister(0, MVT::i32),        // Segment.
10167       Zero,
10168       Chain
10169     };
10170     SDNode *Res =
10171       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10172                           array_lengthof(Ops));
10173     return SDValue(Res, 0);
10174   }
10175
10176   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10177   if (!isDev)
10178     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10179
10180   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10181   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10182   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10183   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10184
10185   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10186   if (!Op1 && !Op2 && !Op3 && Op4)
10187     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10188
10189   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10190   if (Op1 && !Op2 && !Op3 && !Op4)
10191     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10192
10193   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10194   //           (MFENCE)>;
10195   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10196 }
10197
10198 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10199                                              SelectionDAG &DAG) const {
10200   DebugLoc dl = Op.getDebugLoc();
10201   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10202     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10203   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10204     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10205
10206   // The only fence that needs an instruction is a sequentially-consistent
10207   // cross-thread fence.
10208   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10209     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10210     // no-sse2). There isn't any reason to disable it if the target processor
10211     // supports it.
10212     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10213       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10214
10215     SDValue Chain = Op.getOperand(0);
10216     SDValue Zero = DAG.getConstant(0, MVT::i32);
10217     SDValue Ops[] = {
10218       DAG.getRegister(X86::ESP, MVT::i32), // Base
10219       DAG.getTargetConstant(1, MVT::i8),   // Scale
10220       DAG.getRegister(0, MVT::i32),        // Index
10221       DAG.getTargetConstant(0, MVT::i32),  // Disp
10222       DAG.getRegister(0, MVT::i32),        // Segment.
10223       Zero,
10224       Chain
10225     };
10226     SDNode *Res =
10227       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10228                          array_lengthof(Ops));
10229     return SDValue(Res, 0);
10230   }
10231
10232   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10233   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10234 }
10235
10236
10237 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10238   EVT T = Op.getValueType();
10239   DebugLoc DL = Op.getDebugLoc();
10240   unsigned Reg = 0;
10241   unsigned size = 0;
10242   switch(T.getSimpleVT().SimpleTy) {
10243   default:
10244     assert(false && "Invalid value type!");
10245   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10246   case MVT::i16: Reg = X86::AX;  size = 2; break;
10247   case MVT::i32: Reg = X86::EAX; size = 4; break;
10248   case MVT::i64:
10249     assert(Subtarget->is64Bit() && "Node not type legal!");
10250     Reg = X86::RAX; size = 8;
10251     break;
10252   }
10253   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10254                                     Op.getOperand(2), SDValue());
10255   SDValue Ops[] = { cpIn.getValue(0),
10256                     Op.getOperand(1),
10257                     Op.getOperand(3),
10258                     DAG.getTargetConstant(size, MVT::i8),
10259                     cpIn.getValue(1) };
10260   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10261   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10262   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10263                                            Ops, 5, T, MMO);
10264   SDValue cpOut =
10265     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10266   return cpOut;
10267 }
10268
10269 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10270                                                  SelectionDAG &DAG) const {
10271   assert(Subtarget->is64Bit() && "Result not type legalized?");
10272   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10273   SDValue TheChain = Op.getOperand(0);
10274   DebugLoc dl = Op.getDebugLoc();
10275   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10276   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10277   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10278                                    rax.getValue(2));
10279   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10280                             DAG.getConstant(32, MVT::i8));
10281   SDValue Ops[] = {
10282     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10283     rdx.getValue(1)
10284   };
10285   return DAG.getMergeValues(Ops, 2, dl);
10286 }
10287
10288 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10289                                             SelectionDAG &DAG) const {
10290   EVT SrcVT = Op.getOperand(0).getValueType();
10291   EVT DstVT = Op.getValueType();
10292   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10293          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10294   assert((DstVT == MVT::i64 ||
10295           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10296          "Unexpected custom BITCAST");
10297   // i64 <=> MMX conversions are Legal.
10298   if (SrcVT==MVT::i64 && DstVT.isVector())
10299     return Op;
10300   if (DstVT==MVT::i64 && SrcVT.isVector())
10301     return Op;
10302   // MMX <=> MMX conversions are Legal.
10303   if (SrcVT.isVector() && DstVT.isVector())
10304     return Op;
10305   // All other conversions need to be expanded.
10306   return SDValue();
10307 }
10308
10309 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10310   SDNode *Node = Op.getNode();
10311   DebugLoc dl = Node->getDebugLoc();
10312   EVT T = Node->getValueType(0);
10313   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10314                               DAG.getConstant(0, T), Node->getOperand(2));
10315   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10316                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10317                        Node->getOperand(0),
10318                        Node->getOperand(1), negOp,
10319                        cast<AtomicSDNode>(Node)->getSrcValue(),
10320                        cast<AtomicSDNode>(Node)->getAlignment(),
10321                        cast<AtomicSDNode>(Node)->getOrdering(),
10322                        cast<AtomicSDNode>(Node)->getSynchScope());
10323 }
10324
10325 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10326   SDNode *Node = Op.getNode();
10327   DebugLoc dl = Node->getDebugLoc();
10328   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10329
10330   // Convert seq_cst store -> xchg
10331   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10332   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10333   //        (The only way to get a 16-byte store is cmpxchg16b)
10334   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10335   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10336       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10337     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10338                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10339                                  Node->getOperand(0),
10340                                  Node->getOperand(1), Node->getOperand(2),
10341                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10342                                  cast<AtomicSDNode>(Node)->getOrdering(),
10343                                  cast<AtomicSDNode>(Node)->getSynchScope());
10344     return Swap.getValue(1);
10345   }
10346   // Other atomic stores have a simple pattern.
10347   return Op;
10348 }
10349
10350 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10351   EVT VT = Op.getNode()->getValueType(0);
10352
10353   // Let legalize expand this if it isn't a legal type yet.
10354   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10355     return SDValue();
10356
10357   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10358
10359   unsigned Opc;
10360   bool ExtraOp = false;
10361   switch (Op.getOpcode()) {
10362   default: assert(0 && "Invalid code");
10363   case ISD::ADDC: Opc = X86ISD::ADD; break;
10364   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10365   case ISD::SUBC: Opc = X86ISD::SUB; break;
10366   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10367   }
10368
10369   if (!ExtraOp)
10370     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10371                        Op.getOperand(1));
10372   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10373                      Op.getOperand(1), Op.getOperand(2));
10374 }
10375
10376 /// LowerOperation - Provide custom lowering hooks for some operations.
10377 ///
10378 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10379   switch (Op.getOpcode()) {
10380   default: llvm_unreachable("Should not custom lower this!");
10381   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10382   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10383   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10384   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10385   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10386   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10387   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10388   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10389   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10390   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10391   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10392   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10393   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10394   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10395   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10396   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10397   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10398   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10399   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10400   case ISD::SHL_PARTS:
10401   case ISD::SRA_PARTS:
10402   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10403   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10404   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10405   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10406   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10407   case ISD::FABS:               return LowerFABS(Op, DAG);
10408   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10409   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10410   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10411   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10412   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10413   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10414   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10415   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10416   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10417   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10418   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10419   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10420   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10421   case ISD::FRAME_TO_ARGS_OFFSET:
10422                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10423   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10424   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10425   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10426   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10427   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10428   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10429   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10430   case ISD::MUL:                return LowerMUL(Op, DAG);
10431   case ISD::SRA:
10432   case ISD::SRL:
10433   case ISD::SHL:                return LowerShift(Op, DAG);
10434   case ISD::SADDO:
10435   case ISD::UADDO:
10436   case ISD::SSUBO:
10437   case ISD::USUBO:
10438   case ISD::SMULO:
10439   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10440   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10441   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10442   case ISD::ADDC:
10443   case ISD::ADDE:
10444   case ISD::SUBC:
10445   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10446   case ISD::ADD:                return LowerADD(Op, DAG);
10447   case ISD::SUB:                return LowerSUB(Op, DAG);
10448   }
10449 }
10450
10451 static void ReplaceATOMIC_LOAD(SDNode *Node,
10452                                   SmallVectorImpl<SDValue> &Results,
10453                                   SelectionDAG &DAG) {
10454   DebugLoc dl = Node->getDebugLoc();
10455   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10456
10457   // Convert wide load -> cmpxchg8b/cmpxchg16b
10458   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10459   //        (The only way to get a 16-byte load is cmpxchg16b)
10460   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10461   SDValue Zero = DAG.getConstant(0, VT);
10462   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10463                                Node->getOperand(0),
10464                                Node->getOperand(1), Zero, Zero,
10465                                cast<AtomicSDNode>(Node)->getMemOperand(),
10466                                cast<AtomicSDNode>(Node)->getOrdering(),
10467                                cast<AtomicSDNode>(Node)->getSynchScope());
10468   Results.push_back(Swap.getValue(0));
10469   Results.push_back(Swap.getValue(1));
10470 }
10471
10472 void X86TargetLowering::
10473 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10474                         SelectionDAG &DAG, unsigned NewOp) const {
10475   EVT T = Node->getValueType(0);
10476   DebugLoc dl = Node->getDebugLoc();
10477   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10478
10479   SDValue Chain = Node->getOperand(0);
10480   SDValue In1 = Node->getOperand(1);
10481   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10482                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10483   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10484                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10485   SDValue Ops[] = { Chain, In1, In2L, In2H };
10486   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10487   SDValue Result =
10488     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10489                             cast<MemSDNode>(Node)->getMemOperand());
10490   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10491   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10492   Results.push_back(Result.getValue(2));
10493 }
10494
10495 /// ReplaceNodeResults - Replace a node with an illegal result type
10496 /// with a new node built out of custom code.
10497 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10498                                            SmallVectorImpl<SDValue>&Results,
10499                                            SelectionDAG &DAG) const {
10500   DebugLoc dl = N->getDebugLoc();
10501   switch (N->getOpcode()) {
10502   default:
10503     assert(false && "Do not know how to custom type legalize this operation!");
10504     return;
10505   case ISD::SIGN_EXTEND_INREG:
10506   case ISD::ADDC:
10507   case ISD::ADDE:
10508   case ISD::SUBC:
10509   case ISD::SUBE:
10510     // We don't want to expand or promote these.
10511     return;
10512   case ISD::FP_TO_SINT: {
10513     std::pair<SDValue,SDValue> Vals =
10514         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10515     SDValue FIST = Vals.first, StackSlot = Vals.second;
10516     if (FIST.getNode() != 0) {
10517       EVT VT = N->getValueType(0);
10518       // Return a load from the stack slot.
10519       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10520                                     MachinePointerInfo(), false, false, 0));
10521     }
10522     return;
10523   }
10524   case ISD::READCYCLECOUNTER: {
10525     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10526     SDValue TheChain = N->getOperand(0);
10527     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10528     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10529                                      rd.getValue(1));
10530     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10531                                      eax.getValue(2));
10532     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10533     SDValue Ops[] = { eax, edx };
10534     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10535     Results.push_back(edx.getValue(1));
10536     return;
10537   }
10538   case ISD::ATOMIC_CMP_SWAP: {
10539     EVT T = N->getValueType(0);
10540     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10541     bool Regs64bit = T == MVT::i128;
10542     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10543     SDValue cpInL, cpInH;
10544     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10545                         DAG.getConstant(0, HalfT));
10546     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10547                         DAG.getConstant(1, HalfT));
10548     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10549                              Regs64bit ? X86::RAX : X86::EAX,
10550                              cpInL, SDValue());
10551     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10552                              Regs64bit ? X86::RDX : X86::EDX,
10553                              cpInH, cpInL.getValue(1));
10554     SDValue swapInL, swapInH;
10555     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10556                           DAG.getConstant(0, HalfT));
10557     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10558                           DAG.getConstant(1, HalfT));
10559     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10560                                Regs64bit ? X86::RBX : X86::EBX,
10561                                swapInL, cpInH.getValue(1));
10562     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10563                                Regs64bit ? X86::RCX : X86::ECX, 
10564                                swapInH, swapInL.getValue(1));
10565     SDValue Ops[] = { swapInH.getValue(0),
10566                       N->getOperand(1),
10567                       swapInH.getValue(1) };
10568     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10569     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10570     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10571                                   X86ISD::LCMPXCHG8_DAG;
10572     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10573                                              Ops, 3, T, MMO);
10574     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10575                                         Regs64bit ? X86::RAX : X86::EAX,
10576                                         HalfT, Result.getValue(1));
10577     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10578                                         Regs64bit ? X86::RDX : X86::EDX,
10579                                         HalfT, cpOutL.getValue(2));
10580     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10581     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10582     Results.push_back(cpOutH.getValue(1));
10583     return;
10584   }
10585   case ISD::ATOMIC_LOAD_ADD:
10586     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10587     return;
10588   case ISD::ATOMIC_LOAD_AND:
10589     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10590     return;
10591   case ISD::ATOMIC_LOAD_NAND:
10592     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10593     return;
10594   case ISD::ATOMIC_LOAD_OR:
10595     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10596     return;
10597   case ISD::ATOMIC_LOAD_SUB:
10598     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10599     return;
10600   case ISD::ATOMIC_LOAD_XOR:
10601     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10602     return;
10603   case ISD::ATOMIC_SWAP:
10604     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10605     return;
10606   case ISD::ATOMIC_LOAD:
10607     ReplaceATOMIC_LOAD(N, Results, DAG);
10608   }
10609 }
10610
10611 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10612   switch (Opcode) {
10613   default: return NULL;
10614   case X86ISD::BSF:                return "X86ISD::BSF";
10615   case X86ISD::BSR:                return "X86ISD::BSR";
10616   case X86ISD::SHLD:               return "X86ISD::SHLD";
10617   case X86ISD::SHRD:               return "X86ISD::SHRD";
10618   case X86ISD::FAND:               return "X86ISD::FAND";
10619   case X86ISD::FOR:                return "X86ISD::FOR";
10620   case X86ISD::FXOR:               return "X86ISD::FXOR";
10621   case X86ISD::FSRL:               return "X86ISD::FSRL";
10622   case X86ISD::FILD:               return "X86ISD::FILD";
10623   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10624   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10625   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10626   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10627   case X86ISD::FLD:                return "X86ISD::FLD";
10628   case X86ISD::FST:                return "X86ISD::FST";
10629   case X86ISD::CALL:               return "X86ISD::CALL";
10630   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10631   case X86ISD::BT:                 return "X86ISD::BT";
10632   case X86ISD::CMP:                return "X86ISD::CMP";
10633   case X86ISD::COMI:               return "X86ISD::COMI";
10634   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10635   case X86ISD::SETCC:              return "X86ISD::SETCC";
10636   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10637   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10638   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10639   case X86ISD::CMOV:               return "X86ISD::CMOV";
10640   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10641   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10642   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10643   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10644   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10645   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10646   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10647   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10648   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10649   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10650   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10651   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10652   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10653   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10654   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10655   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10656   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10657   case X86ISD::FMAX:               return "X86ISD::FMAX";
10658   case X86ISD::FMIN:               return "X86ISD::FMIN";
10659   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10660   case X86ISD::FRCP:               return "X86ISD::FRCP";
10661   case X86ISD::FHADD:              return "X86ISD::FHADD";
10662   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10663   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10664   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10665   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10666   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10667   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10668   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10669   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10670   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10671   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10672   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10673   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10674   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10675   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10676   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10677   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10678   case X86ISD::VSHL:               return "X86ISD::VSHL";
10679   case X86ISD::VSRL:               return "X86ISD::VSRL";
10680   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10681   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10682   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10683   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10684   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10685   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10686   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10687   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10688   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10689   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10690   case X86ISD::ADD:                return "X86ISD::ADD";
10691   case X86ISD::SUB:                return "X86ISD::SUB";
10692   case X86ISD::ADC:                return "X86ISD::ADC";
10693   case X86ISD::SBB:                return "X86ISD::SBB";
10694   case X86ISD::SMUL:               return "X86ISD::SMUL";
10695   case X86ISD::UMUL:               return "X86ISD::UMUL";
10696   case X86ISD::INC:                return "X86ISD::INC";
10697   case X86ISD::DEC:                return "X86ISD::DEC";
10698   case X86ISD::OR:                 return "X86ISD::OR";
10699   case X86ISD::XOR:                return "X86ISD::XOR";
10700   case X86ISD::AND:                return "X86ISD::AND";
10701   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10702   case X86ISD::PTEST:              return "X86ISD::PTEST";
10703   case X86ISD::TESTP:              return "X86ISD::TESTP";
10704   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10705   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10706   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10707   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10708   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10709   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10710   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10711   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10712   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10713   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10714   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10715   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10716   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10717   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10718   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10719   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10720   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10721   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10722   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10723   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10724   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10725   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10726   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10727   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10728   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10729   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10730   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10731   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10732   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10733   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10734   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10735   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10736   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10737   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10738   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10739   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10740   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10741   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10742   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10743   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10744   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10745   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10746   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10747   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10748   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10749   }
10750 }
10751
10752 // isLegalAddressingMode - Return true if the addressing mode represented
10753 // by AM is legal for this target, for a load/store of the specified type.
10754 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10755                                               Type *Ty) const {
10756   // X86 supports extremely general addressing modes.
10757   CodeModel::Model M = getTargetMachine().getCodeModel();
10758   Reloc::Model R = getTargetMachine().getRelocationModel();
10759
10760   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10761   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10762     return false;
10763
10764   if (AM.BaseGV) {
10765     unsigned GVFlags =
10766       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10767
10768     // If a reference to this global requires an extra load, we can't fold it.
10769     if (isGlobalStubReference(GVFlags))
10770       return false;
10771
10772     // If BaseGV requires a register for the PIC base, we cannot also have a
10773     // BaseReg specified.
10774     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10775       return false;
10776
10777     // If lower 4G is not available, then we must use rip-relative addressing.
10778     if ((M != CodeModel::Small || R != Reloc::Static) &&
10779         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10780       return false;
10781   }
10782
10783   switch (AM.Scale) {
10784   case 0:
10785   case 1:
10786   case 2:
10787   case 4:
10788   case 8:
10789     // These scales always work.
10790     break;
10791   case 3:
10792   case 5:
10793   case 9:
10794     // These scales are formed with basereg+scalereg.  Only accept if there is
10795     // no basereg yet.
10796     if (AM.HasBaseReg)
10797       return false;
10798     break;
10799   default:  // Other stuff never works.
10800     return false;
10801   }
10802
10803   return true;
10804 }
10805
10806
10807 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10808   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10809     return false;
10810   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10811   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10812   if (NumBits1 <= NumBits2)
10813     return false;
10814   return true;
10815 }
10816
10817 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10818   if (!VT1.isInteger() || !VT2.isInteger())
10819     return false;
10820   unsigned NumBits1 = VT1.getSizeInBits();
10821   unsigned NumBits2 = VT2.getSizeInBits();
10822   if (NumBits1 <= NumBits2)
10823     return false;
10824   return true;
10825 }
10826
10827 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10828   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10829   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10830 }
10831
10832 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10833   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10834   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10835 }
10836
10837 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10838   // i16 instructions are longer (0x66 prefix) and potentially slower.
10839   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10840 }
10841
10842 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10843 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10844 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10845 /// are assumed to be legal.
10846 bool
10847 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10848                                       EVT VT) const {
10849   // Very little shuffling can be done for 64-bit vectors right now.
10850   if (VT.getSizeInBits() == 64)
10851     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
10852
10853   // FIXME: pshufb, blends, shifts.
10854   return (VT.getVectorNumElements() == 2 ||
10855           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10856           isMOVLMask(M, VT) ||
10857           isSHUFPMask(M, VT) ||
10858           isPSHUFDMask(M, VT) ||
10859           isPSHUFHWMask(M, VT) ||
10860           isPSHUFLWMask(M, VT) ||
10861           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
10862           isUNPCKLMask(M, VT) ||
10863           isUNPCKHMask(M, VT) ||
10864           isUNPCKL_v_undef_Mask(M, VT) ||
10865           isUNPCKH_v_undef_Mask(M, VT));
10866 }
10867
10868 bool
10869 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10870                                           EVT VT) const {
10871   unsigned NumElts = VT.getVectorNumElements();
10872   // FIXME: This collection of masks seems suspect.
10873   if (NumElts == 2)
10874     return true;
10875   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10876     return (isMOVLMask(Mask, VT)  ||
10877             isCommutedMOVLMask(Mask, VT, true) ||
10878             isSHUFPMask(Mask, VT) ||
10879             isCommutedSHUFPMask(Mask, VT));
10880   }
10881   return false;
10882 }
10883
10884 //===----------------------------------------------------------------------===//
10885 //                           X86 Scheduler Hooks
10886 //===----------------------------------------------------------------------===//
10887
10888 // private utility function
10889 MachineBasicBlock *
10890 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10891                                                        MachineBasicBlock *MBB,
10892                                                        unsigned regOpc,
10893                                                        unsigned immOpc,
10894                                                        unsigned LoadOpc,
10895                                                        unsigned CXchgOpc,
10896                                                        unsigned notOpc,
10897                                                        unsigned EAXreg,
10898                                                        TargetRegisterClass *RC,
10899                                                        bool invSrc) const {
10900   // For the atomic bitwise operator, we generate
10901   //   thisMBB:
10902   //   newMBB:
10903   //     ld  t1 = [bitinstr.addr]
10904   //     op  t2 = t1, [bitinstr.val]
10905   //     mov EAX = t1
10906   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10907   //     bz  newMBB
10908   //     fallthrough -->nextMBB
10909   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10910   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10911   MachineFunction::iterator MBBIter = MBB;
10912   ++MBBIter;
10913
10914   /// First build the CFG
10915   MachineFunction *F = MBB->getParent();
10916   MachineBasicBlock *thisMBB = MBB;
10917   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10918   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10919   F->insert(MBBIter, newMBB);
10920   F->insert(MBBIter, nextMBB);
10921
10922   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10923   nextMBB->splice(nextMBB->begin(), thisMBB,
10924                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10925                   thisMBB->end());
10926   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10927
10928   // Update thisMBB to fall through to newMBB
10929   thisMBB->addSuccessor(newMBB);
10930
10931   // newMBB jumps to itself and fall through to nextMBB
10932   newMBB->addSuccessor(nextMBB);
10933   newMBB->addSuccessor(newMBB);
10934
10935   // Insert instructions into newMBB based on incoming instruction
10936   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10937          "unexpected number of operands");
10938   DebugLoc dl = bInstr->getDebugLoc();
10939   MachineOperand& destOper = bInstr->getOperand(0);
10940   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10941   int numArgs = bInstr->getNumOperands() - 1;
10942   for (int i=0; i < numArgs; ++i)
10943     argOpers[i] = &bInstr->getOperand(i+1);
10944
10945   // x86 address has 4 operands: base, index, scale, and displacement
10946   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10947   int valArgIndx = lastAddrIndx + 1;
10948
10949   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10950   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10951   for (int i=0; i <= lastAddrIndx; ++i)
10952     (*MIB).addOperand(*argOpers[i]);
10953
10954   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10955   if (invSrc) {
10956     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10957   }
10958   else
10959     tt = t1;
10960
10961   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10962   assert((argOpers[valArgIndx]->isReg() ||
10963           argOpers[valArgIndx]->isImm()) &&
10964          "invalid operand");
10965   if (argOpers[valArgIndx]->isReg())
10966     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10967   else
10968     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10969   MIB.addReg(tt);
10970   (*MIB).addOperand(*argOpers[valArgIndx]);
10971
10972   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10973   MIB.addReg(t1);
10974
10975   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10976   for (int i=0; i <= lastAddrIndx; ++i)
10977     (*MIB).addOperand(*argOpers[i]);
10978   MIB.addReg(t2);
10979   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10980   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10981                     bInstr->memoperands_end());
10982
10983   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10984   MIB.addReg(EAXreg);
10985
10986   // insert branch
10987   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10988
10989   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10990   return nextMBB;
10991 }
10992
10993 // private utility function:  64 bit atomics on 32 bit host.
10994 MachineBasicBlock *
10995 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10996                                                        MachineBasicBlock *MBB,
10997                                                        unsigned regOpcL,
10998                                                        unsigned regOpcH,
10999                                                        unsigned immOpcL,
11000                                                        unsigned immOpcH,
11001                                                        bool invSrc) const {
11002   // For the atomic bitwise operator, we generate
11003   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11004   //     ld t1,t2 = [bitinstr.addr]
11005   //   newMBB:
11006   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11007   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11008   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11009   //     mov ECX, EBX <- t5, t6
11010   //     mov EAX, EDX <- t1, t2
11011   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11012   //     mov t3, t4 <- EAX, EDX
11013   //     bz  newMBB
11014   //     result in out1, out2
11015   //     fallthrough -->nextMBB
11016
11017   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11018   const unsigned LoadOpc = X86::MOV32rm;
11019   const unsigned NotOpc = X86::NOT32r;
11020   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11021   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11022   MachineFunction::iterator MBBIter = MBB;
11023   ++MBBIter;
11024
11025   /// First build the CFG
11026   MachineFunction *F = MBB->getParent();
11027   MachineBasicBlock *thisMBB = MBB;
11028   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11029   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11030   F->insert(MBBIter, newMBB);
11031   F->insert(MBBIter, nextMBB);
11032
11033   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11034   nextMBB->splice(nextMBB->begin(), thisMBB,
11035                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11036                   thisMBB->end());
11037   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11038
11039   // Update thisMBB to fall through to newMBB
11040   thisMBB->addSuccessor(newMBB);
11041
11042   // newMBB jumps to itself and fall through to nextMBB
11043   newMBB->addSuccessor(nextMBB);
11044   newMBB->addSuccessor(newMBB);
11045
11046   DebugLoc dl = bInstr->getDebugLoc();
11047   // Insert instructions into newMBB based on incoming instruction
11048   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11049   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11050          "unexpected number of operands");
11051   MachineOperand& dest1Oper = bInstr->getOperand(0);
11052   MachineOperand& dest2Oper = bInstr->getOperand(1);
11053   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11054   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11055     argOpers[i] = &bInstr->getOperand(i+2);
11056
11057     // We use some of the operands multiple times, so conservatively just
11058     // clear any kill flags that might be present.
11059     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11060       argOpers[i]->setIsKill(false);
11061   }
11062
11063   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11064   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11065
11066   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11067   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11068   for (int i=0; i <= lastAddrIndx; ++i)
11069     (*MIB).addOperand(*argOpers[i]);
11070   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11071   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11072   // add 4 to displacement.
11073   for (int i=0; i <= lastAddrIndx-2; ++i)
11074     (*MIB).addOperand(*argOpers[i]);
11075   MachineOperand newOp3 = *(argOpers[3]);
11076   if (newOp3.isImm())
11077     newOp3.setImm(newOp3.getImm()+4);
11078   else
11079     newOp3.setOffset(newOp3.getOffset()+4);
11080   (*MIB).addOperand(newOp3);
11081   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11082
11083   // t3/4 are defined later, at the bottom of the loop
11084   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11085   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11086   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11087     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11088   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11089     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11090
11091   // The subsequent operations should be using the destination registers of
11092   //the PHI instructions.
11093   if (invSrc) {
11094     t1 = F->getRegInfo().createVirtualRegister(RC);
11095     t2 = F->getRegInfo().createVirtualRegister(RC);
11096     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11097     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11098   } else {
11099     t1 = dest1Oper.getReg();
11100     t2 = dest2Oper.getReg();
11101   }
11102
11103   int valArgIndx = lastAddrIndx + 1;
11104   assert((argOpers[valArgIndx]->isReg() ||
11105           argOpers[valArgIndx]->isImm()) &&
11106          "invalid operand");
11107   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11108   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11109   if (argOpers[valArgIndx]->isReg())
11110     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11111   else
11112     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11113   if (regOpcL != X86::MOV32rr)
11114     MIB.addReg(t1);
11115   (*MIB).addOperand(*argOpers[valArgIndx]);
11116   assert(argOpers[valArgIndx + 1]->isReg() ==
11117          argOpers[valArgIndx]->isReg());
11118   assert(argOpers[valArgIndx + 1]->isImm() ==
11119          argOpers[valArgIndx]->isImm());
11120   if (argOpers[valArgIndx + 1]->isReg())
11121     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11122   else
11123     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11124   if (regOpcH != X86::MOV32rr)
11125     MIB.addReg(t2);
11126   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11127
11128   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11129   MIB.addReg(t1);
11130   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11131   MIB.addReg(t2);
11132
11133   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11134   MIB.addReg(t5);
11135   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11136   MIB.addReg(t6);
11137
11138   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11139   for (int i=0; i <= lastAddrIndx; ++i)
11140     (*MIB).addOperand(*argOpers[i]);
11141
11142   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11143   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11144                     bInstr->memoperands_end());
11145
11146   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11147   MIB.addReg(X86::EAX);
11148   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11149   MIB.addReg(X86::EDX);
11150
11151   // insert branch
11152   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11153
11154   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11155   return nextMBB;
11156 }
11157
11158 // private utility function
11159 MachineBasicBlock *
11160 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11161                                                       MachineBasicBlock *MBB,
11162                                                       unsigned cmovOpc) const {
11163   // For the atomic min/max operator, we generate
11164   //   thisMBB:
11165   //   newMBB:
11166   //     ld t1 = [min/max.addr]
11167   //     mov t2 = [min/max.val]
11168   //     cmp  t1, t2
11169   //     cmov[cond] t2 = t1
11170   //     mov EAX = t1
11171   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11172   //     bz   newMBB
11173   //     fallthrough -->nextMBB
11174   //
11175   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11176   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11177   MachineFunction::iterator MBBIter = MBB;
11178   ++MBBIter;
11179
11180   /// First build the CFG
11181   MachineFunction *F = MBB->getParent();
11182   MachineBasicBlock *thisMBB = MBB;
11183   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11184   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11185   F->insert(MBBIter, newMBB);
11186   F->insert(MBBIter, nextMBB);
11187
11188   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11189   nextMBB->splice(nextMBB->begin(), thisMBB,
11190                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11191                   thisMBB->end());
11192   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11193
11194   // Update thisMBB to fall through to newMBB
11195   thisMBB->addSuccessor(newMBB);
11196
11197   // newMBB jumps to newMBB and fall through to nextMBB
11198   newMBB->addSuccessor(nextMBB);
11199   newMBB->addSuccessor(newMBB);
11200
11201   DebugLoc dl = mInstr->getDebugLoc();
11202   // Insert instructions into newMBB based on incoming instruction
11203   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11204          "unexpected number of operands");
11205   MachineOperand& destOper = mInstr->getOperand(0);
11206   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11207   int numArgs = mInstr->getNumOperands() - 1;
11208   for (int i=0; i < numArgs; ++i)
11209     argOpers[i] = &mInstr->getOperand(i+1);
11210
11211   // x86 address has 4 operands: base, index, scale, and displacement
11212   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11213   int valArgIndx = lastAddrIndx + 1;
11214
11215   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11216   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11217   for (int i=0; i <= lastAddrIndx; ++i)
11218     (*MIB).addOperand(*argOpers[i]);
11219
11220   // We only support register and immediate values
11221   assert((argOpers[valArgIndx]->isReg() ||
11222           argOpers[valArgIndx]->isImm()) &&
11223          "invalid operand");
11224
11225   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11226   if (argOpers[valArgIndx]->isReg())
11227     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11228   else
11229     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11230   (*MIB).addOperand(*argOpers[valArgIndx]);
11231
11232   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11233   MIB.addReg(t1);
11234
11235   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11236   MIB.addReg(t1);
11237   MIB.addReg(t2);
11238
11239   // Generate movc
11240   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11241   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11242   MIB.addReg(t2);
11243   MIB.addReg(t1);
11244
11245   // Cmp and exchange if none has modified the memory location
11246   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11247   for (int i=0; i <= lastAddrIndx; ++i)
11248     (*MIB).addOperand(*argOpers[i]);
11249   MIB.addReg(t3);
11250   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11251   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11252                     mInstr->memoperands_end());
11253
11254   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11255   MIB.addReg(X86::EAX);
11256
11257   // insert branch
11258   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11259
11260   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11261   return nextMBB;
11262 }
11263
11264 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11265 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11266 // in the .td file.
11267 MachineBasicBlock *
11268 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11269                             unsigned numArgs, bool memArg) const {
11270   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11271          "Target must have SSE4.2 or AVX features enabled");
11272
11273   DebugLoc dl = MI->getDebugLoc();
11274   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11275   unsigned Opc;
11276   if (!Subtarget->hasAVX()) {
11277     if (memArg)
11278       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11279     else
11280       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11281   } else {
11282     if (memArg)
11283       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11284     else
11285       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11286   }
11287
11288   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11289   for (unsigned i = 0; i < numArgs; ++i) {
11290     MachineOperand &Op = MI->getOperand(i+1);
11291     if (!(Op.isReg() && Op.isImplicit()))
11292       MIB.addOperand(Op);
11293   }
11294   BuildMI(*BB, MI, dl,
11295     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11296              MI->getOperand(0).getReg())
11297     .addReg(X86::XMM0);
11298
11299   MI->eraseFromParent();
11300   return BB;
11301 }
11302
11303 MachineBasicBlock *
11304 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11305   DebugLoc dl = MI->getDebugLoc();
11306   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11307
11308   // Address into RAX/EAX, other two args into ECX, EDX.
11309   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11310   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11311   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11312   for (int i = 0; i < X86::AddrNumOperands; ++i)
11313     MIB.addOperand(MI->getOperand(i));
11314
11315   unsigned ValOps = X86::AddrNumOperands;
11316   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11317     .addReg(MI->getOperand(ValOps).getReg());
11318   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11319     .addReg(MI->getOperand(ValOps+1).getReg());
11320
11321   // The instruction doesn't actually take any operands though.
11322   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11323
11324   MI->eraseFromParent(); // The pseudo is gone now.
11325   return BB;
11326 }
11327
11328 MachineBasicBlock *
11329 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11330   DebugLoc dl = MI->getDebugLoc();
11331   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11332
11333   // First arg in ECX, the second in EAX.
11334   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11335     .addReg(MI->getOperand(0).getReg());
11336   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11337     .addReg(MI->getOperand(1).getReg());
11338
11339   // The instruction doesn't actually take any operands though.
11340   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11341
11342   MI->eraseFromParent(); // The pseudo is gone now.
11343   return BB;
11344 }
11345
11346 MachineBasicBlock *
11347 X86TargetLowering::EmitVAARG64WithCustomInserter(
11348                    MachineInstr *MI,
11349                    MachineBasicBlock *MBB) const {
11350   // Emit va_arg instruction on X86-64.
11351
11352   // Operands to this pseudo-instruction:
11353   // 0  ) Output        : destination address (reg)
11354   // 1-5) Input         : va_list address (addr, i64mem)
11355   // 6  ) ArgSize       : Size (in bytes) of vararg type
11356   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11357   // 8  ) Align         : Alignment of type
11358   // 9  ) EFLAGS (implicit-def)
11359
11360   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11361   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11362
11363   unsigned DestReg = MI->getOperand(0).getReg();
11364   MachineOperand &Base = MI->getOperand(1);
11365   MachineOperand &Scale = MI->getOperand(2);
11366   MachineOperand &Index = MI->getOperand(3);
11367   MachineOperand &Disp = MI->getOperand(4);
11368   MachineOperand &Segment = MI->getOperand(5);
11369   unsigned ArgSize = MI->getOperand(6).getImm();
11370   unsigned ArgMode = MI->getOperand(7).getImm();
11371   unsigned Align = MI->getOperand(8).getImm();
11372
11373   // Memory Reference
11374   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11375   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11376   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11377
11378   // Machine Information
11379   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11380   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11381   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11382   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11383   DebugLoc DL = MI->getDebugLoc();
11384
11385   // struct va_list {
11386   //   i32   gp_offset
11387   //   i32   fp_offset
11388   //   i64   overflow_area (address)
11389   //   i64   reg_save_area (address)
11390   // }
11391   // sizeof(va_list) = 24
11392   // alignment(va_list) = 8
11393
11394   unsigned TotalNumIntRegs = 6;
11395   unsigned TotalNumXMMRegs = 8;
11396   bool UseGPOffset = (ArgMode == 1);
11397   bool UseFPOffset = (ArgMode == 2);
11398   unsigned MaxOffset = TotalNumIntRegs * 8 +
11399                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11400
11401   /* Align ArgSize to a multiple of 8 */
11402   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11403   bool NeedsAlign = (Align > 8);
11404
11405   MachineBasicBlock *thisMBB = MBB;
11406   MachineBasicBlock *overflowMBB;
11407   MachineBasicBlock *offsetMBB;
11408   MachineBasicBlock *endMBB;
11409
11410   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11411   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11412   unsigned OffsetReg = 0;
11413
11414   if (!UseGPOffset && !UseFPOffset) {
11415     // If we only pull from the overflow region, we don't create a branch.
11416     // We don't need to alter control flow.
11417     OffsetDestReg = 0; // unused
11418     OverflowDestReg = DestReg;
11419
11420     offsetMBB = NULL;
11421     overflowMBB = thisMBB;
11422     endMBB = thisMBB;
11423   } else {
11424     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11425     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11426     // If not, pull from overflow_area. (branch to overflowMBB)
11427     //
11428     //       thisMBB
11429     //         |     .
11430     //         |        .
11431     //     offsetMBB   overflowMBB
11432     //         |        .
11433     //         |     .
11434     //        endMBB
11435
11436     // Registers for the PHI in endMBB
11437     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11438     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11439
11440     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11441     MachineFunction *MF = MBB->getParent();
11442     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11443     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11444     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11445
11446     MachineFunction::iterator MBBIter = MBB;
11447     ++MBBIter;
11448
11449     // Insert the new basic blocks
11450     MF->insert(MBBIter, offsetMBB);
11451     MF->insert(MBBIter, overflowMBB);
11452     MF->insert(MBBIter, endMBB);
11453
11454     // Transfer the remainder of MBB and its successor edges to endMBB.
11455     endMBB->splice(endMBB->begin(), thisMBB,
11456                     llvm::next(MachineBasicBlock::iterator(MI)),
11457                     thisMBB->end());
11458     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11459
11460     // Make offsetMBB and overflowMBB successors of thisMBB
11461     thisMBB->addSuccessor(offsetMBB);
11462     thisMBB->addSuccessor(overflowMBB);
11463
11464     // endMBB is a successor of both offsetMBB and overflowMBB
11465     offsetMBB->addSuccessor(endMBB);
11466     overflowMBB->addSuccessor(endMBB);
11467
11468     // Load the offset value into a register
11469     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11470     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11471       .addOperand(Base)
11472       .addOperand(Scale)
11473       .addOperand(Index)
11474       .addDisp(Disp, UseFPOffset ? 4 : 0)
11475       .addOperand(Segment)
11476       .setMemRefs(MMOBegin, MMOEnd);
11477
11478     // Check if there is enough room left to pull this argument.
11479     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11480       .addReg(OffsetReg)
11481       .addImm(MaxOffset + 8 - ArgSizeA8);
11482
11483     // Branch to "overflowMBB" if offset >= max
11484     // Fall through to "offsetMBB" otherwise
11485     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11486       .addMBB(overflowMBB);
11487   }
11488
11489   // In offsetMBB, emit code to use the reg_save_area.
11490   if (offsetMBB) {
11491     assert(OffsetReg != 0);
11492
11493     // Read the reg_save_area address.
11494     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11495     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11496       .addOperand(Base)
11497       .addOperand(Scale)
11498       .addOperand(Index)
11499       .addDisp(Disp, 16)
11500       .addOperand(Segment)
11501       .setMemRefs(MMOBegin, MMOEnd);
11502
11503     // Zero-extend the offset
11504     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11505       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11506         .addImm(0)
11507         .addReg(OffsetReg)
11508         .addImm(X86::sub_32bit);
11509
11510     // Add the offset to the reg_save_area to get the final address.
11511     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11512       .addReg(OffsetReg64)
11513       .addReg(RegSaveReg);
11514
11515     // Compute the offset for the next argument
11516     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11517     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11518       .addReg(OffsetReg)
11519       .addImm(UseFPOffset ? 16 : 8);
11520
11521     // Store it back into the va_list.
11522     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11523       .addOperand(Base)
11524       .addOperand(Scale)
11525       .addOperand(Index)
11526       .addDisp(Disp, UseFPOffset ? 4 : 0)
11527       .addOperand(Segment)
11528       .addReg(NextOffsetReg)
11529       .setMemRefs(MMOBegin, MMOEnd);
11530
11531     // Jump to endMBB
11532     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11533       .addMBB(endMBB);
11534   }
11535
11536   //
11537   // Emit code to use overflow area
11538   //
11539
11540   // Load the overflow_area address into a register.
11541   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11542   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11543     .addOperand(Base)
11544     .addOperand(Scale)
11545     .addOperand(Index)
11546     .addDisp(Disp, 8)
11547     .addOperand(Segment)
11548     .setMemRefs(MMOBegin, MMOEnd);
11549
11550   // If we need to align it, do so. Otherwise, just copy the address
11551   // to OverflowDestReg.
11552   if (NeedsAlign) {
11553     // Align the overflow address
11554     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11555     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11556
11557     // aligned_addr = (addr + (align-1)) & ~(align-1)
11558     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11559       .addReg(OverflowAddrReg)
11560       .addImm(Align-1);
11561
11562     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11563       .addReg(TmpReg)
11564       .addImm(~(uint64_t)(Align-1));
11565   } else {
11566     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11567       .addReg(OverflowAddrReg);
11568   }
11569
11570   // Compute the next overflow address after this argument.
11571   // (the overflow address should be kept 8-byte aligned)
11572   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11573   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11574     .addReg(OverflowDestReg)
11575     .addImm(ArgSizeA8);
11576
11577   // Store the new overflow address.
11578   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11579     .addOperand(Base)
11580     .addOperand(Scale)
11581     .addOperand(Index)
11582     .addDisp(Disp, 8)
11583     .addOperand(Segment)
11584     .addReg(NextAddrReg)
11585     .setMemRefs(MMOBegin, MMOEnd);
11586
11587   // If we branched, emit the PHI to the front of endMBB.
11588   if (offsetMBB) {
11589     BuildMI(*endMBB, endMBB->begin(), DL,
11590             TII->get(X86::PHI), DestReg)
11591       .addReg(OffsetDestReg).addMBB(offsetMBB)
11592       .addReg(OverflowDestReg).addMBB(overflowMBB);
11593   }
11594
11595   // Erase the pseudo instruction
11596   MI->eraseFromParent();
11597
11598   return endMBB;
11599 }
11600
11601 MachineBasicBlock *
11602 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11603                                                  MachineInstr *MI,
11604                                                  MachineBasicBlock *MBB) const {
11605   // Emit code to save XMM registers to the stack. The ABI says that the
11606   // number of registers to save is given in %al, so it's theoretically
11607   // possible to do an indirect jump trick to avoid saving all of them,
11608   // however this code takes a simpler approach and just executes all
11609   // of the stores if %al is non-zero. It's less code, and it's probably
11610   // easier on the hardware branch predictor, and stores aren't all that
11611   // expensive anyway.
11612
11613   // Create the new basic blocks. One block contains all the XMM stores,
11614   // and one block is the final destination regardless of whether any
11615   // stores were performed.
11616   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11617   MachineFunction *F = MBB->getParent();
11618   MachineFunction::iterator MBBIter = MBB;
11619   ++MBBIter;
11620   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11621   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11622   F->insert(MBBIter, XMMSaveMBB);
11623   F->insert(MBBIter, EndMBB);
11624
11625   // Transfer the remainder of MBB and its successor edges to EndMBB.
11626   EndMBB->splice(EndMBB->begin(), MBB,
11627                  llvm::next(MachineBasicBlock::iterator(MI)),
11628                  MBB->end());
11629   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11630
11631   // The original block will now fall through to the XMM save block.
11632   MBB->addSuccessor(XMMSaveMBB);
11633   // The XMMSaveMBB will fall through to the end block.
11634   XMMSaveMBB->addSuccessor(EndMBB);
11635
11636   // Now add the instructions.
11637   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11638   DebugLoc DL = MI->getDebugLoc();
11639
11640   unsigned CountReg = MI->getOperand(0).getReg();
11641   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11642   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11643
11644   if (!Subtarget->isTargetWin64()) {
11645     // If %al is 0, branch around the XMM save block.
11646     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11647     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11648     MBB->addSuccessor(EndMBB);
11649   }
11650
11651   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11652   // In the XMM save block, save all the XMM argument registers.
11653   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11654     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11655     MachineMemOperand *MMO =
11656       F->getMachineMemOperand(
11657           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11658         MachineMemOperand::MOStore,
11659         /*Size=*/16, /*Align=*/16);
11660     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11661       .addFrameIndex(RegSaveFrameIndex)
11662       .addImm(/*Scale=*/1)
11663       .addReg(/*IndexReg=*/0)
11664       .addImm(/*Disp=*/Offset)
11665       .addReg(/*Segment=*/0)
11666       .addReg(MI->getOperand(i).getReg())
11667       .addMemOperand(MMO);
11668   }
11669
11670   MI->eraseFromParent();   // The pseudo instruction is gone now.
11671
11672   return EndMBB;
11673 }
11674
11675 MachineBasicBlock *
11676 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11677                                      MachineBasicBlock *BB) const {
11678   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11679   DebugLoc DL = MI->getDebugLoc();
11680
11681   // To "insert" a SELECT_CC instruction, we actually have to insert the
11682   // diamond control-flow pattern.  The incoming instruction knows the
11683   // destination vreg to set, the condition code register to branch on, the
11684   // true/false values to select between, and a branch opcode to use.
11685   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11686   MachineFunction::iterator It = BB;
11687   ++It;
11688
11689   //  thisMBB:
11690   //  ...
11691   //   TrueVal = ...
11692   //   cmpTY ccX, r1, r2
11693   //   bCC copy1MBB
11694   //   fallthrough --> copy0MBB
11695   MachineBasicBlock *thisMBB = BB;
11696   MachineFunction *F = BB->getParent();
11697   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11698   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11699   F->insert(It, copy0MBB);
11700   F->insert(It, sinkMBB);
11701
11702   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11703   // live into the sink and copy blocks.
11704   if (!MI->killsRegister(X86::EFLAGS)) {
11705     copy0MBB->addLiveIn(X86::EFLAGS);
11706     sinkMBB->addLiveIn(X86::EFLAGS);
11707   }
11708
11709   // Transfer the remainder of BB and its successor edges to sinkMBB.
11710   sinkMBB->splice(sinkMBB->begin(), BB,
11711                   llvm::next(MachineBasicBlock::iterator(MI)),
11712                   BB->end());
11713   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11714
11715   // Add the true and fallthrough blocks as its successors.
11716   BB->addSuccessor(copy0MBB);
11717   BB->addSuccessor(sinkMBB);
11718
11719   // Create the conditional branch instruction.
11720   unsigned Opc =
11721     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11722   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11723
11724   //  copy0MBB:
11725   //   %FalseValue = ...
11726   //   # fallthrough to sinkMBB
11727   copy0MBB->addSuccessor(sinkMBB);
11728
11729   //  sinkMBB:
11730   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11731   //  ...
11732   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11733           TII->get(X86::PHI), MI->getOperand(0).getReg())
11734     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11735     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11736
11737   MI->eraseFromParent();   // The pseudo instruction is gone now.
11738   return sinkMBB;
11739 }
11740
11741 MachineBasicBlock *
11742 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11743                                         bool Is64Bit) const {
11744   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11745   DebugLoc DL = MI->getDebugLoc();
11746   MachineFunction *MF = BB->getParent();
11747   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11748
11749   assert(EnableSegmentedStacks);
11750
11751   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11752   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11753
11754   // BB:
11755   //  ... [Till the alloca]
11756   // If stacklet is not large enough, jump to mallocMBB
11757   //
11758   // bumpMBB:
11759   //  Allocate by subtracting from RSP
11760   //  Jump to continueMBB
11761   //
11762   // mallocMBB:
11763   //  Allocate by call to runtime
11764   //
11765   // continueMBB:
11766   //  ...
11767   //  [rest of original BB]
11768   //
11769
11770   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11771   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11772   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11773
11774   MachineRegisterInfo &MRI = MF->getRegInfo();
11775   const TargetRegisterClass *AddrRegClass =
11776     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11777
11778   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11779     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11780     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11781     sizeVReg = MI->getOperand(1).getReg(),
11782     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11783
11784   MachineFunction::iterator MBBIter = BB;
11785   ++MBBIter;
11786
11787   MF->insert(MBBIter, bumpMBB);
11788   MF->insert(MBBIter, mallocMBB);
11789   MF->insert(MBBIter, continueMBB);
11790
11791   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11792                       (MachineBasicBlock::iterator(MI)), BB->end());
11793   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11794
11795   // Add code to the main basic block to check if the stack limit has been hit,
11796   // and if so, jump to mallocMBB otherwise to bumpMBB.
11797   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11798   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11799     .addReg(tmpSPVReg).addReg(sizeVReg);
11800   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11801     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11802     .addReg(tmpSPVReg);
11803   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11804
11805   // bumpMBB simply decreases the stack pointer, since we know the current
11806   // stacklet has enough space.
11807   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11808     .addReg(tmpSPVReg);
11809   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11810     .addReg(tmpSPVReg);
11811   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11812
11813   // Calls into a routine in libgcc to allocate more space from the heap.
11814   if (Is64Bit) {
11815     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11816       .addReg(sizeVReg);
11817     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11818     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11819   } else {
11820     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11821       .addImm(12);
11822     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11823     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11824       .addExternalSymbol("__morestack_allocate_stack_space");
11825   }
11826
11827   if (!Is64Bit)
11828     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11829       .addImm(16);
11830
11831   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11832     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11833   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11834
11835   // Set up the CFG correctly.
11836   BB->addSuccessor(bumpMBB);
11837   BB->addSuccessor(mallocMBB);
11838   mallocMBB->addSuccessor(continueMBB);
11839   bumpMBB->addSuccessor(continueMBB);
11840
11841   // Take care of the PHI nodes.
11842   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11843           MI->getOperand(0).getReg())
11844     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11845     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11846
11847   // Delete the original pseudo instruction.
11848   MI->eraseFromParent();
11849
11850   // And we're done.
11851   return continueMBB;
11852 }
11853
11854 MachineBasicBlock *
11855 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11856                                           MachineBasicBlock *BB) const {
11857   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11858   DebugLoc DL = MI->getDebugLoc();
11859
11860   assert(!Subtarget->isTargetEnvMacho());
11861
11862   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11863   // non-trivial part is impdef of ESP.
11864
11865   if (Subtarget->isTargetWin64()) {
11866     if (Subtarget->isTargetCygMing()) {
11867       // ___chkstk(Mingw64):
11868       // Clobbers R10, R11, RAX and EFLAGS.
11869       // Updates RSP.
11870       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11871         .addExternalSymbol("___chkstk")
11872         .addReg(X86::RAX, RegState::Implicit)
11873         .addReg(X86::RSP, RegState::Implicit)
11874         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11875         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11876         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11877     } else {
11878       // __chkstk(MSVCRT): does not update stack pointer.
11879       // Clobbers R10, R11 and EFLAGS.
11880       // FIXME: RAX(allocated size) might be reused and not killed.
11881       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11882         .addExternalSymbol("__chkstk")
11883         .addReg(X86::RAX, RegState::Implicit)
11884         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11885       // RAX has the offset to subtracted from RSP.
11886       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11887         .addReg(X86::RSP)
11888         .addReg(X86::RAX);
11889     }
11890   } else {
11891     const char *StackProbeSymbol =
11892       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11893
11894     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11895       .addExternalSymbol(StackProbeSymbol)
11896       .addReg(X86::EAX, RegState::Implicit)
11897       .addReg(X86::ESP, RegState::Implicit)
11898       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11899       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11900       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11901   }
11902
11903   MI->eraseFromParent();   // The pseudo instruction is gone now.
11904   return BB;
11905 }
11906
11907 MachineBasicBlock *
11908 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11909                                       MachineBasicBlock *BB) const {
11910   // This is pretty easy.  We're taking the value that we received from
11911   // our load from the relocation, sticking it in either RDI (x86-64)
11912   // or EAX and doing an indirect call.  The return value will then
11913   // be in the normal return register.
11914   const X86InstrInfo *TII
11915     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11916   DebugLoc DL = MI->getDebugLoc();
11917   MachineFunction *F = BB->getParent();
11918
11919   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11920   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11921
11922   if (Subtarget->is64Bit()) {
11923     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11924                                       TII->get(X86::MOV64rm), X86::RDI)
11925     .addReg(X86::RIP)
11926     .addImm(0).addReg(0)
11927     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11928                       MI->getOperand(3).getTargetFlags())
11929     .addReg(0);
11930     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11931     addDirectMem(MIB, X86::RDI);
11932   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11933     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11934                                       TII->get(X86::MOV32rm), X86::EAX)
11935     .addReg(0)
11936     .addImm(0).addReg(0)
11937     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11938                       MI->getOperand(3).getTargetFlags())
11939     .addReg(0);
11940     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11941     addDirectMem(MIB, X86::EAX);
11942   } else {
11943     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11944                                       TII->get(X86::MOV32rm), X86::EAX)
11945     .addReg(TII->getGlobalBaseReg(F))
11946     .addImm(0).addReg(0)
11947     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11948                       MI->getOperand(3).getTargetFlags())
11949     .addReg(0);
11950     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11951     addDirectMem(MIB, X86::EAX);
11952   }
11953
11954   MI->eraseFromParent(); // The pseudo instruction is gone now.
11955   return BB;
11956 }
11957
11958 MachineBasicBlock *
11959 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11960                                                MachineBasicBlock *BB) const {
11961   switch (MI->getOpcode()) {
11962   default: assert(0 && "Unexpected instr type to insert");
11963   case X86::TAILJMPd64:
11964   case X86::TAILJMPr64:
11965   case X86::TAILJMPm64:
11966     assert(0 && "TAILJMP64 would not be touched here.");
11967   case X86::TCRETURNdi64:
11968   case X86::TCRETURNri64:
11969   case X86::TCRETURNmi64:
11970     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11971     // On AMD64, additional defs should be added before register allocation.
11972     if (!Subtarget->isTargetWin64()) {
11973       MI->addRegisterDefined(X86::RSI);
11974       MI->addRegisterDefined(X86::RDI);
11975       MI->addRegisterDefined(X86::XMM6);
11976       MI->addRegisterDefined(X86::XMM7);
11977       MI->addRegisterDefined(X86::XMM8);
11978       MI->addRegisterDefined(X86::XMM9);
11979       MI->addRegisterDefined(X86::XMM10);
11980       MI->addRegisterDefined(X86::XMM11);
11981       MI->addRegisterDefined(X86::XMM12);
11982       MI->addRegisterDefined(X86::XMM13);
11983       MI->addRegisterDefined(X86::XMM14);
11984       MI->addRegisterDefined(X86::XMM15);
11985     }
11986     return BB;
11987   case X86::WIN_ALLOCA:
11988     return EmitLoweredWinAlloca(MI, BB);
11989   case X86::SEG_ALLOCA_32:
11990     return EmitLoweredSegAlloca(MI, BB, false);
11991   case X86::SEG_ALLOCA_64:
11992     return EmitLoweredSegAlloca(MI, BB, true);
11993   case X86::TLSCall_32:
11994   case X86::TLSCall_64:
11995     return EmitLoweredTLSCall(MI, BB);
11996   case X86::CMOV_GR8:
11997   case X86::CMOV_FR32:
11998   case X86::CMOV_FR64:
11999   case X86::CMOV_V4F32:
12000   case X86::CMOV_V2F64:
12001   case X86::CMOV_V2I64:
12002   case X86::CMOV_V8F32:
12003   case X86::CMOV_V4F64:
12004   case X86::CMOV_V4I64:
12005   case X86::CMOV_GR16:
12006   case X86::CMOV_GR32:
12007   case X86::CMOV_RFP32:
12008   case X86::CMOV_RFP64:
12009   case X86::CMOV_RFP80:
12010     return EmitLoweredSelect(MI, BB);
12011
12012   case X86::FP32_TO_INT16_IN_MEM:
12013   case X86::FP32_TO_INT32_IN_MEM:
12014   case X86::FP32_TO_INT64_IN_MEM:
12015   case X86::FP64_TO_INT16_IN_MEM:
12016   case X86::FP64_TO_INT32_IN_MEM:
12017   case X86::FP64_TO_INT64_IN_MEM:
12018   case X86::FP80_TO_INT16_IN_MEM:
12019   case X86::FP80_TO_INT32_IN_MEM:
12020   case X86::FP80_TO_INT64_IN_MEM: {
12021     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12022     DebugLoc DL = MI->getDebugLoc();
12023
12024     // Change the floating point control register to use "round towards zero"
12025     // mode when truncating to an integer value.
12026     MachineFunction *F = BB->getParent();
12027     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12028     addFrameReference(BuildMI(*BB, MI, DL,
12029                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12030
12031     // Load the old value of the high byte of the control word...
12032     unsigned OldCW =
12033       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12034     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12035                       CWFrameIdx);
12036
12037     // Set the high part to be round to zero...
12038     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12039       .addImm(0xC7F);
12040
12041     // Reload the modified control word now...
12042     addFrameReference(BuildMI(*BB, MI, DL,
12043                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12044
12045     // Restore the memory image of control word to original value
12046     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12047       .addReg(OldCW);
12048
12049     // Get the X86 opcode to use.
12050     unsigned Opc;
12051     switch (MI->getOpcode()) {
12052     default: llvm_unreachable("illegal opcode!");
12053     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12054     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12055     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12056     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12057     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12058     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12059     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12060     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12061     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12062     }
12063
12064     X86AddressMode AM;
12065     MachineOperand &Op = MI->getOperand(0);
12066     if (Op.isReg()) {
12067       AM.BaseType = X86AddressMode::RegBase;
12068       AM.Base.Reg = Op.getReg();
12069     } else {
12070       AM.BaseType = X86AddressMode::FrameIndexBase;
12071       AM.Base.FrameIndex = Op.getIndex();
12072     }
12073     Op = MI->getOperand(1);
12074     if (Op.isImm())
12075       AM.Scale = Op.getImm();
12076     Op = MI->getOperand(2);
12077     if (Op.isImm())
12078       AM.IndexReg = Op.getImm();
12079     Op = MI->getOperand(3);
12080     if (Op.isGlobal()) {
12081       AM.GV = Op.getGlobal();
12082     } else {
12083       AM.Disp = Op.getImm();
12084     }
12085     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12086                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12087
12088     // Reload the original control word now.
12089     addFrameReference(BuildMI(*BB, MI, DL,
12090                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12091
12092     MI->eraseFromParent();   // The pseudo instruction is gone now.
12093     return BB;
12094   }
12095     // String/text processing lowering.
12096   case X86::PCMPISTRM128REG:
12097   case X86::VPCMPISTRM128REG:
12098     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12099   case X86::PCMPISTRM128MEM:
12100   case X86::VPCMPISTRM128MEM:
12101     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12102   case X86::PCMPESTRM128REG:
12103   case X86::VPCMPESTRM128REG:
12104     return EmitPCMP(MI, BB, 5, false /* in mem */);
12105   case X86::PCMPESTRM128MEM:
12106   case X86::VPCMPESTRM128MEM:
12107     return EmitPCMP(MI, BB, 5, true /* in mem */);
12108
12109     // Thread synchronization.
12110   case X86::MONITOR:
12111     return EmitMonitor(MI, BB);
12112   case X86::MWAIT:
12113     return EmitMwait(MI, BB);
12114
12115     // Atomic Lowering.
12116   case X86::ATOMAND32:
12117     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12118                                                X86::AND32ri, X86::MOV32rm,
12119                                                X86::LCMPXCHG32,
12120                                                X86::NOT32r, X86::EAX,
12121                                                X86::GR32RegisterClass);
12122   case X86::ATOMOR32:
12123     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12124                                                X86::OR32ri, X86::MOV32rm,
12125                                                X86::LCMPXCHG32,
12126                                                X86::NOT32r, X86::EAX,
12127                                                X86::GR32RegisterClass);
12128   case X86::ATOMXOR32:
12129     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12130                                                X86::XOR32ri, X86::MOV32rm,
12131                                                X86::LCMPXCHG32,
12132                                                X86::NOT32r, X86::EAX,
12133                                                X86::GR32RegisterClass);
12134   case X86::ATOMNAND32:
12135     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12136                                                X86::AND32ri, X86::MOV32rm,
12137                                                X86::LCMPXCHG32,
12138                                                X86::NOT32r, X86::EAX,
12139                                                X86::GR32RegisterClass, true);
12140   case X86::ATOMMIN32:
12141     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12142   case X86::ATOMMAX32:
12143     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12144   case X86::ATOMUMIN32:
12145     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12146   case X86::ATOMUMAX32:
12147     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12148
12149   case X86::ATOMAND16:
12150     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12151                                                X86::AND16ri, X86::MOV16rm,
12152                                                X86::LCMPXCHG16,
12153                                                X86::NOT16r, X86::AX,
12154                                                X86::GR16RegisterClass);
12155   case X86::ATOMOR16:
12156     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12157                                                X86::OR16ri, X86::MOV16rm,
12158                                                X86::LCMPXCHG16,
12159                                                X86::NOT16r, X86::AX,
12160                                                X86::GR16RegisterClass);
12161   case X86::ATOMXOR16:
12162     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12163                                                X86::XOR16ri, X86::MOV16rm,
12164                                                X86::LCMPXCHG16,
12165                                                X86::NOT16r, X86::AX,
12166                                                X86::GR16RegisterClass);
12167   case X86::ATOMNAND16:
12168     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12169                                                X86::AND16ri, X86::MOV16rm,
12170                                                X86::LCMPXCHG16,
12171                                                X86::NOT16r, X86::AX,
12172                                                X86::GR16RegisterClass, true);
12173   case X86::ATOMMIN16:
12174     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12175   case X86::ATOMMAX16:
12176     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12177   case X86::ATOMUMIN16:
12178     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12179   case X86::ATOMUMAX16:
12180     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12181
12182   case X86::ATOMAND8:
12183     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12184                                                X86::AND8ri, X86::MOV8rm,
12185                                                X86::LCMPXCHG8,
12186                                                X86::NOT8r, X86::AL,
12187                                                X86::GR8RegisterClass);
12188   case X86::ATOMOR8:
12189     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12190                                                X86::OR8ri, X86::MOV8rm,
12191                                                X86::LCMPXCHG8,
12192                                                X86::NOT8r, X86::AL,
12193                                                X86::GR8RegisterClass);
12194   case X86::ATOMXOR8:
12195     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12196                                                X86::XOR8ri, X86::MOV8rm,
12197                                                X86::LCMPXCHG8,
12198                                                X86::NOT8r, X86::AL,
12199                                                X86::GR8RegisterClass);
12200   case X86::ATOMNAND8:
12201     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12202                                                X86::AND8ri, X86::MOV8rm,
12203                                                X86::LCMPXCHG8,
12204                                                X86::NOT8r, X86::AL,
12205                                                X86::GR8RegisterClass, true);
12206   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12207   // This group is for 64-bit host.
12208   case X86::ATOMAND64:
12209     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12210                                                X86::AND64ri32, X86::MOV64rm,
12211                                                X86::LCMPXCHG64,
12212                                                X86::NOT64r, X86::RAX,
12213                                                X86::GR64RegisterClass);
12214   case X86::ATOMOR64:
12215     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12216                                                X86::OR64ri32, X86::MOV64rm,
12217                                                X86::LCMPXCHG64,
12218                                                X86::NOT64r, X86::RAX,
12219                                                X86::GR64RegisterClass);
12220   case X86::ATOMXOR64:
12221     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12222                                                X86::XOR64ri32, X86::MOV64rm,
12223                                                X86::LCMPXCHG64,
12224                                                X86::NOT64r, X86::RAX,
12225                                                X86::GR64RegisterClass);
12226   case X86::ATOMNAND64:
12227     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12228                                                X86::AND64ri32, X86::MOV64rm,
12229                                                X86::LCMPXCHG64,
12230                                                X86::NOT64r, X86::RAX,
12231                                                X86::GR64RegisterClass, true);
12232   case X86::ATOMMIN64:
12233     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12234   case X86::ATOMMAX64:
12235     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12236   case X86::ATOMUMIN64:
12237     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12238   case X86::ATOMUMAX64:
12239     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12240
12241   // This group does 64-bit operations on a 32-bit host.
12242   case X86::ATOMAND6432:
12243     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12244                                                X86::AND32rr, X86::AND32rr,
12245                                                X86::AND32ri, X86::AND32ri,
12246                                                false);
12247   case X86::ATOMOR6432:
12248     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12249                                                X86::OR32rr, X86::OR32rr,
12250                                                X86::OR32ri, X86::OR32ri,
12251                                                false);
12252   case X86::ATOMXOR6432:
12253     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12254                                                X86::XOR32rr, X86::XOR32rr,
12255                                                X86::XOR32ri, X86::XOR32ri,
12256                                                false);
12257   case X86::ATOMNAND6432:
12258     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12259                                                X86::AND32rr, X86::AND32rr,
12260                                                X86::AND32ri, X86::AND32ri,
12261                                                true);
12262   case X86::ATOMADD6432:
12263     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12264                                                X86::ADD32rr, X86::ADC32rr,
12265                                                X86::ADD32ri, X86::ADC32ri,
12266                                                false);
12267   case X86::ATOMSUB6432:
12268     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12269                                                X86::SUB32rr, X86::SBB32rr,
12270                                                X86::SUB32ri, X86::SBB32ri,
12271                                                false);
12272   case X86::ATOMSWAP6432:
12273     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12274                                                X86::MOV32rr, X86::MOV32rr,
12275                                                X86::MOV32ri, X86::MOV32ri,
12276                                                false);
12277   case X86::VASTART_SAVE_XMM_REGS:
12278     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12279
12280   case X86::VAARG_64:
12281     return EmitVAARG64WithCustomInserter(MI, BB);
12282   }
12283 }
12284
12285 //===----------------------------------------------------------------------===//
12286 //                           X86 Optimization Hooks
12287 //===----------------------------------------------------------------------===//
12288
12289 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12290                                                        const APInt &Mask,
12291                                                        APInt &KnownZero,
12292                                                        APInt &KnownOne,
12293                                                        const SelectionDAG &DAG,
12294                                                        unsigned Depth) const {
12295   unsigned Opc = Op.getOpcode();
12296   assert((Opc >= ISD::BUILTIN_OP_END ||
12297           Opc == ISD::INTRINSIC_WO_CHAIN ||
12298           Opc == ISD::INTRINSIC_W_CHAIN ||
12299           Opc == ISD::INTRINSIC_VOID) &&
12300          "Should use MaskedValueIsZero if you don't know whether Op"
12301          " is a target node!");
12302
12303   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12304   switch (Opc) {
12305   default: break;
12306   case X86ISD::ADD:
12307   case X86ISD::SUB:
12308   case X86ISD::ADC:
12309   case X86ISD::SBB:
12310   case X86ISD::SMUL:
12311   case X86ISD::UMUL:
12312   case X86ISD::INC:
12313   case X86ISD::DEC:
12314   case X86ISD::OR:
12315   case X86ISD::XOR:
12316   case X86ISD::AND:
12317     // These nodes' second result is a boolean.
12318     if (Op.getResNo() == 0)
12319       break;
12320     // Fallthrough
12321   case X86ISD::SETCC:
12322     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12323                                        Mask.getBitWidth() - 1);
12324     break;
12325   case ISD::INTRINSIC_WO_CHAIN: {
12326     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12327     unsigned NumLoBits = 0;
12328     switch (IntId) {
12329     default: break;
12330     case Intrinsic::x86_sse_movmsk_ps:
12331     case Intrinsic::x86_avx_movmsk_ps_256:
12332     case Intrinsic::x86_sse2_movmsk_pd:
12333     case Intrinsic::x86_avx_movmsk_pd_256:
12334     case Intrinsic::x86_mmx_pmovmskb:
12335     case Intrinsic::x86_sse2_pmovmskb_128: {
12336       // High bits of movmskp{s|d}, pmovmskb are known zero.
12337       switch (IntId) {
12338         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12339         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12340         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12341         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12342         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12343         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12344       }
12345       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12346                                         Mask.getBitWidth() - NumLoBits);
12347       break;
12348     }
12349     }
12350     break;
12351   }
12352   }
12353 }
12354
12355 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12356                                                          unsigned Depth) const {
12357   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12358   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12359     return Op.getValueType().getScalarType().getSizeInBits();
12360
12361   // Fallback case.
12362   return 1;
12363 }
12364
12365 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12366 /// node is a GlobalAddress + offset.
12367 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12368                                        const GlobalValue* &GA,
12369                                        int64_t &Offset) const {
12370   if (N->getOpcode() == X86ISD::Wrapper) {
12371     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12372       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12373       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12374       return true;
12375     }
12376   }
12377   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12378 }
12379
12380 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12381 /// same as extracting the high 128-bit part of 256-bit vector and then
12382 /// inserting the result into the low part of a new 256-bit vector
12383 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12384   EVT VT = SVOp->getValueType(0);
12385   int NumElems = VT.getVectorNumElements();
12386
12387   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12388   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12389     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12390         SVOp->getMaskElt(j) >= 0)
12391       return false;
12392
12393   return true;
12394 }
12395
12396 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12397 /// same as extracting the low 128-bit part of 256-bit vector and then
12398 /// inserting the result into the high part of a new 256-bit vector
12399 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12400   EVT VT = SVOp->getValueType(0);
12401   int NumElems = VT.getVectorNumElements();
12402
12403   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12404   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12405     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12406         SVOp->getMaskElt(j) >= 0)
12407       return false;
12408
12409   return true;
12410 }
12411
12412 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12413 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12414                                         TargetLowering::DAGCombinerInfo &DCI) {
12415   DebugLoc dl = N->getDebugLoc();
12416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12417   SDValue V1 = SVOp->getOperand(0);
12418   SDValue V2 = SVOp->getOperand(1);
12419   EVT VT = SVOp->getValueType(0);
12420   int NumElems = VT.getVectorNumElements();
12421
12422   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12423       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12424     //
12425     //                   0,0,0,...
12426     //                      |
12427     //    V      UNDEF    BUILD_VECTOR    UNDEF
12428     //     \      /           \           /
12429     //  CONCAT_VECTOR         CONCAT_VECTOR
12430     //         \                  /
12431     //          \                /
12432     //          RESULT: V + zero extended
12433     //
12434     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12435         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12436         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12437       return SDValue();
12438
12439     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12440       return SDValue();
12441
12442     // To match the shuffle mask, the first half of the mask should
12443     // be exactly the first vector, and all the rest a splat with the
12444     // first element of the second one.
12445     for (int i = 0; i < NumElems/2; ++i)
12446       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12447           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12448         return SDValue();
12449
12450     // Emit a zeroed vector and insert the desired subvector on its
12451     // first half.
12452     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12453     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12454                          DAG.getConstant(0, MVT::i32), DAG, dl);
12455     return DCI.CombineTo(N, InsV);
12456   }
12457
12458   //===--------------------------------------------------------------------===//
12459   // Combine some shuffles into subvector extracts and inserts:
12460   //
12461
12462   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12463   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12464     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12465                                     DAG, dl);
12466     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12467                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12468     return DCI.CombineTo(N, InsV);
12469   }
12470
12471   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12472   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12473     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12474     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12475                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12476     return DCI.CombineTo(N, InsV);
12477   }
12478
12479   return SDValue();
12480 }
12481
12482 /// PerformShuffleCombine - Performs several different shuffle combines.
12483 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12484                                      TargetLowering::DAGCombinerInfo &DCI,
12485                                      const X86Subtarget *Subtarget) {
12486   DebugLoc dl = N->getDebugLoc();
12487   EVT VT = N->getValueType(0);
12488
12489   // Don't create instructions with illegal types after legalize types has run.
12490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12491   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12492     return SDValue();
12493
12494   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12495   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12496       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12497     return PerformShuffleCombine256(N, DAG, DCI);
12498
12499   // Only handle 128 wide vector from here on.
12500   if (VT.getSizeInBits() != 128)
12501     return SDValue();
12502
12503   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12504   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12505   // consecutive, non-overlapping, and in the right order.
12506   SmallVector<SDValue, 16> Elts;
12507   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12508     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12509
12510   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12511 }
12512
12513 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12514 /// generation and convert it from being a bunch of shuffles and extracts
12515 /// to a simple store and scalar loads to extract the elements.
12516 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12517                                                 const TargetLowering &TLI) {
12518   SDValue InputVector = N->getOperand(0);
12519
12520   // Only operate on vectors of 4 elements, where the alternative shuffling
12521   // gets to be more expensive.
12522   if (InputVector.getValueType() != MVT::v4i32)
12523     return SDValue();
12524
12525   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12526   // single use which is a sign-extend or zero-extend, and all elements are
12527   // used.
12528   SmallVector<SDNode *, 4> Uses;
12529   unsigned ExtractedElements = 0;
12530   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12531        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12532     if (UI.getUse().getResNo() != InputVector.getResNo())
12533       return SDValue();
12534
12535     SDNode *Extract = *UI;
12536     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12537       return SDValue();
12538
12539     if (Extract->getValueType(0) != MVT::i32)
12540       return SDValue();
12541     if (!Extract->hasOneUse())
12542       return SDValue();
12543     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12544         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12545       return SDValue();
12546     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12547       return SDValue();
12548
12549     // Record which element was extracted.
12550     ExtractedElements |=
12551       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12552
12553     Uses.push_back(Extract);
12554   }
12555
12556   // If not all the elements were used, this may not be worthwhile.
12557   if (ExtractedElements != 15)
12558     return SDValue();
12559
12560   // Ok, we've now decided to do the transformation.
12561   DebugLoc dl = InputVector.getDebugLoc();
12562
12563   // Store the value to a temporary stack slot.
12564   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12565   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12566                             MachinePointerInfo(), false, false, 0);
12567
12568   // Replace each use (extract) with a load of the appropriate element.
12569   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12570        UE = Uses.end(); UI != UE; ++UI) {
12571     SDNode *Extract = *UI;
12572
12573     // cOMpute the element's address.
12574     SDValue Idx = Extract->getOperand(1);
12575     unsigned EltSize =
12576         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12577     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12578     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12579
12580     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12581                                      StackPtr, OffsetVal);
12582
12583     // Load the scalar.
12584     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12585                                      ScalarAddr, MachinePointerInfo(),
12586                                      false, false, 0);
12587
12588     // Replace the exact with the load.
12589     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12590   }
12591
12592   // The replacement was made in place; don't return anything.
12593   return SDValue();
12594 }
12595
12596 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12597 /// nodes.
12598 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12599                                     const X86Subtarget *Subtarget) {
12600   DebugLoc DL = N->getDebugLoc();
12601   SDValue Cond = N->getOperand(0);
12602   // Get the LHS/RHS of the select.
12603   SDValue LHS = N->getOperand(1);
12604   SDValue RHS = N->getOperand(2);
12605   EVT VT = LHS.getValueType();
12606
12607   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12608   // instructions match the semantics of the common C idiom x<y?x:y but not
12609   // x<=y?x:y, because of how they handle negative zero (which can be
12610   // ignored in unsafe-math mode).
12611   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12612       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12613       (Subtarget->hasXMMInt() ||
12614        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12615     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12616
12617     unsigned Opcode = 0;
12618     // Check for x CC y ? x : y.
12619     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12620         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12621       switch (CC) {
12622       default: break;
12623       case ISD::SETULT:
12624         // Converting this to a min would handle NaNs incorrectly, and swapping
12625         // the operands would cause it to handle comparisons between positive
12626         // and negative zero incorrectly.
12627         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12628           if (!UnsafeFPMath &&
12629               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12630             break;
12631           std::swap(LHS, RHS);
12632         }
12633         Opcode = X86ISD::FMIN;
12634         break;
12635       case ISD::SETOLE:
12636         // Converting this to a min would handle comparisons between positive
12637         // and negative zero incorrectly.
12638         if (!UnsafeFPMath &&
12639             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12640           break;
12641         Opcode = X86ISD::FMIN;
12642         break;
12643       case ISD::SETULE:
12644         // Converting this to a min would handle both negative zeros and NaNs
12645         // incorrectly, but we can swap the operands to fix both.
12646         std::swap(LHS, RHS);
12647       case ISD::SETOLT:
12648       case ISD::SETLT:
12649       case ISD::SETLE:
12650         Opcode = X86ISD::FMIN;
12651         break;
12652
12653       case ISD::SETOGE:
12654         // Converting this to a max would handle comparisons between positive
12655         // and negative zero incorrectly.
12656         if (!UnsafeFPMath &&
12657             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12658           break;
12659         Opcode = X86ISD::FMAX;
12660         break;
12661       case ISD::SETUGT:
12662         // Converting this to a max would handle NaNs incorrectly, and swapping
12663         // the operands would cause it to handle comparisons between positive
12664         // and negative zero incorrectly.
12665         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12666           if (!UnsafeFPMath &&
12667               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12668             break;
12669           std::swap(LHS, RHS);
12670         }
12671         Opcode = X86ISD::FMAX;
12672         break;
12673       case ISD::SETUGE:
12674         // Converting this to a max would handle both negative zeros and NaNs
12675         // incorrectly, but we can swap the operands to fix both.
12676         std::swap(LHS, RHS);
12677       case ISD::SETOGT:
12678       case ISD::SETGT:
12679       case ISD::SETGE:
12680         Opcode = X86ISD::FMAX;
12681         break;
12682       }
12683     // Check for x CC y ? y : x -- a min/max with reversed arms.
12684     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12685                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12686       switch (CC) {
12687       default: break;
12688       case ISD::SETOGE:
12689         // Converting this to a min would handle comparisons between positive
12690         // and negative zero incorrectly, and swapping the operands would
12691         // cause it to handle NaNs incorrectly.
12692         if (!UnsafeFPMath &&
12693             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12694           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12695             break;
12696           std::swap(LHS, RHS);
12697         }
12698         Opcode = X86ISD::FMIN;
12699         break;
12700       case ISD::SETUGT:
12701         // Converting this to a min would handle NaNs incorrectly.
12702         if (!UnsafeFPMath &&
12703             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12704           break;
12705         Opcode = X86ISD::FMIN;
12706         break;
12707       case ISD::SETUGE:
12708         // Converting this to a min would handle both negative zeros and NaNs
12709         // incorrectly, but we can swap the operands to fix both.
12710         std::swap(LHS, RHS);
12711       case ISD::SETOGT:
12712       case ISD::SETGT:
12713       case ISD::SETGE:
12714         Opcode = X86ISD::FMIN;
12715         break;
12716
12717       case ISD::SETULT:
12718         // Converting this to a max would handle NaNs incorrectly.
12719         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12720           break;
12721         Opcode = X86ISD::FMAX;
12722         break;
12723       case ISD::SETOLE:
12724         // Converting this to a max would handle comparisons between positive
12725         // and negative zero incorrectly, and swapping the operands would
12726         // cause it to handle NaNs incorrectly.
12727         if (!UnsafeFPMath &&
12728             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12729           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12730             break;
12731           std::swap(LHS, RHS);
12732         }
12733         Opcode = X86ISD::FMAX;
12734         break;
12735       case ISD::SETULE:
12736         // Converting this to a max would handle both negative zeros and NaNs
12737         // incorrectly, but we can swap the operands to fix both.
12738         std::swap(LHS, RHS);
12739       case ISD::SETOLT:
12740       case ISD::SETLT:
12741       case ISD::SETLE:
12742         Opcode = X86ISD::FMAX;
12743         break;
12744       }
12745     }
12746
12747     if (Opcode)
12748       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12749   }
12750
12751   // If this is a select between two integer constants, try to do some
12752   // optimizations.
12753   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12754     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12755       // Don't do this for crazy integer types.
12756       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12757         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12758         // so that TrueC (the true value) is larger than FalseC.
12759         bool NeedsCondInvert = false;
12760
12761         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12762             // Efficiently invertible.
12763             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12764              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12765               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12766           NeedsCondInvert = true;
12767           std::swap(TrueC, FalseC);
12768         }
12769
12770         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12771         if (FalseC->getAPIntValue() == 0 &&
12772             TrueC->getAPIntValue().isPowerOf2()) {
12773           if (NeedsCondInvert) // Invert the condition if needed.
12774             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12775                                DAG.getConstant(1, Cond.getValueType()));
12776
12777           // Zero extend the condition if needed.
12778           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12779
12780           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12781           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12782                              DAG.getConstant(ShAmt, MVT::i8));
12783         }
12784
12785         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12786         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12787           if (NeedsCondInvert) // Invert the condition if needed.
12788             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12789                                DAG.getConstant(1, Cond.getValueType()));
12790
12791           // Zero extend the condition if needed.
12792           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12793                              FalseC->getValueType(0), Cond);
12794           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12795                              SDValue(FalseC, 0));
12796         }
12797
12798         // Optimize cases that will turn into an LEA instruction.  This requires
12799         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12800         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12801           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12802           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12803
12804           bool isFastMultiplier = false;
12805           if (Diff < 10) {
12806             switch ((unsigned char)Diff) {
12807               default: break;
12808               case 1:  // result = add base, cond
12809               case 2:  // result = lea base(    , cond*2)
12810               case 3:  // result = lea base(cond, cond*2)
12811               case 4:  // result = lea base(    , cond*4)
12812               case 5:  // result = lea base(cond, cond*4)
12813               case 8:  // result = lea base(    , cond*8)
12814               case 9:  // result = lea base(cond, cond*8)
12815                 isFastMultiplier = true;
12816                 break;
12817             }
12818           }
12819
12820           if (isFastMultiplier) {
12821             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12822             if (NeedsCondInvert) // Invert the condition if needed.
12823               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12824                                  DAG.getConstant(1, Cond.getValueType()));
12825
12826             // Zero extend the condition if needed.
12827             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12828                                Cond);
12829             // Scale the condition by the difference.
12830             if (Diff != 1)
12831               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12832                                  DAG.getConstant(Diff, Cond.getValueType()));
12833
12834             // Add the base if non-zero.
12835             if (FalseC->getAPIntValue() != 0)
12836               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12837                                  SDValue(FalseC, 0));
12838             return Cond;
12839           }
12840         }
12841       }
12842   }
12843
12844   return SDValue();
12845 }
12846
12847 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12848 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12849                                   TargetLowering::DAGCombinerInfo &DCI) {
12850   DebugLoc DL = N->getDebugLoc();
12851
12852   // If the flag operand isn't dead, don't touch this CMOV.
12853   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12854     return SDValue();
12855
12856   SDValue FalseOp = N->getOperand(0);
12857   SDValue TrueOp = N->getOperand(1);
12858   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12859   SDValue Cond = N->getOperand(3);
12860   if (CC == X86::COND_E || CC == X86::COND_NE) {
12861     switch (Cond.getOpcode()) {
12862     default: break;
12863     case X86ISD::BSR:
12864     case X86ISD::BSF:
12865       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12866       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12867         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12868     }
12869   }
12870
12871   // If this is a select between two integer constants, try to do some
12872   // optimizations.  Note that the operands are ordered the opposite of SELECT
12873   // operands.
12874   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12875     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12876       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12877       // larger than FalseC (the false value).
12878       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12879         CC = X86::GetOppositeBranchCondition(CC);
12880         std::swap(TrueC, FalseC);
12881       }
12882
12883       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12884       // This is efficient for any integer data type (including i8/i16) and
12885       // shift amount.
12886       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12887         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12888                            DAG.getConstant(CC, MVT::i8), Cond);
12889
12890         // Zero extend the condition if needed.
12891         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12892
12893         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12894         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12895                            DAG.getConstant(ShAmt, MVT::i8));
12896         if (N->getNumValues() == 2)  // Dead flag value?
12897           return DCI.CombineTo(N, Cond, SDValue());
12898         return Cond;
12899       }
12900
12901       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12902       // for any integer data type, including i8/i16.
12903       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12904         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12905                            DAG.getConstant(CC, MVT::i8), Cond);
12906
12907         // Zero extend the condition if needed.
12908         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12909                            FalseC->getValueType(0), Cond);
12910         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12911                            SDValue(FalseC, 0));
12912
12913         if (N->getNumValues() == 2)  // Dead flag value?
12914           return DCI.CombineTo(N, Cond, SDValue());
12915         return Cond;
12916       }
12917
12918       // Optimize cases that will turn into an LEA instruction.  This requires
12919       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12920       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12921         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12922         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12923
12924         bool isFastMultiplier = false;
12925         if (Diff < 10) {
12926           switch ((unsigned char)Diff) {
12927           default: break;
12928           case 1:  // result = add base, cond
12929           case 2:  // result = lea base(    , cond*2)
12930           case 3:  // result = lea base(cond, cond*2)
12931           case 4:  // result = lea base(    , cond*4)
12932           case 5:  // result = lea base(cond, cond*4)
12933           case 8:  // result = lea base(    , cond*8)
12934           case 9:  // result = lea base(cond, cond*8)
12935             isFastMultiplier = true;
12936             break;
12937           }
12938         }
12939
12940         if (isFastMultiplier) {
12941           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12942           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12943                              DAG.getConstant(CC, MVT::i8), Cond);
12944           // Zero extend the condition if needed.
12945           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12946                              Cond);
12947           // Scale the condition by the difference.
12948           if (Diff != 1)
12949             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12950                                DAG.getConstant(Diff, Cond.getValueType()));
12951
12952           // Add the base if non-zero.
12953           if (FalseC->getAPIntValue() != 0)
12954             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12955                                SDValue(FalseC, 0));
12956           if (N->getNumValues() == 2)  // Dead flag value?
12957             return DCI.CombineTo(N, Cond, SDValue());
12958           return Cond;
12959         }
12960       }
12961     }
12962   }
12963   return SDValue();
12964 }
12965
12966
12967 /// PerformMulCombine - Optimize a single multiply with constant into two
12968 /// in order to implement it with two cheaper instructions, e.g.
12969 /// LEA + SHL, LEA + LEA.
12970 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12971                                  TargetLowering::DAGCombinerInfo &DCI) {
12972   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12973     return SDValue();
12974
12975   EVT VT = N->getValueType(0);
12976   if (VT != MVT::i64)
12977     return SDValue();
12978
12979   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12980   if (!C)
12981     return SDValue();
12982   uint64_t MulAmt = C->getZExtValue();
12983   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12984     return SDValue();
12985
12986   uint64_t MulAmt1 = 0;
12987   uint64_t MulAmt2 = 0;
12988   if ((MulAmt % 9) == 0) {
12989     MulAmt1 = 9;
12990     MulAmt2 = MulAmt / 9;
12991   } else if ((MulAmt % 5) == 0) {
12992     MulAmt1 = 5;
12993     MulAmt2 = MulAmt / 5;
12994   } else if ((MulAmt % 3) == 0) {
12995     MulAmt1 = 3;
12996     MulAmt2 = MulAmt / 3;
12997   }
12998   if (MulAmt2 &&
12999       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13000     DebugLoc DL = N->getDebugLoc();
13001
13002     if (isPowerOf2_64(MulAmt2) &&
13003         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13004       // If second multiplifer is pow2, issue it first. We want the multiply by
13005       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13006       // is an add.
13007       std::swap(MulAmt1, MulAmt2);
13008
13009     SDValue NewMul;
13010     if (isPowerOf2_64(MulAmt1))
13011       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13012                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13013     else
13014       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13015                            DAG.getConstant(MulAmt1, VT));
13016
13017     if (isPowerOf2_64(MulAmt2))
13018       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13019                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13020     else
13021       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13022                            DAG.getConstant(MulAmt2, VT));
13023
13024     // Do not add new nodes to DAG combiner worklist.
13025     DCI.CombineTo(N, NewMul, false);
13026   }
13027   return SDValue();
13028 }
13029
13030 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13031   SDValue N0 = N->getOperand(0);
13032   SDValue N1 = N->getOperand(1);
13033   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13034   EVT VT = N0.getValueType();
13035
13036   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13037   // since the result of setcc_c is all zero's or all ones.
13038   if (N1C && N0.getOpcode() == ISD::AND &&
13039       N0.getOperand(1).getOpcode() == ISD::Constant) {
13040     SDValue N00 = N0.getOperand(0);
13041     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13042         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13043           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13044          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13045       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13046       APInt ShAmt = N1C->getAPIntValue();
13047       Mask = Mask.shl(ShAmt);
13048       if (Mask != 0)
13049         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13050                            N00, DAG.getConstant(Mask, VT));
13051     }
13052   }
13053
13054   return SDValue();
13055 }
13056
13057 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13058 ///                       when possible.
13059 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13060                                    const X86Subtarget *Subtarget) {
13061   EVT VT = N->getValueType(0);
13062   if (!VT.isVector() && VT.isInteger() &&
13063       N->getOpcode() == ISD::SHL)
13064     return PerformSHLCombine(N, DAG);
13065
13066   // On X86 with SSE2 support, we can transform this to a vector shift if
13067   // all elements are shifted by the same amount.  We can't do this in legalize
13068   // because the a constant vector is typically transformed to a constant pool
13069   // so we have no knowledge of the shift amount.
13070   if (!Subtarget->hasXMMInt())
13071     return SDValue();
13072
13073   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13074     return SDValue();
13075
13076   SDValue ShAmtOp = N->getOperand(1);
13077   EVT EltVT = VT.getVectorElementType();
13078   DebugLoc DL = N->getDebugLoc();
13079   SDValue BaseShAmt = SDValue();
13080   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13081     unsigned NumElts = VT.getVectorNumElements();
13082     unsigned i = 0;
13083     for (; i != NumElts; ++i) {
13084       SDValue Arg = ShAmtOp.getOperand(i);
13085       if (Arg.getOpcode() == ISD::UNDEF) continue;
13086       BaseShAmt = Arg;
13087       break;
13088     }
13089     for (; i != NumElts; ++i) {
13090       SDValue Arg = ShAmtOp.getOperand(i);
13091       if (Arg.getOpcode() == ISD::UNDEF) continue;
13092       if (Arg != BaseShAmt) {
13093         return SDValue();
13094       }
13095     }
13096   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13097              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13098     SDValue InVec = ShAmtOp.getOperand(0);
13099     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13100       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13101       unsigned i = 0;
13102       for (; i != NumElts; ++i) {
13103         SDValue Arg = InVec.getOperand(i);
13104         if (Arg.getOpcode() == ISD::UNDEF) continue;
13105         BaseShAmt = Arg;
13106         break;
13107       }
13108     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13109        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13110          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13111          if (C->getZExtValue() == SplatIdx)
13112            BaseShAmt = InVec.getOperand(1);
13113        }
13114     }
13115     if (BaseShAmt.getNode() == 0)
13116       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13117                               DAG.getIntPtrConstant(0));
13118   } else
13119     return SDValue();
13120
13121   // The shift amount is an i32.
13122   if (EltVT.bitsGT(MVT::i32))
13123     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13124   else if (EltVT.bitsLT(MVT::i32))
13125     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13126
13127   // The shift amount is identical so we can do a vector shift.
13128   SDValue  ValOp = N->getOperand(0);
13129   switch (N->getOpcode()) {
13130   default:
13131     llvm_unreachable("Unknown shift opcode!");
13132     break;
13133   case ISD::SHL:
13134     if (VT == MVT::v2i64)
13135       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13136                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13137                          ValOp, BaseShAmt);
13138     if (VT == MVT::v4i32)
13139       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13140                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13141                          ValOp, BaseShAmt);
13142     if (VT == MVT::v8i16)
13143       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13144                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13145                          ValOp, BaseShAmt);
13146     break;
13147   case ISD::SRA:
13148     if (VT == MVT::v4i32)
13149       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13150                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13151                          ValOp, BaseShAmt);
13152     if (VT == MVT::v8i16)
13153       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13154                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13155                          ValOp, BaseShAmt);
13156     break;
13157   case ISD::SRL:
13158     if (VT == MVT::v2i64)
13159       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13160                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13161                          ValOp, BaseShAmt);
13162     if (VT == MVT::v4i32)
13163       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13164                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13165                          ValOp, BaseShAmt);
13166     if (VT ==  MVT::v8i16)
13167       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13168                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13169                          ValOp, BaseShAmt);
13170     break;
13171   }
13172   return SDValue();
13173 }
13174
13175
13176 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13177 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13178 // and friends.  Likewise for OR -> CMPNEQSS.
13179 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13180                             TargetLowering::DAGCombinerInfo &DCI,
13181                             const X86Subtarget *Subtarget) {
13182   unsigned opcode;
13183
13184   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13185   // we're requiring SSE2 for both.
13186   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13187     SDValue N0 = N->getOperand(0);
13188     SDValue N1 = N->getOperand(1);
13189     SDValue CMP0 = N0->getOperand(1);
13190     SDValue CMP1 = N1->getOperand(1);
13191     DebugLoc DL = N->getDebugLoc();
13192
13193     // The SETCCs should both refer to the same CMP.
13194     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13195       return SDValue();
13196
13197     SDValue CMP00 = CMP0->getOperand(0);
13198     SDValue CMP01 = CMP0->getOperand(1);
13199     EVT     VT    = CMP00.getValueType();
13200
13201     if (VT == MVT::f32 || VT == MVT::f64) {
13202       bool ExpectingFlags = false;
13203       // Check for any users that want flags:
13204       for (SDNode::use_iterator UI = N->use_begin(),
13205              UE = N->use_end();
13206            !ExpectingFlags && UI != UE; ++UI)
13207         switch (UI->getOpcode()) {
13208         default:
13209         case ISD::BR_CC:
13210         case ISD::BRCOND:
13211         case ISD::SELECT:
13212           ExpectingFlags = true;
13213           break;
13214         case ISD::CopyToReg:
13215         case ISD::SIGN_EXTEND:
13216         case ISD::ZERO_EXTEND:
13217         case ISD::ANY_EXTEND:
13218           break;
13219         }
13220
13221       if (!ExpectingFlags) {
13222         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13223         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13224
13225         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13226           X86::CondCode tmp = cc0;
13227           cc0 = cc1;
13228           cc1 = tmp;
13229         }
13230
13231         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13232             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13233           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13234           X86ISD::NodeType NTOperator = is64BitFP ?
13235             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13236           // FIXME: need symbolic constants for these magic numbers.
13237           // See X86ATTInstPrinter.cpp:printSSECC().
13238           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13239           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13240                                               DAG.getConstant(x86cc, MVT::i8));
13241           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13242                                               OnesOrZeroesF);
13243           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13244                                       DAG.getConstant(1, MVT::i32));
13245           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13246           return OneBitOfTruth;
13247         }
13248       }
13249     }
13250   }
13251   return SDValue();
13252 }
13253
13254 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13255 /// so it can be folded inside ANDNP.
13256 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13257   EVT VT = N->getValueType(0);
13258
13259   // Match direct AllOnes for 128 and 256-bit vectors
13260   if (ISD::isBuildVectorAllOnes(N))
13261     return true;
13262
13263   // Look through a bit convert.
13264   if (N->getOpcode() == ISD::BITCAST)
13265     N = N->getOperand(0).getNode();
13266
13267   // Sometimes the operand may come from a insert_subvector building a 256-bit
13268   // allones vector
13269   if (VT.getSizeInBits() == 256 &&
13270       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13271     SDValue V1 = N->getOperand(0);
13272     SDValue V2 = N->getOperand(1);
13273
13274     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13275         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13276         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13277         ISD::isBuildVectorAllOnes(V2.getNode()))
13278       return true;
13279   }
13280
13281   return false;
13282 }
13283
13284 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13285                                  TargetLowering::DAGCombinerInfo &DCI,
13286                                  const X86Subtarget *Subtarget) {
13287   if (DCI.isBeforeLegalizeOps())
13288     return SDValue();
13289
13290   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13291   if (R.getNode())
13292     return R;
13293
13294   // Want to form ANDNP nodes:
13295   // 1) In the hopes of then easily combining them with OR and AND nodes
13296   //    to form PBLEND/PSIGN.
13297   // 2) To match ANDN packed intrinsics
13298   EVT VT = N->getValueType(0);
13299   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13300     return SDValue();
13301
13302   SDValue N0 = N->getOperand(0);
13303   SDValue N1 = N->getOperand(1);
13304   DebugLoc DL = N->getDebugLoc();
13305
13306   // Check LHS for vnot
13307   if (N0.getOpcode() == ISD::XOR &&
13308       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13309       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13310     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13311
13312   // Check RHS for vnot
13313   if (N1.getOpcode() == ISD::XOR &&
13314       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13315       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13316     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13317
13318   return SDValue();
13319 }
13320
13321 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13322                                 TargetLowering::DAGCombinerInfo &DCI,
13323                                 const X86Subtarget *Subtarget) {
13324   if (DCI.isBeforeLegalizeOps())
13325     return SDValue();
13326
13327   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13328   if (R.getNode())
13329     return R;
13330
13331   EVT VT = N->getValueType(0);
13332   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13333     return SDValue();
13334
13335   SDValue N0 = N->getOperand(0);
13336   SDValue N1 = N->getOperand(1);
13337
13338   // look for psign/blend
13339   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13340     if (VT == MVT::v2i64) {
13341       // Canonicalize pandn to RHS
13342       if (N0.getOpcode() == X86ISD::ANDNP)
13343         std::swap(N0, N1);
13344       // or (and (m, x), (pandn m, y))
13345       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13346         SDValue Mask = N1.getOperand(0);
13347         SDValue X    = N1.getOperand(1);
13348         SDValue Y;
13349         if (N0.getOperand(0) == Mask)
13350           Y = N0.getOperand(1);
13351         if (N0.getOperand(1) == Mask)
13352           Y = N0.getOperand(0);
13353
13354         // Check to see if the mask appeared in both the AND and ANDNP and
13355         if (!Y.getNode())
13356           return SDValue();
13357
13358         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13359         if (Mask.getOpcode() != ISD::BITCAST ||
13360             X.getOpcode() != ISD::BITCAST ||
13361             Y.getOpcode() != ISD::BITCAST)
13362           return SDValue();
13363
13364         // Look through mask bitcast.
13365         Mask = Mask.getOperand(0);
13366         EVT MaskVT = Mask.getValueType();
13367
13368         // Validate that the Mask operand is a vector sra node.  The sra node
13369         // will be an intrinsic.
13370         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13371           return SDValue();
13372
13373         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13374         // there is no psrai.b
13375         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13376         case Intrinsic::x86_sse2_psrai_w:
13377         case Intrinsic::x86_sse2_psrai_d:
13378           break;
13379         default: return SDValue();
13380         }
13381
13382         // Check that the SRA is all signbits.
13383         SDValue SraC = Mask.getOperand(2);
13384         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13385         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13386         if ((SraAmt + 1) != EltBits)
13387           return SDValue();
13388
13389         DebugLoc DL = N->getDebugLoc();
13390
13391         // Now we know we at least have a plendvb with the mask val.  See if
13392         // we can form a psignb/w/d.
13393         // psign = x.type == y.type == mask.type && y = sub(0, x);
13394         X = X.getOperand(0);
13395         Y = Y.getOperand(0);
13396         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13397             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13398             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13399           unsigned Opc = 0;
13400           switch (EltBits) {
13401           case 8: Opc = X86ISD::PSIGNB; break;
13402           case 16: Opc = X86ISD::PSIGNW; break;
13403           case 32: Opc = X86ISD::PSIGND; break;
13404           default: break;
13405           }
13406           if (Opc) {
13407             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13408             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13409           }
13410         }
13411         // PBLENDVB only available on SSE 4.1
13412         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13413           return SDValue();
13414
13415         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13416         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13417         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13418         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13419         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13420       }
13421     }
13422   }
13423
13424   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13425   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13426     std::swap(N0, N1);
13427   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13428     return SDValue();
13429   if (!N0.hasOneUse() || !N1.hasOneUse())
13430     return SDValue();
13431
13432   SDValue ShAmt0 = N0.getOperand(1);
13433   if (ShAmt0.getValueType() != MVT::i8)
13434     return SDValue();
13435   SDValue ShAmt1 = N1.getOperand(1);
13436   if (ShAmt1.getValueType() != MVT::i8)
13437     return SDValue();
13438   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13439     ShAmt0 = ShAmt0.getOperand(0);
13440   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13441     ShAmt1 = ShAmt1.getOperand(0);
13442
13443   DebugLoc DL = N->getDebugLoc();
13444   unsigned Opc = X86ISD::SHLD;
13445   SDValue Op0 = N0.getOperand(0);
13446   SDValue Op1 = N1.getOperand(0);
13447   if (ShAmt0.getOpcode() == ISD::SUB) {
13448     Opc = X86ISD::SHRD;
13449     std::swap(Op0, Op1);
13450     std::swap(ShAmt0, ShAmt1);
13451   }
13452
13453   unsigned Bits = VT.getSizeInBits();
13454   if (ShAmt1.getOpcode() == ISD::SUB) {
13455     SDValue Sum = ShAmt1.getOperand(0);
13456     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13457       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13458       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13459         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13460       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13461         return DAG.getNode(Opc, DL, VT,
13462                            Op0, Op1,
13463                            DAG.getNode(ISD::TRUNCATE, DL,
13464                                        MVT::i8, ShAmt0));
13465     }
13466   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13467     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13468     if (ShAmt0C &&
13469         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13470       return DAG.getNode(Opc, DL, VT,
13471                          N0.getOperand(0), N1.getOperand(0),
13472                          DAG.getNode(ISD::TRUNCATE, DL,
13473                                        MVT::i8, ShAmt0));
13474   }
13475
13476   return SDValue();
13477 }
13478
13479 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13480 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13481                                    const X86Subtarget *Subtarget) {
13482   LoadSDNode *Ld = cast<LoadSDNode>(N);
13483   EVT RegVT = Ld->getValueType(0);
13484   EVT MemVT = Ld->getMemoryVT();
13485   DebugLoc dl = Ld->getDebugLoc();
13486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13487
13488   ISD::LoadExtType Ext = Ld->getExtensionType();
13489
13490   // If this is a vector EXT Load then attempt to optimize it using a
13491   // shuffle. We need SSE4 for the shuffles.
13492   // TODO: It is possible to support ZExt by zeroing the undef values
13493   // during the shuffle phase or after the shuffle.
13494   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13495     assert(MemVT != RegVT && "Cannot extend to the same type");
13496     assert(MemVT.isVector() && "Must load a vector from memory");
13497
13498     unsigned NumElems = RegVT.getVectorNumElements();
13499     unsigned RegSz = RegVT.getSizeInBits();
13500     unsigned MemSz = MemVT.getSizeInBits();
13501     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13502     // All sizes must be a power of two
13503     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13504
13505     // Attempt to load the original value using a single load op.
13506     // Find a scalar type which is equal to the loaded word size.
13507     MVT SclrLoadTy = MVT::i8;
13508     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13509          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13510       MVT Tp = (MVT::SimpleValueType)tp;
13511       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13512         SclrLoadTy = Tp;
13513         break;
13514       }
13515     }
13516
13517     // Proceed if a load word is found.
13518     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13519
13520     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13521       RegSz/SclrLoadTy.getSizeInBits());
13522
13523     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13524                                   RegSz/MemVT.getScalarType().getSizeInBits());
13525     // Can't shuffle using an illegal type.
13526     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13527
13528     // Perform a single load.
13529     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13530                                   Ld->getBasePtr(),
13531                                   Ld->getPointerInfo(), Ld->isVolatile(),
13532                                   Ld->isNonTemporal(), Ld->getAlignment());
13533
13534     // Insert the word loaded into a vector.
13535     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13536       LoadUnitVecVT, ScalarLoad);
13537
13538     // Bitcast the loaded value to a vector of the original element type, in
13539     // the size of the target vector type.
13540     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13541     unsigned SizeRatio = RegSz/MemSz;
13542
13543     // Redistribute the loaded elements into the different locations.
13544     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13545     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13546
13547     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13548                                 DAG.getUNDEF(SlicedVec.getValueType()),
13549                                 ShuffleVec.data());
13550
13551     // Bitcast to the requested type.
13552     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13553     // Replace the original load with the new sequence
13554     // and return the new chain.
13555     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13556     return SDValue(ScalarLoad.getNode(), 1);
13557   }
13558
13559   return SDValue();
13560 }
13561
13562 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13563 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13564                                    const X86Subtarget *Subtarget) {
13565   StoreSDNode *St = cast<StoreSDNode>(N);
13566   EVT VT = St->getValue().getValueType();
13567   EVT StVT = St->getMemoryVT();
13568   DebugLoc dl = St->getDebugLoc();
13569   SDValue StoredVal = St->getOperand(1);
13570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13571
13572   // If we are saving a concatination of two XMM registers, perform two stores.
13573   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13574   // 128-bit ones. If in the future the cost becomes only one memory access the
13575   // first version would be better.
13576   if (VT.getSizeInBits() == 256 &&
13577     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13578     StoredVal.getNumOperands() == 2) {
13579
13580     SDValue Value0 = StoredVal.getOperand(0);
13581     SDValue Value1 = StoredVal.getOperand(1);
13582
13583     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13584     SDValue Ptr0 = St->getBasePtr();
13585     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13586
13587     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13588                                 St->getPointerInfo(), St->isVolatile(),
13589                                 St->isNonTemporal(), St->getAlignment());
13590     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13591                                 St->getPointerInfo(), St->isVolatile(),
13592                                 St->isNonTemporal(), St->getAlignment());
13593     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13594   }
13595
13596   // Optimize trunc store (of multiple scalars) to shuffle and store.
13597   // First, pack all of the elements in one place. Next, store to memory
13598   // in fewer chunks.
13599   if (St->isTruncatingStore() && VT.isVector()) {
13600     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13601     unsigned NumElems = VT.getVectorNumElements();
13602     assert(StVT != VT && "Cannot truncate to the same type");
13603     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13604     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13605
13606     // From, To sizes and ElemCount must be pow of two
13607     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13608     // We are going to use the original vector elt for storing.
13609     // Accumulated smaller vector elements must be a multiple of the store size.
13610     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13611
13612     unsigned SizeRatio  = FromSz / ToSz;
13613
13614     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13615
13616     // Create a type on which we perform the shuffle
13617     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13618             StVT.getScalarType(), NumElems*SizeRatio);
13619
13620     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13621
13622     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13623     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13624     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13625
13626     // Can't shuffle using an illegal type
13627     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13628
13629     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13630                                 DAG.getUNDEF(WideVec.getValueType()),
13631                                 ShuffleVec.data());
13632     // At this point all of the data is stored at the bottom of the
13633     // register. We now need to save it to mem.
13634
13635     // Find the largest store unit
13636     MVT StoreType = MVT::i8;
13637     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13638          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13639       MVT Tp = (MVT::SimpleValueType)tp;
13640       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13641         StoreType = Tp;
13642     }
13643
13644     // Bitcast the original vector into a vector of store-size units
13645     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13646             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13647     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13648     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13649     SmallVector<SDValue, 8> Chains;
13650     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13651                                         TLI.getPointerTy());
13652     SDValue Ptr = St->getBasePtr();
13653
13654     // Perform one or more big stores into memory.
13655     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13656       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13657                                    StoreType, ShuffWide,
13658                                    DAG.getIntPtrConstant(i));
13659       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13660                                 St->getPointerInfo(), St->isVolatile(),
13661                                 St->isNonTemporal(), St->getAlignment());
13662       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13663       Chains.push_back(Ch);
13664     }
13665
13666     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13667                                Chains.size());
13668   }
13669
13670
13671   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13672   // the FP state in cases where an emms may be missing.
13673   // A preferable solution to the general problem is to figure out the right
13674   // places to insert EMMS.  This qualifies as a quick hack.
13675
13676   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13677   if (VT.getSizeInBits() != 64)
13678     return SDValue();
13679
13680   const Function *F = DAG.getMachineFunction().getFunction();
13681   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13682   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13683                      && Subtarget->hasXMMInt();
13684   if ((VT.isVector() ||
13685        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13686       isa<LoadSDNode>(St->getValue()) &&
13687       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13688       St->getChain().hasOneUse() && !St->isVolatile()) {
13689     SDNode* LdVal = St->getValue().getNode();
13690     LoadSDNode *Ld = 0;
13691     int TokenFactorIndex = -1;
13692     SmallVector<SDValue, 8> Ops;
13693     SDNode* ChainVal = St->getChain().getNode();
13694     // Must be a store of a load.  We currently handle two cases:  the load
13695     // is a direct child, and it's under an intervening TokenFactor.  It is
13696     // possible to dig deeper under nested TokenFactors.
13697     if (ChainVal == LdVal)
13698       Ld = cast<LoadSDNode>(St->getChain());
13699     else if (St->getValue().hasOneUse() &&
13700              ChainVal->getOpcode() == ISD::TokenFactor) {
13701       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13702         if (ChainVal->getOperand(i).getNode() == LdVal) {
13703           TokenFactorIndex = i;
13704           Ld = cast<LoadSDNode>(St->getValue());
13705         } else
13706           Ops.push_back(ChainVal->getOperand(i));
13707       }
13708     }
13709
13710     if (!Ld || !ISD::isNormalLoad(Ld))
13711       return SDValue();
13712
13713     // If this is not the MMX case, i.e. we are just turning i64 load/store
13714     // into f64 load/store, avoid the transformation if there are multiple
13715     // uses of the loaded value.
13716     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13717       return SDValue();
13718
13719     DebugLoc LdDL = Ld->getDebugLoc();
13720     DebugLoc StDL = N->getDebugLoc();
13721     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13722     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13723     // pair instead.
13724     if (Subtarget->is64Bit() || F64IsLegal) {
13725       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13726       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13727                                   Ld->getPointerInfo(), Ld->isVolatile(),
13728                                   Ld->isNonTemporal(), Ld->getAlignment());
13729       SDValue NewChain = NewLd.getValue(1);
13730       if (TokenFactorIndex != -1) {
13731         Ops.push_back(NewChain);
13732         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13733                                Ops.size());
13734       }
13735       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13736                           St->getPointerInfo(),
13737                           St->isVolatile(), St->isNonTemporal(),
13738                           St->getAlignment());
13739     }
13740
13741     // Otherwise, lower to two pairs of 32-bit loads / stores.
13742     SDValue LoAddr = Ld->getBasePtr();
13743     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13744                                  DAG.getConstant(4, MVT::i32));
13745
13746     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13747                                Ld->getPointerInfo(),
13748                                Ld->isVolatile(), Ld->isNonTemporal(),
13749                                Ld->getAlignment());
13750     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13751                                Ld->getPointerInfo().getWithOffset(4),
13752                                Ld->isVolatile(), Ld->isNonTemporal(),
13753                                MinAlign(Ld->getAlignment(), 4));
13754
13755     SDValue NewChain = LoLd.getValue(1);
13756     if (TokenFactorIndex != -1) {
13757       Ops.push_back(LoLd);
13758       Ops.push_back(HiLd);
13759       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13760                              Ops.size());
13761     }
13762
13763     LoAddr = St->getBasePtr();
13764     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13765                          DAG.getConstant(4, MVT::i32));
13766
13767     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13768                                 St->getPointerInfo(),
13769                                 St->isVolatile(), St->isNonTemporal(),
13770                                 St->getAlignment());
13771     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13772                                 St->getPointerInfo().getWithOffset(4),
13773                                 St->isVolatile(),
13774                                 St->isNonTemporal(),
13775                                 MinAlign(St->getAlignment(), 4));
13776     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13777   }
13778   return SDValue();
13779 }
13780
13781 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
13782 /// and return the operands for the horizontal operation in LHS and RHS.  A
13783 /// horizontal operation performs the binary operation on successive elements
13784 /// of its first operand, then on successive elements of its second operand,
13785 /// returning the resulting values in a vector.  For example, if
13786 ///   A = < float a0, float a1, float a2, float a3 >
13787 /// and
13788 ///   B = < float b0, float b1, float b2, float b3 >
13789 /// then the result of doing a horizontal operation on A and B is
13790 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
13791 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
13792 /// A horizontal-op B, for some already available A and B, and if so then LHS is
13793 /// set to A, RHS to B, and the routine returns 'true'.
13794 /// Note that the binary operation should have the property that if one of the
13795 /// operands is UNDEF then the result is UNDEF.
13796 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
13797   // Look for the following pattern: if
13798   //   A = < float a0, float a1, float a2, float a3 >
13799   //   B = < float b0, float b1, float b2, float b3 >
13800   // and
13801   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
13802   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
13803   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
13804   // which is A horizontal-op B.
13805
13806   // At least one of the operands should be a vector shuffle.
13807   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13808       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
13809     return false;
13810
13811   EVT VT = LHS.getValueType();
13812   unsigned N = VT.getVectorNumElements();
13813
13814   // View LHS in the form
13815   //   LHS = VECTOR_SHUFFLE A, B, LMask
13816   // If LHS is not a shuffle then pretend it is the shuffle
13817   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
13818   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
13819   // type VT.
13820   SDValue A, B;
13821   SmallVector<int, 8> LMask(N);
13822   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13823     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
13824       A = LHS.getOperand(0);
13825     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
13826       B = LHS.getOperand(1);
13827     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
13828   } else {
13829     if (LHS.getOpcode() != ISD::UNDEF)
13830       A = LHS;
13831     for (unsigned i = 0; i != N; ++i)
13832       LMask[i] = i;
13833   }
13834
13835   // Likewise, view RHS in the form
13836   //   RHS = VECTOR_SHUFFLE C, D, RMask
13837   SDValue C, D;
13838   SmallVector<int, 8> RMask(N);
13839   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13840     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
13841       C = RHS.getOperand(0);
13842     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
13843       D = RHS.getOperand(1);
13844     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
13845   } else {
13846     if (RHS.getOpcode() != ISD::UNDEF)
13847       C = RHS;
13848     for (unsigned i = 0; i != N; ++i)
13849       RMask[i] = i;
13850   }
13851
13852   // Check that the shuffles are both shuffling the same vectors.
13853   if (!(A == C && B == D) && !(A == D && B == C))
13854     return false;
13855
13856   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
13857   if (!A.getNode() && !B.getNode())
13858     return false;
13859
13860   // If A and B occur in reverse order in RHS, then "swap" them (which means
13861   // rewriting the mask).
13862   if (A != C)
13863     for (unsigned i = 0; i != N; ++i) {
13864       unsigned Idx = RMask[i];
13865       if (Idx < N)
13866         RMask[i] += N;
13867       else if (Idx < 2*N)
13868         RMask[i] -= N;
13869     }
13870
13871   // At this point LHS and RHS are equivalent to
13872   //   LHS = VECTOR_SHUFFLE A, B, LMask
13873   //   RHS = VECTOR_SHUFFLE A, B, RMask
13874   // Check that the masks correspond to performing a horizontal operation.
13875   for (unsigned i = 0; i != N; ++i) {
13876     unsigned LIdx = LMask[i], RIdx = RMask[i];
13877
13878     // Ignore any UNDEF components.
13879     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
13880         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
13881       continue;
13882
13883     // Check that successive elements are being operated on.  If not, this is
13884     // not a horizontal operation.
13885     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
13886         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
13887       return false;
13888   }
13889
13890   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
13891   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
13892   return true;
13893 }
13894
13895 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
13896 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
13897                                   const X86Subtarget *Subtarget) {
13898   EVT VT = N->getValueType(0);
13899   SDValue LHS = N->getOperand(0);
13900   SDValue RHS = N->getOperand(1);
13901
13902   // Try to synthesize horizontal adds from adds of shuffles.
13903   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13904       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13905       isHorizontalBinOp(LHS, RHS, true))
13906     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
13907   return SDValue();
13908 }
13909
13910 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
13911 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
13912                                   const X86Subtarget *Subtarget) {
13913   EVT VT = N->getValueType(0);
13914   SDValue LHS = N->getOperand(0);
13915   SDValue RHS = N->getOperand(1);
13916
13917   // Try to synthesize horizontal subs from subs of shuffles.
13918   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13919       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13920       isHorizontalBinOp(LHS, RHS, false))
13921     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
13922   return SDValue();
13923 }
13924
13925 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13926 /// X86ISD::FXOR nodes.
13927 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13928   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13929   // F[X]OR(0.0, x) -> x
13930   // F[X]OR(x, 0.0) -> x
13931   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13932     if (C->getValueAPF().isPosZero())
13933       return N->getOperand(1);
13934   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13935     if (C->getValueAPF().isPosZero())
13936       return N->getOperand(0);
13937   return SDValue();
13938 }
13939
13940 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13941 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13942   // FAND(0.0, x) -> 0.0
13943   // FAND(x, 0.0) -> 0.0
13944   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13945     if (C->getValueAPF().isPosZero())
13946       return N->getOperand(0);
13947   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13948     if (C->getValueAPF().isPosZero())
13949       return N->getOperand(1);
13950   return SDValue();
13951 }
13952
13953 static SDValue PerformBTCombine(SDNode *N,
13954                                 SelectionDAG &DAG,
13955                                 TargetLowering::DAGCombinerInfo &DCI) {
13956   // BT ignores high bits in the bit index operand.
13957   SDValue Op1 = N->getOperand(1);
13958   if (Op1.hasOneUse()) {
13959     unsigned BitWidth = Op1.getValueSizeInBits();
13960     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13961     APInt KnownZero, KnownOne;
13962     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13963                                           !DCI.isBeforeLegalizeOps());
13964     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13965     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13966         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13967       DCI.CommitTargetLoweringOpt(TLO);
13968   }
13969   return SDValue();
13970 }
13971
13972 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13973   SDValue Op = N->getOperand(0);
13974   if (Op.getOpcode() == ISD::BITCAST)
13975     Op = Op.getOperand(0);
13976   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13977   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13978       VT.getVectorElementType().getSizeInBits() ==
13979       OpVT.getVectorElementType().getSizeInBits()) {
13980     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13981   }
13982   return SDValue();
13983 }
13984
13985 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13986   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13987   //           (and (i32 x86isd::setcc_carry), 1)
13988   // This eliminates the zext. This transformation is necessary because
13989   // ISD::SETCC is always legalized to i8.
13990   DebugLoc dl = N->getDebugLoc();
13991   SDValue N0 = N->getOperand(0);
13992   EVT VT = N->getValueType(0);
13993   if (N0.getOpcode() == ISD::AND &&
13994       N0.hasOneUse() &&
13995       N0.getOperand(0).hasOneUse()) {
13996     SDValue N00 = N0.getOperand(0);
13997     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13998       return SDValue();
13999     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14000     if (!C || C->getZExtValue() != 1)
14001       return SDValue();
14002     return DAG.getNode(ISD::AND, dl, VT,
14003                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14004                                    N00.getOperand(0), N00.getOperand(1)),
14005                        DAG.getConstant(1, VT));
14006   }
14007
14008   return SDValue();
14009 }
14010
14011 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14012 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14013   unsigned X86CC = N->getConstantOperandVal(0);
14014   SDValue EFLAG = N->getOperand(1);
14015   DebugLoc DL = N->getDebugLoc();
14016
14017   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14018   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14019   // cases.
14020   if (X86CC == X86::COND_B)
14021     return DAG.getNode(ISD::AND, DL, MVT::i8,
14022                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14023                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14024                        DAG.getConstant(1, MVT::i8));
14025
14026   return SDValue();
14027 }
14028
14029 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14030                                         const X86TargetLowering *XTLI) {
14031   SDValue Op0 = N->getOperand(0);
14032   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14033   // a 32-bit target where SSE doesn't support i64->FP operations.
14034   if (Op0.getOpcode() == ISD::LOAD) {
14035     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14036     EVT VT = Ld->getValueType(0);
14037     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14038         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14039         !XTLI->getSubtarget()->is64Bit() &&
14040         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14041       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14042                                           Ld->getChain(), Op0, DAG);
14043       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14044       return FILDChain;
14045     }
14046   }
14047   return SDValue();
14048 }
14049
14050 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14051 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14052                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14053   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14054   // the result is either zero or one (depending on the input carry bit).
14055   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14056   if (X86::isZeroNode(N->getOperand(0)) &&
14057       X86::isZeroNode(N->getOperand(1)) &&
14058       // We don't have a good way to replace an EFLAGS use, so only do this when
14059       // dead right now.
14060       SDValue(N, 1).use_empty()) {
14061     DebugLoc DL = N->getDebugLoc();
14062     EVT VT = N->getValueType(0);
14063     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14064     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14065                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14066                                            DAG.getConstant(X86::COND_B,MVT::i8),
14067                                            N->getOperand(2)),
14068                                DAG.getConstant(1, VT));
14069     return DCI.CombineTo(N, Res1, CarryOut);
14070   }
14071
14072   return SDValue();
14073 }
14074
14075 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14076 //      (add Y, (setne X, 0)) -> sbb -1, Y
14077 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14078 //      (sub (setne X, 0), Y) -> adc -1, Y
14079 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14080   DebugLoc DL = N->getDebugLoc();
14081
14082   // Look through ZExts.
14083   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14084   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14085     return SDValue();
14086
14087   SDValue SetCC = Ext.getOperand(0);
14088   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14089     return SDValue();
14090
14091   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14092   if (CC != X86::COND_E && CC != X86::COND_NE)
14093     return SDValue();
14094
14095   SDValue Cmp = SetCC.getOperand(1);
14096   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14097       !X86::isZeroNode(Cmp.getOperand(1)) ||
14098       !Cmp.getOperand(0).getValueType().isInteger())
14099     return SDValue();
14100
14101   SDValue CmpOp0 = Cmp.getOperand(0);
14102   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14103                                DAG.getConstant(1, CmpOp0.getValueType()));
14104
14105   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14106   if (CC == X86::COND_NE)
14107     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14108                        DL, OtherVal.getValueType(), OtherVal,
14109                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14110   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14111                      DL, OtherVal.getValueType(), OtherVal,
14112                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14113 }
14114
14115 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14116   SDValue Op0 = N->getOperand(0);
14117   SDValue Op1 = N->getOperand(1);
14118
14119   // X86 can't encode an immediate LHS of a sub. See if we can push the
14120   // negation into a preceding instruction.
14121   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14122     // If the RHS of the sub is a XOR with one use and a constant, invert the
14123     // immediate. Then add one to the LHS of the sub so we can turn
14124     // X-Y -> X+~Y+1, saving one register.
14125     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14126         isa<ConstantSDNode>(Op1.getOperand(1))) {
14127       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14128       EVT VT = Op0.getValueType();
14129       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14130                                    Op1.getOperand(0),
14131                                    DAG.getConstant(~XorC, VT));
14132       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14133                          DAG.getConstant(C->getAPIntValue()+1, VT));
14134     }
14135   }
14136
14137   return OptimizeConditionalInDecrement(N, DAG);
14138 }
14139
14140 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14141                                              DAGCombinerInfo &DCI) const {
14142   SelectionDAG &DAG = DCI.DAG;
14143   switch (N->getOpcode()) {
14144   default: break;
14145   case ISD::EXTRACT_VECTOR_ELT:
14146     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14147   case ISD::VSELECT:
14148   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14149   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14150   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14151   case ISD::SUB:            return PerformSubCombine(N, DAG);
14152   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14153   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14154   case ISD::SHL:
14155   case ISD::SRA:
14156   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14157   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14158   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14159   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14160   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14161   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14162   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14163   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14164   case X86ISD::FXOR:
14165   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14166   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14167   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14168   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14169   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14170   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14171   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14172   case X86ISD::SHUFPD:
14173   case X86ISD::PALIGN:
14174   case X86ISD::PUNPCKHBW:
14175   case X86ISD::PUNPCKHWD:
14176   case X86ISD::PUNPCKHDQ:
14177   case X86ISD::PUNPCKHQDQ:
14178   case X86ISD::UNPCKHPS:
14179   case X86ISD::UNPCKHPD:
14180   case X86ISD::VUNPCKHPSY:
14181   case X86ISD::VUNPCKHPDY:
14182   case X86ISD::PUNPCKLBW:
14183   case X86ISD::PUNPCKLWD:
14184   case X86ISD::PUNPCKLDQ:
14185   case X86ISD::PUNPCKLQDQ:
14186   case X86ISD::UNPCKLPS:
14187   case X86ISD::UNPCKLPD:
14188   case X86ISD::VUNPCKLPSY:
14189   case X86ISD::VUNPCKLPDY:
14190   case X86ISD::MOVHLPS:
14191   case X86ISD::MOVLHPS:
14192   case X86ISD::PSHUFD:
14193   case X86ISD::PSHUFHW:
14194   case X86ISD::PSHUFLW:
14195   case X86ISD::MOVSS:
14196   case X86ISD::MOVSD:
14197   case X86ISD::VPERMILPS:
14198   case X86ISD::VPERMILPSY:
14199   case X86ISD::VPERMILPD:
14200   case X86ISD::VPERMILPDY:
14201   case X86ISD::VPERM2F128:
14202   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14203   }
14204
14205   return SDValue();
14206 }
14207
14208 /// isTypeDesirableForOp - Return true if the target has native support for
14209 /// the specified value type and it is 'desirable' to use the type for the
14210 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14211 /// instruction encodings are longer and some i16 instructions are slow.
14212 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14213   if (!isTypeLegal(VT))
14214     return false;
14215   if (VT != MVT::i16)
14216     return true;
14217
14218   switch (Opc) {
14219   default:
14220     return true;
14221   case ISD::LOAD:
14222   case ISD::SIGN_EXTEND:
14223   case ISD::ZERO_EXTEND:
14224   case ISD::ANY_EXTEND:
14225   case ISD::SHL:
14226   case ISD::SRL:
14227   case ISD::SUB:
14228   case ISD::ADD:
14229   case ISD::MUL:
14230   case ISD::AND:
14231   case ISD::OR:
14232   case ISD::XOR:
14233     return false;
14234   }
14235 }
14236
14237 /// IsDesirableToPromoteOp - This method query the target whether it is
14238 /// beneficial for dag combiner to promote the specified node. If true, it
14239 /// should return the desired promotion type by reference.
14240 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14241   EVT VT = Op.getValueType();
14242   if (VT != MVT::i16)
14243     return false;
14244
14245   bool Promote = false;
14246   bool Commute = false;
14247   switch (Op.getOpcode()) {
14248   default: break;
14249   case ISD::LOAD: {
14250     LoadSDNode *LD = cast<LoadSDNode>(Op);
14251     // If the non-extending load has a single use and it's not live out, then it
14252     // might be folded.
14253     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14254                                                      Op.hasOneUse()*/) {
14255       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14256              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14257         // The only case where we'd want to promote LOAD (rather then it being
14258         // promoted as an operand is when it's only use is liveout.
14259         if (UI->getOpcode() != ISD::CopyToReg)
14260           return false;
14261       }
14262     }
14263     Promote = true;
14264     break;
14265   }
14266   case ISD::SIGN_EXTEND:
14267   case ISD::ZERO_EXTEND:
14268   case ISD::ANY_EXTEND:
14269     Promote = true;
14270     break;
14271   case ISD::SHL:
14272   case ISD::SRL: {
14273     SDValue N0 = Op.getOperand(0);
14274     // Look out for (store (shl (load), x)).
14275     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14276       return false;
14277     Promote = true;
14278     break;
14279   }
14280   case ISD::ADD:
14281   case ISD::MUL:
14282   case ISD::AND:
14283   case ISD::OR:
14284   case ISD::XOR:
14285     Commute = true;
14286     // fallthrough
14287   case ISD::SUB: {
14288     SDValue N0 = Op.getOperand(0);
14289     SDValue N1 = Op.getOperand(1);
14290     if (!Commute && MayFoldLoad(N1))
14291       return false;
14292     // Avoid disabling potential load folding opportunities.
14293     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14294       return false;
14295     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14296       return false;
14297     Promote = true;
14298   }
14299   }
14300
14301   PVT = MVT::i32;
14302   return Promote;
14303 }
14304
14305 //===----------------------------------------------------------------------===//
14306 //                           X86 Inline Assembly Support
14307 //===----------------------------------------------------------------------===//
14308
14309 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14310   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14311
14312   std::string AsmStr = IA->getAsmString();
14313
14314   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14315   SmallVector<StringRef, 4> AsmPieces;
14316   SplitString(AsmStr, AsmPieces, ";\n");
14317
14318   switch (AsmPieces.size()) {
14319   default: return false;
14320   case 1:
14321     AsmStr = AsmPieces[0];
14322     AsmPieces.clear();
14323     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14324
14325     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14326     // we will turn this bswap into something that will be lowered to logical ops
14327     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14328     // so don't worry about this.
14329     // bswap $0
14330     if (AsmPieces.size() == 2 &&
14331         (AsmPieces[0] == "bswap" ||
14332          AsmPieces[0] == "bswapq" ||
14333          AsmPieces[0] == "bswapl") &&
14334         (AsmPieces[1] == "$0" ||
14335          AsmPieces[1] == "${0:q}")) {
14336       // No need to check constraints, nothing other than the equivalent of
14337       // "=r,0" would be valid here.
14338       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14339       if (!Ty || Ty->getBitWidth() % 16 != 0)
14340         return false;
14341       return IntrinsicLowering::LowerToByteSwap(CI);
14342     }
14343     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14344     if (CI->getType()->isIntegerTy(16) &&
14345         AsmPieces.size() == 3 &&
14346         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14347         AsmPieces[1] == "$$8," &&
14348         AsmPieces[2] == "${0:w}" &&
14349         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14350       AsmPieces.clear();
14351       const std::string &ConstraintsStr = IA->getConstraintString();
14352       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14353       std::sort(AsmPieces.begin(), AsmPieces.end());
14354       if (AsmPieces.size() == 4 &&
14355           AsmPieces[0] == "~{cc}" &&
14356           AsmPieces[1] == "~{dirflag}" &&
14357           AsmPieces[2] == "~{flags}" &&
14358           AsmPieces[3] == "~{fpsr}") {
14359         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14360         if (!Ty || Ty->getBitWidth() % 16 != 0)
14361           return false;
14362         return IntrinsicLowering::LowerToByteSwap(CI);
14363       }
14364     }
14365     break;
14366   case 3:
14367     if (CI->getType()->isIntegerTy(32) &&
14368         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14369       SmallVector<StringRef, 4> Words;
14370       SplitString(AsmPieces[0], Words, " \t,");
14371       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14372           Words[2] == "${0:w}") {
14373         Words.clear();
14374         SplitString(AsmPieces[1], Words, " \t,");
14375         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14376             Words[2] == "$0") {
14377           Words.clear();
14378           SplitString(AsmPieces[2], Words, " \t,");
14379           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14380               Words[2] == "${0:w}") {
14381             AsmPieces.clear();
14382             const std::string &ConstraintsStr = IA->getConstraintString();
14383             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14384             std::sort(AsmPieces.begin(), AsmPieces.end());
14385             if (AsmPieces.size() == 4 &&
14386                 AsmPieces[0] == "~{cc}" &&
14387                 AsmPieces[1] == "~{dirflag}" &&
14388                 AsmPieces[2] == "~{flags}" &&
14389                 AsmPieces[3] == "~{fpsr}") {
14390               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14391               if (!Ty || Ty->getBitWidth() % 16 != 0)
14392                 return false;
14393               return IntrinsicLowering::LowerToByteSwap(CI);
14394             }
14395           }
14396         }
14397       }
14398     }
14399
14400     if (CI->getType()->isIntegerTy(64)) {
14401       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14402       if (Constraints.size() >= 2 &&
14403           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14404           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14405         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14406         SmallVector<StringRef, 4> Words;
14407         SplitString(AsmPieces[0], Words, " \t");
14408         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14409           Words.clear();
14410           SplitString(AsmPieces[1], Words, " \t");
14411           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14412             Words.clear();
14413             SplitString(AsmPieces[2], Words, " \t,");
14414             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14415                 Words[2] == "%edx") {
14416               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14417               if (!Ty || Ty->getBitWidth() % 16 != 0)
14418                 return false;
14419               return IntrinsicLowering::LowerToByteSwap(CI);
14420             }
14421           }
14422         }
14423       }
14424     }
14425     break;
14426   }
14427   return false;
14428 }
14429
14430
14431
14432 /// getConstraintType - Given a constraint letter, return the type of
14433 /// constraint it is for this target.
14434 X86TargetLowering::ConstraintType
14435 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14436   if (Constraint.size() == 1) {
14437     switch (Constraint[0]) {
14438     case 'R':
14439     case 'q':
14440     case 'Q':
14441     case 'f':
14442     case 't':
14443     case 'u':
14444     case 'y':
14445     case 'x':
14446     case 'Y':
14447     case 'l':
14448       return C_RegisterClass;
14449     case 'a':
14450     case 'b':
14451     case 'c':
14452     case 'd':
14453     case 'S':
14454     case 'D':
14455     case 'A':
14456       return C_Register;
14457     case 'I':
14458     case 'J':
14459     case 'K':
14460     case 'L':
14461     case 'M':
14462     case 'N':
14463     case 'G':
14464     case 'C':
14465     case 'e':
14466     case 'Z':
14467       return C_Other;
14468     default:
14469       break;
14470     }
14471   }
14472   return TargetLowering::getConstraintType(Constraint);
14473 }
14474
14475 /// Examine constraint type and operand type and determine a weight value.
14476 /// This object must already have been set up with the operand type
14477 /// and the current alternative constraint selected.
14478 TargetLowering::ConstraintWeight
14479   X86TargetLowering::getSingleConstraintMatchWeight(
14480     AsmOperandInfo &info, const char *constraint) const {
14481   ConstraintWeight weight = CW_Invalid;
14482   Value *CallOperandVal = info.CallOperandVal;
14483     // If we don't have a value, we can't do a match,
14484     // but allow it at the lowest weight.
14485   if (CallOperandVal == NULL)
14486     return CW_Default;
14487   Type *type = CallOperandVal->getType();
14488   // Look at the constraint type.
14489   switch (*constraint) {
14490   default:
14491     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14492   case 'R':
14493   case 'q':
14494   case 'Q':
14495   case 'a':
14496   case 'b':
14497   case 'c':
14498   case 'd':
14499   case 'S':
14500   case 'D':
14501   case 'A':
14502     if (CallOperandVal->getType()->isIntegerTy())
14503       weight = CW_SpecificReg;
14504     break;
14505   case 'f':
14506   case 't':
14507   case 'u':
14508       if (type->isFloatingPointTy())
14509         weight = CW_SpecificReg;
14510       break;
14511   case 'y':
14512       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14513         weight = CW_SpecificReg;
14514       break;
14515   case 'x':
14516   case 'Y':
14517     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14518       weight = CW_Register;
14519     break;
14520   case 'I':
14521     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14522       if (C->getZExtValue() <= 31)
14523         weight = CW_Constant;
14524     }
14525     break;
14526   case 'J':
14527     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14528       if (C->getZExtValue() <= 63)
14529         weight = CW_Constant;
14530     }
14531     break;
14532   case 'K':
14533     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14534       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14535         weight = CW_Constant;
14536     }
14537     break;
14538   case 'L':
14539     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14540       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14541         weight = CW_Constant;
14542     }
14543     break;
14544   case 'M':
14545     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14546       if (C->getZExtValue() <= 3)
14547         weight = CW_Constant;
14548     }
14549     break;
14550   case 'N':
14551     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14552       if (C->getZExtValue() <= 0xff)
14553         weight = CW_Constant;
14554     }
14555     break;
14556   case 'G':
14557   case 'C':
14558     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14559       weight = CW_Constant;
14560     }
14561     break;
14562   case 'e':
14563     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14564       if ((C->getSExtValue() >= -0x80000000LL) &&
14565           (C->getSExtValue() <= 0x7fffffffLL))
14566         weight = CW_Constant;
14567     }
14568     break;
14569   case 'Z':
14570     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14571       if (C->getZExtValue() <= 0xffffffff)
14572         weight = CW_Constant;
14573     }
14574     break;
14575   }
14576   return weight;
14577 }
14578
14579 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14580 /// with another that has more specific requirements based on the type of the
14581 /// corresponding operand.
14582 const char *X86TargetLowering::
14583 LowerXConstraint(EVT ConstraintVT) const {
14584   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14585   // 'f' like normal targets.
14586   if (ConstraintVT.isFloatingPoint()) {
14587     if (Subtarget->hasXMMInt())
14588       return "Y";
14589     if (Subtarget->hasXMM())
14590       return "x";
14591   }
14592
14593   return TargetLowering::LowerXConstraint(ConstraintVT);
14594 }
14595
14596 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14597 /// vector.  If it is invalid, don't add anything to Ops.
14598 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14599                                                      std::string &Constraint,
14600                                                      std::vector<SDValue>&Ops,
14601                                                      SelectionDAG &DAG) const {
14602   SDValue Result(0, 0);
14603
14604   // Only support length 1 constraints for now.
14605   if (Constraint.length() > 1) return;
14606
14607   char ConstraintLetter = Constraint[0];
14608   switch (ConstraintLetter) {
14609   default: break;
14610   case 'I':
14611     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14612       if (C->getZExtValue() <= 31) {
14613         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14614         break;
14615       }
14616     }
14617     return;
14618   case 'J':
14619     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14620       if (C->getZExtValue() <= 63) {
14621         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14622         break;
14623       }
14624     }
14625     return;
14626   case 'K':
14627     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14628       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14629         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14630         break;
14631       }
14632     }
14633     return;
14634   case 'N':
14635     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14636       if (C->getZExtValue() <= 255) {
14637         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14638         break;
14639       }
14640     }
14641     return;
14642   case 'e': {
14643     // 32-bit signed value
14644     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14645       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14646                                            C->getSExtValue())) {
14647         // Widen to 64 bits here to get it sign extended.
14648         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14649         break;
14650       }
14651     // FIXME gcc accepts some relocatable values here too, but only in certain
14652     // memory models; it's complicated.
14653     }
14654     return;
14655   }
14656   case 'Z': {
14657     // 32-bit unsigned value
14658     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14659       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14660                                            C->getZExtValue())) {
14661         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14662         break;
14663       }
14664     }
14665     // FIXME gcc accepts some relocatable values here too, but only in certain
14666     // memory models; it's complicated.
14667     return;
14668   }
14669   case 'i': {
14670     // Literal immediates are always ok.
14671     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14672       // Widen to 64 bits here to get it sign extended.
14673       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14674       break;
14675     }
14676
14677     // In any sort of PIC mode addresses need to be computed at runtime by
14678     // adding in a register or some sort of table lookup.  These can't
14679     // be used as immediates.
14680     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14681       return;
14682
14683     // If we are in non-pic codegen mode, we allow the address of a global (with
14684     // an optional displacement) to be used with 'i'.
14685     GlobalAddressSDNode *GA = 0;
14686     int64_t Offset = 0;
14687
14688     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14689     while (1) {
14690       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14691         Offset += GA->getOffset();
14692         break;
14693       } else if (Op.getOpcode() == ISD::ADD) {
14694         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14695           Offset += C->getZExtValue();
14696           Op = Op.getOperand(0);
14697           continue;
14698         }
14699       } else if (Op.getOpcode() == ISD::SUB) {
14700         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14701           Offset += -C->getZExtValue();
14702           Op = Op.getOperand(0);
14703           continue;
14704         }
14705       }
14706
14707       // Otherwise, this isn't something we can handle, reject it.
14708       return;
14709     }
14710
14711     const GlobalValue *GV = GA->getGlobal();
14712     // If we require an extra load to get this address, as in PIC mode, we
14713     // can't accept it.
14714     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14715                                                         getTargetMachine())))
14716       return;
14717
14718     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14719                                         GA->getValueType(0), Offset);
14720     break;
14721   }
14722   }
14723
14724   if (Result.getNode()) {
14725     Ops.push_back(Result);
14726     return;
14727   }
14728   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14729 }
14730
14731 std::pair<unsigned, const TargetRegisterClass*>
14732 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14733                                                 EVT VT) const {
14734   // First, see if this is a constraint that directly corresponds to an LLVM
14735   // register class.
14736   if (Constraint.size() == 1) {
14737     // GCC Constraint Letters
14738     switch (Constraint[0]) {
14739     default: break;
14740       // TODO: Slight differences here in allocation order and leaving
14741       // RIP in the class. Do they matter any more here than they do
14742       // in the normal allocation?
14743     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14744       if (Subtarget->is64Bit()) {
14745         if (VT == MVT::i32 || VT == MVT::f32)
14746           return std::make_pair(0U, X86::GR32RegisterClass);
14747         else if (VT == MVT::i16)
14748           return std::make_pair(0U, X86::GR16RegisterClass);
14749         else if (VT == MVT::i8 || VT == MVT::i1)
14750           return std::make_pair(0U, X86::GR8RegisterClass);
14751         else if (VT == MVT::i64 || VT == MVT::f64)
14752           return std::make_pair(0U, X86::GR64RegisterClass);
14753         break;
14754       }
14755       // 32-bit fallthrough
14756     case 'Q':   // Q_REGS
14757       if (VT == MVT::i32 || VT == MVT::f32)
14758         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14759       else if (VT == MVT::i16)
14760         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14761       else if (VT == MVT::i8 || VT == MVT::i1)
14762         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14763       else if (VT == MVT::i64)
14764         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14765       break;
14766     case 'r':   // GENERAL_REGS
14767     case 'l':   // INDEX_REGS
14768       if (VT == MVT::i8 || VT == MVT::i1)
14769         return std::make_pair(0U, X86::GR8RegisterClass);
14770       if (VT == MVT::i16)
14771         return std::make_pair(0U, X86::GR16RegisterClass);
14772       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14773         return std::make_pair(0U, X86::GR32RegisterClass);
14774       return std::make_pair(0U, X86::GR64RegisterClass);
14775     case 'R':   // LEGACY_REGS
14776       if (VT == MVT::i8 || VT == MVT::i1)
14777         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14778       if (VT == MVT::i16)
14779         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14780       if (VT == MVT::i32 || !Subtarget->is64Bit())
14781         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14782       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14783     case 'f':  // FP Stack registers.
14784       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14785       // value to the correct fpstack register class.
14786       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14787         return std::make_pair(0U, X86::RFP32RegisterClass);
14788       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14789         return std::make_pair(0U, X86::RFP64RegisterClass);
14790       return std::make_pair(0U, X86::RFP80RegisterClass);
14791     case 'y':   // MMX_REGS if MMX allowed.
14792       if (!Subtarget->hasMMX()) break;
14793       return std::make_pair(0U, X86::VR64RegisterClass);
14794     case 'Y':   // SSE_REGS if SSE2 allowed
14795       if (!Subtarget->hasXMMInt()) break;
14796       // FALL THROUGH.
14797     case 'x':   // SSE_REGS if SSE1 allowed
14798       if (!Subtarget->hasXMM()) break;
14799
14800       switch (VT.getSimpleVT().SimpleTy) {
14801       default: break;
14802       // Scalar SSE types.
14803       case MVT::f32:
14804       case MVT::i32:
14805         return std::make_pair(0U, X86::FR32RegisterClass);
14806       case MVT::f64:
14807       case MVT::i64:
14808         return std::make_pair(0U, X86::FR64RegisterClass);
14809       // Vector types.
14810       case MVT::v16i8:
14811       case MVT::v8i16:
14812       case MVT::v4i32:
14813       case MVT::v2i64:
14814       case MVT::v4f32:
14815       case MVT::v2f64:
14816         return std::make_pair(0U, X86::VR128RegisterClass);
14817       }
14818       break;
14819     }
14820   }
14821
14822   // Use the default implementation in TargetLowering to convert the register
14823   // constraint into a member of a register class.
14824   std::pair<unsigned, const TargetRegisterClass*> Res;
14825   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14826
14827   // Not found as a standard register?
14828   if (Res.second == 0) {
14829     // Map st(0) -> st(7) -> ST0
14830     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14831         tolower(Constraint[1]) == 's' &&
14832         tolower(Constraint[2]) == 't' &&
14833         Constraint[3] == '(' &&
14834         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14835         Constraint[5] == ')' &&
14836         Constraint[6] == '}') {
14837
14838       Res.first = X86::ST0+Constraint[4]-'0';
14839       Res.second = X86::RFP80RegisterClass;
14840       return Res;
14841     }
14842
14843     // GCC allows "st(0)" to be called just plain "st".
14844     if (StringRef("{st}").equals_lower(Constraint)) {
14845       Res.first = X86::ST0;
14846       Res.second = X86::RFP80RegisterClass;
14847       return Res;
14848     }
14849
14850     // flags -> EFLAGS
14851     if (StringRef("{flags}").equals_lower(Constraint)) {
14852       Res.first = X86::EFLAGS;
14853       Res.second = X86::CCRRegisterClass;
14854       return Res;
14855     }
14856
14857     // 'A' means EAX + EDX.
14858     if (Constraint == "A") {
14859       Res.first = X86::EAX;
14860       Res.second = X86::GR32_ADRegisterClass;
14861       return Res;
14862     }
14863     return Res;
14864   }
14865
14866   // Otherwise, check to see if this is a register class of the wrong value
14867   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14868   // turn into {ax},{dx}.
14869   if (Res.second->hasType(VT))
14870     return Res;   // Correct type already, nothing to do.
14871
14872   // All of the single-register GCC register classes map their values onto
14873   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14874   // really want an 8-bit or 32-bit register, map to the appropriate register
14875   // class and return the appropriate register.
14876   if (Res.second == X86::GR16RegisterClass) {
14877     if (VT == MVT::i8) {
14878       unsigned DestReg = 0;
14879       switch (Res.first) {
14880       default: break;
14881       case X86::AX: DestReg = X86::AL; break;
14882       case X86::DX: DestReg = X86::DL; break;
14883       case X86::CX: DestReg = X86::CL; break;
14884       case X86::BX: DestReg = X86::BL; break;
14885       }
14886       if (DestReg) {
14887         Res.first = DestReg;
14888         Res.second = X86::GR8RegisterClass;
14889       }
14890     } else if (VT == MVT::i32) {
14891       unsigned DestReg = 0;
14892       switch (Res.first) {
14893       default: break;
14894       case X86::AX: DestReg = X86::EAX; break;
14895       case X86::DX: DestReg = X86::EDX; break;
14896       case X86::CX: DestReg = X86::ECX; break;
14897       case X86::BX: DestReg = X86::EBX; break;
14898       case X86::SI: DestReg = X86::ESI; break;
14899       case X86::DI: DestReg = X86::EDI; break;
14900       case X86::BP: DestReg = X86::EBP; break;
14901       case X86::SP: DestReg = X86::ESP; break;
14902       }
14903       if (DestReg) {
14904         Res.first = DestReg;
14905         Res.second = X86::GR32RegisterClass;
14906       }
14907     } else if (VT == MVT::i64) {
14908       unsigned DestReg = 0;
14909       switch (Res.first) {
14910       default: break;
14911       case X86::AX: DestReg = X86::RAX; break;
14912       case X86::DX: DestReg = X86::RDX; break;
14913       case X86::CX: DestReg = X86::RCX; break;
14914       case X86::BX: DestReg = X86::RBX; break;
14915       case X86::SI: DestReg = X86::RSI; break;
14916       case X86::DI: DestReg = X86::RDI; break;
14917       case X86::BP: DestReg = X86::RBP; break;
14918       case X86::SP: DestReg = X86::RSP; break;
14919       }
14920       if (DestReg) {
14921         Res.first = DestReg;
14922         Res.second = X86::GR64RegisterClass;
14923       }
14924     }
14925   } else if (Res.second == X86::FR32RegisterClass ||
14926              Res.second == X86::FR64RegisterClass ||
14927              Res.second == X86::VR128RegisterClass) {
14928     // Handle references to XMM physical registers that got mapped into the
14929     // wrong class.  This can happen with constraints like {xmm0} where the
14930     // target independent register mapper will just pick the first match it can
14931     // find, ignoring the required type.
14932     if (VT == MVT::f32)
14933       Res.second = X86::FR32RegisterClass;
14934     else if (VT == MVT::f64)
14935       Res.second = X86::FR64RegisterClass;
14936     else if (X86::VR128RegisterClass->hasType(VT))
14937       Res.second = X86::VR128RegisterClass;
14938   }
14939
14940   return Res;
14941 }