Synthesize SSE3/AVX 128 bit horizontal add/sub instructions from
[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::CTLZ             , MVT::i8   , Custom);
384   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
385   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
386   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
387   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
388   if (Subtarget->is64Bit()) {
389     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
390     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
391   }
392
393   if (Subtarget->hasPOPCNT()) {
394     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
395   } else {
396     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
397     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
398     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
399     if (Subtarget->is64Bit())
400       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
401   }
402
403   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
404   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
405
406   // These should be promoted to a larger select which is supported.
407   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
408   // X86 wants to expand cmov itself.
409   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
410   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
413   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
414   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
416   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
419   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
420   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
421   if (Subtarget->is64Bit()) {
422     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
423     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
424   }
425   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasXMM())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
457   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
458
459   // On X86 and X86-64, atomic operations are lowered to locked instructions.
460   // Locked instructions, in turn, have implicit fence semantics (all memory
461   // operations are flushed before issuing the locked instruction, and they
462   // are not buffered), so we can fold away the common pattern of
463   // fence-atomic-fence.
464   setShouldFoldAtomicFences(true);
465
466   // Expand certain atomics
467   for (unsigned i = 0, e = 4; i != e; ++i) {
468     MVT VT = IntVTs[i];
469     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
470     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
471     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472   }
473
474   if (!Subtarget->is64Bit()) {
475     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
476     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
477     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
478     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
479     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
480     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
482     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
483   }
484
485   if (Subtarget->hasCmpxchg16b()) {
486     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
487   }
488
489   // FIXME - use subtarget debug flags
490   if (!Subtarget->isTargetDarwin() &&
491       !Subtarget->isTargetELF() &&
492       !Subtarget->isTargetCygMing()) {
493     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
494   }
495
496   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
497   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
498   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
499   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
500   if (Subtarget->is64Bit()) {
501     setExceptionPointerRegister(X86::RAX);
502     setExceptionSelectorRegister(X86::RDX);
503   } else {
504     setExceptionPointerRegister(X86::EAX);
505     setExceptionSelectorRegister(X86::EDX);
506   }
507   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
508   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
509
510   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
511   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
512
513   setOperationAction(ISD::TRAP, MVT::Other, Legal);
514
515   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
516   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
517   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
518   if (Subtarget->is64Bit()) {
519     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
520     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
521   } else {
522     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
523     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
524   }
525
526   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
527   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
528
529   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
530     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
531                        MVT::i64 : MVT::i32, Custom);
532   else if (EnableSegmentedStacks)
533     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
534                        MVT::i64 : MVT::i32, Custom);
535   else
536     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
537                        MVT::i64 : MVT::i32, Expand);
538
539   if (!UseSoftFloat && X86ScalarSSEf64) {
540     // f32 and f64 use SSE.
541     // Set up the FP register classes.
542     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
543     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
544
545     // Use ANDPD to simulate FABS.
546     setOperationAction(ISD::FABS , MVT::f64, Custom);
547     setOperationAction(ISD::FABS , MVT::f32, Custom);
548
549     // Use XORP to simulate FNEG.
550     setOperationAction(ISD::FNEG , MVT::f64, Custom);
551     setOperationAction(ISD::FNEG , MVT::f32, Custom);
552
553     // Use ANDPD and ORPD to simulate FCOPYSIGN.
554     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
555     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
556
557     // Lower this to FGETSIGNx86 plus an AND.
558     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
559     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
560
561     // We don't support sin/cos/fmod
562     setOperationAction(ISD::FSIN , MVT::f64, Expand);
563     setOperationAction(ISD::FCOS , MVT::f64, Expand);
564     setOperationAction(ISD::FSIN , MVT::f32, Expand);
565     setOperationAction(ISD::FCOS , MVT::f32, Expand);
566
567     // Expand FP immediates into loads from the stack, except for the special
568     // cases we handle.
569     addLegalFPImmediate(APFloat(+0.0)); // xorpd
570     addLegalFPImmediate(APFloat(+0.0f)); // xorps
571   } else if (!UseSoftFloat && X86ScalarSSEf32) {
572     // Use SSE for f32, x87 for f64.
573     // Set up the FP register classes.
574     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
575     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
576
577     // Use ANDPS to simulate FABS.
578     setOperationAction(ISD::FABS , MVT::f32, Custom);
579
580     // Use XORP to simulate FNEG.
581     setOperationAction(ISD::FNEG , MVT::f32, Custom);
582
583     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
584
585     // Use ANDPS and ORPS to simulate FCOPYSIGN.
586     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
588
589     // We don't support sin/cos/fmod
590     setOperationAction(ISD::FSIN , MVT::f32, Expand);
591     setOperationAction(ISD::FCOS , MVT::f32, Expand);
592
593     // Special cases we handle for FP constants.
594     addLegalFPImmediate(APFloat(+0.0f)); // xorps
595     addLegalFPImmediate(APFloat(+0.0)); // FLD0
596     addLegalFPImmediate(APFloat(+1.0)); // FLD1
597     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
598     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
599
600     if (!UnsafeFPMath) {
601       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
602       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
603     }
604   } else if (!UseSoftFloat) {
605     // f32 and f64 in x87.
606     // Set up the FP register classes.
607     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
608     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
609
610     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
611     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
612     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
613     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
614
615     if (!UnsafeFPMath) {
616       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
617       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
618     }
619     addLegalFPImmediate(APFloat(+0.0)); // FLD0
620     addLegalFPImmediate(APFloat(+1.0)); // FLD1
621     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
624     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
625     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
626     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
627   }
628
629   // We don't support FMA.
630   setOperationAction(ISD::FMA, MVT::f64, Expand);
631   setOperationAction(ISD::FMA, MVT::f32, Expand);
632
633   // Long double always uses X87.
634   if (!UseSoftFloat) {
635     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
636     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
637     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
638     {
639       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
640       addLegalFPImmediate(TmpFlt);  // FLD0
641       TmpFlt.changeSign();
642       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
643
644       bool ignored;
645       APFloat TmpFlt2(+1.0);
646       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
647                       &ignored);
648       addLegalFPImmediate(TmpFlt2);  // FLD1
649       TmpFlt2.changeSign();
650       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
651     }
652
653     if (!UnsafeFPMath) {
654       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
655       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
656     }
657
658     setOperationAction(ISD::FMA, MVT::f80, Expand);
659   }
660
661   // Always use a library call for pow.
662   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
663   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
664   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
665
666   setOperationAction(ISD::FLOG, MVT::f80, Expand);
667   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
668   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
669   setOperationAction(ISD::FEXP, MVT::f80, Expand);
670   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
671
672   // First set operation action for all vector types to either promote
673   // (for widening) or expand (for scalarization). Then we will selectively
674   // turn on ones that can be effectively codegen'd.
675   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
676        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
677     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
678     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
679     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
680     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
681     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
692     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
694     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
695     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
727     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
732     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
733          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
734       setTruncStoreAction((MVT::SimpleValueType)VT,
735                           (MVT::SimpleValueType)InnerVT, Expand);
736     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
737     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
738     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
739   }
740
741   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
742   // with -msoft-float, disable use of MMX as well.
743   if (!UseSoftFloat && Subtarget->hasMMX()) {
744     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
745     // No operations on x86mmx supported, everything uses intrinsics.
746   }
747
748   // MMX-sized vectors (other than x86mmx) are expected to be expanded
749   // into smaller operations.
750   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
751   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
752   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
753   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
754   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
755   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
756   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
757   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
758   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
759   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
760   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
761   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
762   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
763   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
764   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
765   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
766   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
767   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
768   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
769   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
770   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
771   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
772   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
773   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
774   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
775   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
776   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
777   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
778   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
779
780   if (!UseSoftFloat && Subtarget->hasXMM()) {
781     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
782
783     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
788     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
789     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
790     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
791     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
792     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
794     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
795   }
796
797   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
798     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
799
800     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
801     // registers cannot be used even for integer operations.
802     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
803     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
804     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
805     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
806
807     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
808     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
809     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
810     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
812     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
813     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
814     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
815     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
816     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
817     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
822     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
828
829     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
831     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
834
835     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
836     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
837     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
838     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
839     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
840
841     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
842     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
843       EVT VT = (MVT::SimpleValueType)i;
844       // Do not attempt to custom lower non-power-of-2 vectors
845       if (!isPowerOf2_32(VT.getVectorNumElements()))
846         continue;
847       // Do not attempt to custom lower non-128-bit vectors
848       if (!VT.is128BitVector())
849         continue;
850       setOperationAction(ISD::BUILD_VECTOR,
851                          VT.getSimpleVT().SimpleTy, Custom);
852       setOperationAction(ISD::VECTOR_SHUFFLE,
853                          VT.getSimpleVT().SimpleTy, Custom);
854       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
855                          VT.getSimpleVT().SimpleTy, Custom);
856     }
857
858     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
859     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
860     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
861     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
863     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
864
865     if (Subtarget->is64Bit()) {
866       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
868     }
869
870     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
871     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
872       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
873       EVT VT = SVT;
874
875       // Do not attempt to promote non-128-bit vectors
876       if (!VT.is128BitVector())
877         continue;
878
879       setOperationAction(ISD::AND,    SVT, Promote);
880       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
881       setOperationAction(ISD::OR,     SVT, Promote);
882       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
883       setOperationAction(ISD::XOR,    SVT, Promote);
884       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
885       setOperationAction(ISD::LOAD,   SVT, Promote);
886       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
887       setOperationAction(ISD::SELECT, SVT, Promote);
888       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
889     }
890
891     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
892
893     // Custom lower v2i64 and v2f64 selects.
894     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
895     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
896     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
897     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
898
899     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
900     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
901   }
902
903   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
904     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
905     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
906     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
907     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
908     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
909     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
910     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
911     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
912     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
913     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
914
915     // FIXME: Do we need to handle scalar-to-vector here?
916     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
917
918     // Can turn SHL into an integer multiply.
919     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
920     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
921
922     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
923     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
924     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
925     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
926     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
927
928     // i8 and i16 vectors are custom , because the source register and source
929     // source memory operand types are not the same width.  f32 vectors are
930     // custom since the immediate controlling the insert encodes additional
931     // information.
932     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
933     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
934     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
936
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
938     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
939     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
940     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
941
942     if (Subtarget->is64Bit()) {
943       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
944       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
945     }
946   }
947
948   if (Subtarget->hasXMMInt()) {
949     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
950     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
951     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
952     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
953
954     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
955     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
956     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
957
958     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
959     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
960   }
961
962   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
963     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
964
965   if (!UseSoftFloat && Subtarget->hasAVX()) {
966     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
967     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
968     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
969     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
970     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
971     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
972
973     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
974     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
975     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
976
977     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
978     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
979     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
980     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
981     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
982     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
983
984     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
985     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
986     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
987     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
988     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
989     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
990
991     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
992     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
993     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
994
995     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
996     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
997     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
998     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
999     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1000     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1001
1002     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1003     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1004     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1005     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1006
1007     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1008     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1009     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1010     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1011
1012     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1013     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1014
1015     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1016     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1017     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1018     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1019
1020     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1021     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1022     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1023
1024     setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1025     setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1026     setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1027     setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1028
1029     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1030     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1031     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1032     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1033
1034     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1035     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1036     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1037     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1038
1039     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1040     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1041     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1042     // Don't lower v32i8 because there is no 128-bit byte mul
1043
1044     // Custom lower several nodes for 256-bit types.
1045     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1046                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1047       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1048       EVT VT = SVT;
1049
1050       // Extract subvector is special because the value type
1051       // (result) is 128-bit but the source is 256-bit wide.
1052       if (VT.is128BitVector())
1053         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1054
1055       // Do not attempt to custom lower other non-256-bit vectors
1056       if (!VT.is256BitVector())
1057         continue;
1058
1059       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1060       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1061       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1062       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1063       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1064       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1065     }
1066
1067     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1068     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1069       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1070       EVT VT = SVT;
1071
1072       // Do not attempt to promote non-256-bit vectors
1073       if (!VT.is256BitVector())
1074         continue;
1075
1076       setOperationAction(ISD::AND,    SVT, Promote);
1077       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1078       setOperationAction(ISD::OR,     SVT, Promote);
1079       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1080       setOperationAction(ISD::XOR,    SVT, Promote);
1081       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1082       setOperationAction(ISD::LOAD,   SVT, Promote);
1083       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1084       setOperationAction(ISD::SELECT, SVT, Promote);
1085       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1086     }
1087   }
1088
1089   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1090   // of this type with custom code.
1091   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1092          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1093     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1094   }
1095
1096   // We want to custom lower some of our intrinsics.
1097   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1098
1099
1100   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1101   // handle type legalization for these operations here.
1102   //
1103   // FIXME: We really should do custom legalization for addition and
1104   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1105   // than generic legalization for 64-bit multiplication-with-overflow, though.
1106   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1107     // Add/Sub/Mul with overflow operations are custom lowered.
1108     MVT VT = IntVTs[i];
1109     setOperationAction(ISD::SADDO, VT, Custom);
1110     setOperationAction(ISD::UADDO, VT, Custom);
1111     setOperationAction(ISD::SSUBO, VT, Custom);
1112     setOperationAction(ISD::USUBO, VT, Custom);
1113     setOperationAction(ISD::SMULO, VT, Custom);
1114     setOperationAction(ISD::UMULO, VT, Custom);
1115   }
1116
1117   // There are no 8-bit 3-address imul/mul instructions
1118   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1119   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1120
1121   if (!Subtarget->is64Bit()) {
1122     // These libcalls are not available in 32-bit.
1123     setLibcallName(RTLIB::SHL_I128, 0);
1124     setLibcallName(RTLIB::SRL_I128, 0);
1125     setLibcallName(RTLIB::SRA_I128, 0);
1126   }
1127
1128   // We have target-specific dag combine patterns for the following nodes:
1129   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1130   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1131   setTargetDAGCombine(ISD::BUILD_VECTOR);
1132   setTargetDAGCombine(ISD::VSELECT);
1133   setTargetDAGCombine(ISD::SELECT);
1134   setTargetDAGCombine(ISD::SHL);
1135   setTargetDAGCombine(ISD::SRA);
1136   setTargetDAGCombine(ISD::SRL);
1137   setTargetDAGCombine(ISD::OR);
1138   setTargetDAGCombine(ISD::AND);
1139   setTargetDAGCombine(ISD::ADD);
1140   setTargetDAGCombine(ISD::FADD);
1141   setTargetDAGCombine(ISD::FSUB);
1142   setTargetDAGCombine(ISD::SUB);
1143   setTargetDAGCombine(ISD::LOAD);
1144   setTargetDAGCombine(ISD::STORE);
1145   setTargetDAGCombine(ISD::ZERO_EXTEND);
1146   setTargetDAGCombine(ISD::SINT_TO_FP);
1147   if (Subtarget->is64Bit())
1148     setTargetDAGCombine(ISD::MUL);
1149
1150   computeRegisterProperties();
1151
1152   // On Darwin, -Os means optimize for size without hurting performance,
1153   // do not reduce the limit.
1154   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1155   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1156   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1157   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1158   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1159   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1160   setPrefLoopAlignment(16);
1161   benefitFromCodePlacementOpt = true;
1162
1163   setPrefFunctionAlignment(4);
1164 }
1165
1166
1167 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1168   if (!VT.isVector()) return MVT::i8;
1169   return VT.changeVectorElementTypeToInteger();
1170 }
1171
1172
1173 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1174 /// the desired ByVal argument alignment.
1175 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1176   if (MaxAlign == 16)
1177     return;
1178   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1179     if (VTy->getBitWidth() == 128)
1180       MaxAlign = 16;
1181   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1182     unsigned EltAlign = 0;
1183     getMaxByValAlign(ATy->getElementType(), EltAlign);
1184     if (EltAlign > MaxAlign)
1185       MaxAlign = EltAlign;
1186   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1187     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1188       unsigned EltAlign = 0;
1189       getMaxByValAlign(STy->getElementType(i), EltAlign);
1190       if (EltAlign > MaxAlign)
1191         MaxAlign = EltAlign;
1192       if (MaxAlign == 16)
1193         break;
1194     }
1195   }
1196   return;
1197 }
1198
1199 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1200 /// function arguments in the caller parameter area. For X86, aggregates
1201 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1202 /// are at 4-byte boundaries.
1203 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1204   if (Subtarget->is64Bit()) {
1205     // Max of 8 and alignment of type.
1206     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1207     if (TyAlign > 8)
1208       return TyAlign;
1209     return 8;
1210   }
1211
1212   unsigned Align = 4;
1213   if (Subtarget->hasXMM())
1214     getMaxByValAlign(Ty, Align);
1215   return Align;
1216 }
1217
1218 /// getOptimalMemOpType - Returns the target specific optimal type for load
1219 /// and store operations as a result of memset, memcpy, and memmove
1220 /// lowering. If DstAlign is zero that means it's safe to destination
1221 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1222 /// means there isn't a need to check it against alignment requirement,
1223 /// probably because the source does not need to be loaded. If
1224 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1225 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1226 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1227 /// constant so it does not need to be loaded.
1228 /// It returns EVT::Other if the type should be determined using generic
1229 /// target-independent logic.
1230 EVT
1231 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1232                                        unsigned DstAlign, unsigned SrcAlign,
1233                                        bool NonScalarIntSafe,
1234                                        bool MemcpyStrSrc,
1235                                        MachineFunction &MF) const {
1236   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1237   // linux.  This is because the stack realignment code can't handle certain
1238   // cases like PR2962.  This should be removed when PR2962 is fixed.
1239   const Function *F = MF.getFunction();
1240   if (NonScalarIntSafe &&
1241       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1242     if (Size >= 16 &&
1243         (Subtarget->isUnalignedMemAccessFast() ||
1244          ((DstAlign == 0 || DstAlign >= 16) &&
1245           (SrcAlign == 0 || SrcAlign >= 16))) &&
1246         Subtarget->getStackAlignment() >= 16) {
1247       if (Subtarget->hasAVX() &&
1248           Subtarget->getStackAlignment() >= 32)
1249         return MVT::v8f32;
1250       if (Subtarget->hasXMMInt())
1251         return MVT::v4i32;
1252       if (Subtarget->hasXMM())
1253         return MVT::v4f32;
1254     } else if (!MemcpyStrSrc && Size >= 8 &&
1255                !Subtarget->is64Bit() &&
1256                Subtarget->getStackAlignment() >= 8 &&
1257                Subtarget->hasXMMInt()) {
1258       // Do not use f64 to lower memcpy if source is string constant. It's
1259       // better to use i32 to avoid the loads.
1260       return MVT::f64;
1261     }
1262   }
1263   if (Subtarget->is64Bit() && Size >= 8)
1264     return MVT::i64;
1265   return MVT::i32;
1266 }
1267
1268 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1269 /// current function.  The returned value is a member of the
1270 /// MachineJumpTableInfo::JTEntryKind enum.
1271 unsigned X86TargetLowering::getJumpTableEncoding() const {
1272   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1273   // symbol.
1274   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1275       Subtarget->isPICStyleGOT())
1276     return MachineJumpTableInfo::EK_Custom32;
1277
1278   // Otherwise, use the normal jump table encoding heuristics.
1279   return TargetLowering::getJumpTableEncoding();
1280 }
1281
1282 const MCExpr *
1283 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1284                                              const MachineBasicBlock *MBB,
1285                                              unsigned uid,MCContext &Ctx) const{
1286   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1287          Subtarget->isPICStyleGOT());
1288   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1289   // entries.
1290   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1291                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1292 }
1293
1294 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1295 /// jumptable.
1296 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1297                                                     SelectionDAG &DAG) const {
1298   if (!Subtarget->is64Bit())
1299     // This doesn't have DebugLoc associated with it, but is not really the
1300     // same as a Register.
1301     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1302   return Table;
1303 }
1304
1305 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1306 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1307 /// MCExpr.
1308 const MCExpr *X86TargetLowering::
1309 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1310                              MCContext &Ctx) const {
1311   // X86-64 uses RIP relative addressing based on the jump table label.
1312   if (Subtarget->isPICStyleRIPRel())
1313     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1314
1315   // Otherwise, the reference is relative to the PIC base.
1316   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1317 }
1318
1319 // FIXME: Why this routine is here? Move to RegInfo!
1320 std::pair<const TargetRegisterClass*, uint8_t>
1321 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1322   const TargetRegisterClass *RRC = 0;
1323   uint8_t Cost = 1;
1324   switch (VT.getSimpleVT().SimpleTy) {
1325   default:
1326     return TargetLowering::findRepresentativeClass(VT);
1327   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1328     RRC = (Subtarget->is64Bit()
1329            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1330     break;
1331   case MVT::x86mmx:
1332     RRC = X86::VR64RegisterClass;
1333     break;
1334   case MVT::f32: case MVT::f64:
1335   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1336   case MVT::v4f32: case MVT::v2f64:
1337   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1338   case MVT::v4f64:
1339     RRC = X86::VR128RegisterClass;
1340     break;
1341   }
1342   return std::make_pair(RRC, Cost);
1343 }
1344
1345 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1346                                                unsigned &Offset) const {
1347   if (!Subtarget->isTargetLinux())
1348     return false;
1349
1350   if (Subtarget->is64Bit()) {
1351     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1352     Offset = 0x28;
1353     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1354       AddressSpace = 256;
1355     else
1356       AddressSpace = 257;
1357   } else {
1358     // %gs:0x14 on i386
1359     Offset = 0x14;
1360     AddressSpace = 256;
1361   }
1362   return true;
1363 }
1364
1365
1366 //===----------------------------------------------------------------------===//
1367 //               Return Value Calling Convention Implementation
1368 //===----------------------------------------------------------------------===//
1369
1370 #include "X86GenCallingConv.inc"
1371
1372 bool
1373 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1374                                   MachineFunction &MF, bool isVarArg,
1375                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1376                         LLVMContext &Context) const {
1377   SmallVector<CCValAssign, 16> RVLocs;
1378   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1379                  RVLocs, Context);
1380   return CCInfo.CheckReturn(Outs, RetCC_X86);
1381 }
1382
1383 SDValue
1384 X86TargetLowering::LowerReturn(SDValue Chain,
1385                                CallingConv::ID CallConv, bool isVarArg,
1386                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1387                                const SmallVectorImpl<SDValue> &OutVals,
1388                                DebugLoc dl, SelectionDAG &DAG) const {
1389   MachineFunction &MF = DAG.getMachineFunction();
1390   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1391
1392   SmallVector<CCValAssign, 16> RVLocs;
1393   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1394                  RVLocs, *DAG.getContext());
1395   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1396
1397   // Add the regs to the liveout set for the function.
1398   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1399   for (unsigned i = 0; i != RVLocs.size(); ++i)
1400     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1401       MRI.addLiveOut(RVLocs[i].getLocReg());
1402
1403   SDValue Flag;
1404
1405   SmallVector<SDValue, 6> RetOps;
1406   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1407   // Operand #1 = Bytes To Pop
1408   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1409                    MVT::i16));
1410
1411   // Copy the result values into the output registers.
1412   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1413     CCValAssign &VA = RVLocs[i];
1414     assert(VA.isRegLoc() && "Can only return in registers!");
1415     SDValue ValToCopy = OutVals[i];
1416     EVT ValVT = ValToCopy.getValueType();
1417
1418     // If this is x86-64, and we disabled SSE, we can't return FP values,
1419     // or SSE or MMX vectors.
1420     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1421          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1422           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1423       report_fatal_error("SSE register return with SSE disabled");
1424     }
1425     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1426     // llvm-gcc has never done it right and no one has noticed, so this
1427     // should be OK for now.
1428     if (ValVT == MVT::f64 &&
1429         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1430       report_fatal_error("SSE2 register return with SSE2 disabled");
1431
1432     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1433     // the RET instruction and handled by the FP Stackifier.
1434     if (VA.getLocReg() == X86::ST0 ||
1435         VA.getLocReg() == X86::ST1) {
1436       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1437       // change the value to the FP stack register class.
1438       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1439         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1440       RetOps.push_back(ValToCopy);
1441       // Don't emit a copytoreg.
1442       continue;
1443     }
1444
1445     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1446     // which is returned in RAX / RDX.
1447     if (Subtarget->is64Bit()) {
1448       if (ValVT == MVT::x86mmx) {
1449         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1450           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1451           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1452                                   ValToCopy);
1453           // If we don't have SSE2 available, convert to v4f32 so the generated
1454           // register is legal.
1455           if (!Subtarget->hasXMMInt())
1456             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1457         }
1458       }
1459     }
1460
1461     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1462     Flag = Chain.getValue(1);
1463   }
1464
1465   // The x86-64 ABI for returning structs by value requires that we copy
1466   // the sret argument into %rax for the return. We saved the argument into
1467   // a virtual register in the entry block, so now we copy the value out
1468   // and into %rax.
1469   if (Subtarget->is64Bit() &&
1470       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1471     MachineFunction &MF = DAG.getMachineFunction();
1472     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1473     unsigned Reg = FuncInfo->getSRetReturnReg();
1474     assert(Reg &&
1475            "SRetReturnReg should have been set in LowerFormalArguments().");
1476     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1477
1478     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1479     Flag = Chain.getValue(1);
1480
1481     // RAX now acts like a return value.
1482     MRI.addLiveOut(X86::RAX);
1483   }
1484
1485   RetOps[0] = Chain;  // Update chain.
1486
1487   // Add the flag if we have it.
1488   if (Flag.getNode())
1489     RetOps.push_back(Flag);
1490
1491   return DAG.getNode(X86ISD::RET_FLAG, dl,
1492                      MVT::Other, &RetOps[0], RetOps.size());
1493 }
1494
1495 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1496   if (N->getNumValues() != 1)
1497     return false;
1498   if (!N->hasNUsesOfValue(1, 0))
1499     return false;
1500
1501   SDNode *Copy = *N->use_begin();
1502   if (Copy->getOpcode() != ISD::CopyToReg &&
1503       Copy->getOpcode() != ISD::FP_EXTEND)
1504     return false;
1505
1506   bool HasRet = false;
1507   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1508        UI != UE; ++UI) {
1509     if (UI->getOpcode() != X86ISD::RET_FLAG)
1510       return false;
1511     HasRet = true;
1512   }
1513
1514   return HasRet;
1515 }
1516
1517 EVT
1518 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1519                                             ISD::NodeType ExtendKind) const {
1520   MVT ReturnMVT;
1521   // TODO: Is this also valid on 32-bit?
1522   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1523     ReturnMVT = MVT::i8;
1524   else
1525     ReturnMVT = MVT::i32;
1526
1527   EVT MinVT = getRegisterType(Context, ReturnMVT);
1528   return VT.bitsLT(MinVT) ? MinVT : VT;
1529 }
1530
1531 /// LowerCallResult - Lower the result values of a call into the
1532 /// appropriate copies out of appropriate physical registers.
1533 ///
1534 SDValue
1535 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1536                                    CallingConv::ID CallConv, bool isVarArg,
1537                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1538                                    DebugLoc dl, SelectionDAG &DAG,
1539                                    SmallVectorImpl<SDValue> &InVals) const {
1540
1541   // Assign locations to each value returned by this call.
1542   SmallVector<CCValAssign, 16> RVLocs;
1543   bool Is64Bit = Subtarget->is64Bit();
1544   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1545                  getTargetMachine(), RVLocs, *DAG.getContext());
1546   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1547
1548   // Copy all of the result registers out of their specified physreg.
1549   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1550     CCValAssign &VA = RVLocs[i];
1551     EVT CopyVT = VA.getValVT();
1552
1553     // If this is x86-64, and we disabled SSE, we can't return FP values
1554     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1555         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1556       report_fatal_error("SSE register return with SSE disabled");
1557     }
1558
1559     SDValue Val;
1560
1561     // If this is a call to a function that returns an fp value on the floating
1562     // point stack, we must guarantee the the value is popped from the stack, so
1563     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1564     // if the return value is not used. We use the FpPOP_RETVAL instruction
1565     // instead.
1566     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1567       // If we prefer to use the value in xmm registers, copy it out as f80 and
1568       // use a truncate to move it from fp stack reg to xmm reg.
1569       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1570       SDValue Ops[] = { Chain, InFlag };
1571       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1572                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1573       Val = Chain.getValue(0);
1574
1575       // Round the f80 to the right size, which also moves it to the appropriate
1576       // xmm register.
1577       if (CopyVT != VA.getValVT())
1578         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1579                           // This truncation won't change the value.
1580                           DAG.getIntPtrConstant(1));
1581     } else {
1582       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1583                                  CopyVT, InFlag).getValue(1);
1584       Val = Chain.getValue(0);
1585     }
1586     InFlag = Chain.getValue(2);
1587     InVals.push_back(Val);
1588   }
1589
1590   return Chain;
1591 }
1592
1593
1594 //===----------------------------------------------------------------------===//
1595 //                C & StdCall & Fast Calling Convention implementation
1596 //===----------------------------------------------------------------------===//
1597 //  StdCall calling convention seems to be standard for many Windows' API
1598 //  routines and around. It differs from C calling convention just a little:
1599 //  callee should clean up the stack, not caller. Symbols should be also
1600 //  decorated in some fancy way :) It doesn't support any vector arguments.
1601 //  For info on fast calling convention see Fast Calling Convention (tail call)
1602 //  implementation LowerX86_32FastCCCallTo.
1603
1604 /// CallIsStructReturn - Determines whether a call uses struct return
1605 /// semantics.
1606 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1607   if (Outs.empty())
1608     return false;
1609
1610   return Outs[0].Flags.isSRet();
1611 }
1612
1613 /// ArgsAreStructReturn - Determines whether a function uses struct
1614 /// return semantics.
1615 static bool
1616 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1617   if (Ins.empty())
1618     return false;
1619
1620   return Ins[0].Flags.isSRet();
1621 }
1622
1623 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1624 /// by "Src" to address "Dst" with size and alignment information specified by
1625 /// the specific parameter attribute. The copy will be passed as a byval
1626 /// function parameter.
1627 static SDValue
1628 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1629                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1630                           DebugLoc dl) {
1631   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1632
1633   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1634                        /*isVolatile*/false, /*AlwaysInline=*/true,
1635                        MachinePointerInfo(), MachinePointerInfo());
1636 }
1637
1638 /// IsTailCallConvention - Return true if the calling convention is one that
1639 /// supports tail call optimization.
1640 static bool IsTailCallConvention(CallingConv::ID CC) {
1641   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1642 }
1643
1644 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1645   if (!CI->isTailCall())
1646     return false;
1647
1648   CallSite CS(CI);
1649   CallingConv::ID CalleeCC = CS.getCallingConv();
1650   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1651     return false;
1652
1653   return true;
1654 }
1655
1656 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1657 /// a tailcall target by changing its ABI.
1658 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1659   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1660 }
1661
1662 SDValue
1663 X86TargetLowering::LowerMemArgument(SDValue Chain,
1664                                     CallingConv::ID CallConv,
1665                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1666                                     DebugLoc dl, SelectionDAG &DAG,
1667                                     const CCValAssign &VA,
1668                                     MachineFrameInfo *MFI,
1669                                     unsigned i) const {
1670   // Create the nodes corresponding to a load from this parameter slot.
1671   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1672   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1673   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1674   EVT ValVT;
1675
1676   // If value is passed by pointer we have address passed instead of the value
1677   // itself.
1678   if (VA.getLocInfo() == CCValAssign::Indirect)
1679     ValVT = VA.getLocVT();
1680   else
1681     ValVT = VA.getValVT();
1682
1683   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1684   // changed with more analysis.
1685   // In case of tail call optimization mark all arguments mutable. Since they
1686   // could be overwritten by lowering of arguments in case of a tail call.
1687   if (Flags.isByVal()) {
1688     unsigned Bytes = Flags.getByValSize();
1689     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1690     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1691     return DAG.getFrameIndex(FI, getPointerTy());
1692   } else {
1693     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1694                                     VA.getLocMemOffset(), isImmutable);
1695     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1696     return DAG.getLoad(ValVT, dl, Chain, FIN,
1697                        MachinePointerInfo::getFixedStack(FI),
1698                        false, false, 0);
1699   }
1700 }
1701
1702 SDValue
1703 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1704                                         CallingConv::ID CallConv,
1705                                         bool isVarArg,
1706                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1707                                         DebugLoc dl,
1708                                         SelectionDAG &DAG,
1709                                         SmallVectorImpl<SDValue> &InVals)
1710                                           const {
1711   MachineFunction &MF = DAG.getMachineFunction();
1712   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1713
1714   const Function* Fn = MF.getFunction();
1715   if (Fn->hasExternalLinkage() &&
1716       Subtarget->isTargetCygMing() &&
1717       Fn->getName() == "main")
1718     FuncInfo->setForceFramePointer(true);
1719
1720   MachineFrameInfo *MFI = MF.getFrameInfo();
1721   bool Is64Bit = Subtarget->is64Bit();
1722   bool IsWin64 = Subtarget->isTargetWin64();
1723
1724   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1725          "Var args not supported with calling convention fastcc or ghc");
1726
1727   // Assign locations to all of the incoming arguments.
1728   SmallVector<CCValAssign, 16> ArgLocs;
1729   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1730                  ArgLocs, *DAG.getContext());
1731
1732   // Allocate shadow area for Win64
1733   if (IsWin64) {
1734     CCInfo.AllocateStack(32, 8);
1735   }
1736
1737   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1738
1739   unsigned LastVal = ~0U;
1740   SDValue ArgValue;
1741   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1742     CCValAssign &VA = ArgLocs[i];
1743     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1744     // places.
1745     assert(VA.getValNo() != LastVal &&
1746            "Don't support value assigned to multiple locs yet");
1747     LastVal = VA.getValNo();
1748
1749     if (VA.isRegLoc()) {
1750       EVT RegVT = VA.getLocVT();
1751       TargetRegisterClass *RC = NULL;
1752       if (RegVT == MVT::i32)
1753         RC = X86::GR32RegisterClass;
1754       else if (Is64Bit && RegVT == MVT::i64)
1755         RC = X86::GR64RegisterClass;
1756       else if (RegVT == MVT::f32)
1757         RC = X86::FR32RegisterClass;
1758       else if (RegVT == MVT::f64)
1759         RC = X86::FR64RegisterClass;
1760       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1761         RC = X86::VR256RegisterClass;
1762       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1763         RC = X86::VR128RegisterClass;
1764       else if (RegVT == MVT::x86mmx)
1765         RC = X86::VR64RegisterClass;
1766       else
1767         llvm_unreachable("Unknown argument type!");
1768
1769       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1770       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1771
1772       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1773       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1774       // right size.
1775       if (VA.getLocInfo() == CCValAssign::SExt)
1776         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1777                                DAG.getValueType(VA.getValVT()));
1778       else if (VA.getLocInfo() == CCValAssign::ZExt)
1779         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1780                                DAG.getValueType(VA.getValVT()));
1781       else if (VA.getLocInfo() == CCValAssign::BCvt)
1782         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1783
1784       if (VA.isExtInLoc()) {
1785         // Handle MMX values passed in XMM regs.
1786         if (RegVT.isVector()) {
1787           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1788                                  ArgValue);
1789         } else
1790           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1791       }
1792     } else {
1793       assert(VA.isMemLoc());
1794       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1795     }
1796
1797     // If value is passed via pointer - do a load.
1798     if (VA.getLocInfo() == CCValAssign::Indirect)
1799       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1800                              MachinePointerInfo(), false, false, 0);
1801
1802     InVals.push_back(ArgValue);
1803   }
1804
1805   // The x86-64 ABI for returning structs by value requires that we copy
1806   // the sret argument into %rax for the return. Save the argument into
1807   // a virtual register so that we can access it from the return points.
1808   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1809     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1810     unsigned Reg = FuncInfo->getSRetReturnReg();
1811     if (!Reg) {
1812       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1813       FuncInfo->setSRetReturnReg(Reg);
1814     }
1815     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1816     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1817   }
1818
1819   unsigned StackSize = CCInfo.getNextStackOffset();
1820   // Align stack specially for tail calls.
1821   if (FuncIsMadeTailCallSafe(CallConv))
1822     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1823
1824   // If the function takes variable number of arguments, make a frame index for
1825   // the start of the first vararg value... for expansion of llvm.va_start.
1826   if (isVarArg) {
1827     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1828                     CallConv != CallingConv::X86_ThisCall)) {
1829       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1830     }
1831     if (Is64Bit) {
1832       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1833
1834       // FIXME: We should really autogenerate these arrays
1835       static const unsigned GPR64ArgRegsWin64[] = {
1836         X86::RCX, X86::RDX, X86::R8,  X86::R9
1837       };
1838       static const unsigned GPR64ArgRegs64Bit[] = {
1839         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1840       };
1841       static const unsigned XMMArgRegs64Bit[] = {
1842         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1843         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1844       };
1845       const unsigned *GPR64ArgRegs;
1846       unsigned NumXMMRegs = 0;
1847
1848       if (IsWin64) {
1849         // The XMM registers which might contain var arg parameters are shadowed
1850         // in their paired GPR.  So we only need to save the GPR to their home
1851         // slots.
1852         TotalNumIntRegs = 4;
1853         GPR64ArgRegs = GPR64ArgRegsWin64;
1854       } else {
1855         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1856         GPR64ArgRegs = GPR64ArgRegs64Bit;
1857
1858         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1859       }
1860       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1861                                                        TotalNumIntRegs);
1862
1863       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1864       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1865              "SSE register cannot be used when SSE is disabled!");
1866       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1867              "SSE register cannot be used when SSE is disabled!");
1868       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1869         // Kernel mode asks for SSE to be disabled, so don't push them
1870         // on the stack.
1871         TotalNumXMMRegs = 0;
1872
1873       if (IsWin64) {
1874         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1875         // Get to the caller-allocated home save location.  Add 8 to account
1876         // for the return address.
1877         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1878         FuncInfo->setRegSaveFrameIndex(
1879           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1880         // Fixup to set vararg frame on shadow area (4 x i64).
1881         if (NumIntRegs < 4)
1882           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1883       } else {
1884         // For X86-64, if there are vararg parameters that are passed via
1885         // registers, then we must store them to their spots on the stack so they
1886         // may be loaded by deferencing the result of va_next.
1887         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1888         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1889         FuncInfo->setRegSaveFrameIndex(
1890           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1891                                false));
1892       }
1893
1894       // Store the integer parameter registers.
1895       SmallVector<SDValue, 8> MemOps;
1896       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1897                                         getPointerTy());
1898       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1899       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1900         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1901                                   DAG.getIntPtrConstant(Offset));
1902         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1903                                      X86::GR64RegisterClass);
1904         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1905         SDValue Store =
1906           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1907                        MachinePointerInfo::getFixedStack(
1908                          FuncInfo->getRegSaveFrameIndex(), Offset),
1909                        false, false, 0);
1910         MemOps.push_back(Store);
1911         Offset += 8;
1912       }
1913
1914       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1915         // Now store the XMM (fp + vector) parameter registers.
1916         SmallVector<SDValue, 11> SaveXMMOps;
1917         SaveXMMOps.push_back(Chain);
1918
1919         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1920         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1921         SaveXMMOps.push_back(ALVal);
1922
1923         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1924                                FuncInfo->getRegSaveFrameIndex()));
1925         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1926                                FuncInfo->getVarArgsFPOffset()));
1927
1928         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1929           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1930                                        X86::VR128RegisterClass);
1931           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1932           SaveXMMOps.push_back(Val);
1933         }
1934         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1935                                      MVT::Other,
1936                                      &SaveXMMOps[0], SaveXMMOps.size()));
1937       }
1938
1939       if (!MemOps.empty())
1940         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1941                             &MemOps[0], MemOps.size());
1942     }
1943   }
1944
1945   // Some CCs need callee pop.
1946   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1947     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1948   } else {
1949     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1950     // If this is an sret function, the return should pop the hidden pointer.
1951     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1952       FuncInfo->setBytesToPopOnReturn(4);
1953   }
1954
1955   if (!Is64Bit) {
1956     // RegSaveFrameIndex is X86-64 only.
1957     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1958     if (CallConv == CallingConv::X86_FastCall ||
1959         CallConv == CallingConv::X86_ThisCall)
1960       // fastcc functions can't have varargs.
1961       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1962   }
1963
1964   FuncInfo->setArgumentStackSize(StackSize);
1965
1966   return Chain;
1967 }
1968
1969 SDValue
1970 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1971                                     SDValue StackPtr, SDValue Arg,
1972                                     DebugLoc dl, SelectionDAG &DAG,
1973                                     const CCValAssign &VA,
1974                                     ISD::ArgFlagsTy Flags) const {
1975   unsigned LocMemOffset = VA.getLocMemOffset();
1976   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1977   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1978   if (Flags.isByVal())
1979     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1980
1981   return DAG.getStore(Chain, dl, Arg, PtrOff,
1982                       MachinePointerInfo::getStack(LocMemOffset),
1983                       false, false, 0);
1984 }
1985
1986 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1987 /// optimization is performed and it is required.
1988 SDValue
1989 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1990                                            SDValue &OutRetAddr, SDValue Chain,
1991                                            bool IsTailCall, bool Is64Bit,
1992                                            int FPDiff, DebugLoc dl) const {
1993   // Adjust the Return address stack slot.
1994   EVT VT = getPointerTy();
1995   OutRetAddr = getReturnAddressFrameIndex(DAG);
1996
1997   // Load the "old" Return address.
1998   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1999                            false, false, 0);
2000   return SDValue(OutRetAddr.getNode(), 1);
2001 }
2002
2003 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2004 /// optimization is performed and it is required (FPDiff!=0).
2005 static SDValue
2006 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2007                          SDValue Chain, SDValue RetAddrFrIdx,
2008                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2009   // Store the return address to the appropriate stack slot.
2010   if (!FPDiff) return Chain;
2011   // Calculate the new stack slot for the return address.
2012   int SlotSize = Is64Bit ? 8 : 4;
2013   int NewReturnAddrFI =
2014     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2015   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2016   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2017   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2018                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2019                        false, false, 0);
2020   return Chain;
2021 }
2022
2023 SDValue
2024 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2025                              CallingConv::ID CallConv, bool isVarArg,
2026                              bool &isTailCall,
2027                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2028                              const SmallVectorImpl<SDValue> &OutVals,
2029                              const SmallVectorImpl<ISD::InputArg> &Ins,
2030                              DebugLoc dl, SelectionDAG &DAG,
2031                              SmallVectorImpl<SDValue> &InVals) const {
2032   MachineFunction &MF = DAG.getMachineFunction();
2033   bool Is64Bit        = Subtarget->is64Bit();
2034   bool IsWin64        = Subtarget->isTargetWin64();
2035   bool IsStructRet    = CallIsStructReturn(Outs);
2036   bool IsSibcall      = false;
2037
2038   if (isTailCall) {
2039     // Check if it's really possible to do a tail call.
2040     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2041                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2042                                                    Outs, OutVals, Ins, DAG);
2043
2044     // Sibcalls are automatically detected tailcalls which do not require
2045     // ABI changes.
2046     if (!GuaranteedTailCallOpt && isTailCall)
2047       IsSibcall = true;
2048
2049     if (isTailCall)
2050       ++NumTailCalls;
2051   }
2052
2053   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2054          "Var args not supported with calling convention fastcc or ghc");
2055
2056   // Analyze operands of the call, assigning locations to each operand.
2057   SmallVector<CCValAssign, 16> ArgLocs;
2058   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2059                  ArgLocs, *DAG.getContext());
2060
2061   // Allocate shadow area for Win64
2062   if (IsWin64) {
2063     CCInfo.AllocateStack(32, 8);
2064   }
2065
2066   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2067
2068   // Get a count of how many bytes are to be pushed on the stack.
2069   unsigned NumBytes = CCInfo.getNextStackOffset();
2070   if (IsSibcall)
2071     // This is a sibcall. The memory operands are available in caller's
2072     // own caller's stack.
2073     NumBytes = 0;
2074   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2075     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2076
2077   int FPDiff = 0;
2078   if (isTailCall && !IsSibcall) {
2079     // Lower arguments at fp - stackoffset + fpdiff.
2080     unsigned NumBytesCallerPushed =
2081       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2082     FPDiff = NumBytesCallerPushed - NumBytes;
2083
2084     // Set the delta of movement of the returnaddr stackslot.
2085     // But only set if delta is greater than previous delta.
2086     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2087       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2088   }
2089
2090   if (!IsSibcall)
2091     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2092
2093   SDValue RetAddrFrIdx;
2094   // Load return address for tail calls.
2095   if (isTailCall && FPDiff)
2096     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2097                                     Is64Bit, FPDiff, dl);
2098
2099   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2100   SmallVector<SDValue, 8> MemOpChains;
2101   SDValue StackPtr;
2102
2103   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2104   // of tail call optimization arguments are handle later.
2105   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2106     CCValAssign &VA = ArgLocs[i];
2107     EVT RegVT = VA.getLocVT();
2108     SDValue Arg = OutVals[i];
2109     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2110     bool isByVal = Flags.isByVal();
2111
2112     // Promote the value if needed.
2113     switch (VA.getLocInfo()) {
2114     default: llvm_unreachable("Unknown loc info!");
2115     case CCValAssign::Full: break;
2116     case CCValAssign::SExt:
2117       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2118       break;
2119     case CCValAssign::ZExt:
2120       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2121       break;
2122     case CCValAssign::AExt:
2123       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2124         // Special case: passing MMX values in XMM registers.
2125         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2126         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2127         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2128       } else
2129         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2130       break;
2131     case CCValAssign::BCvt:
2132       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2133       break;
2134     case CCValAssign::Indirect: {
2135       // Store the argument.
2136       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2137       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2138       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2139                            MachinePointerInfo::getFixedStack(FI),
2140                            false, false, 0);
2141       Arg = SpillSlot;
2142       break;
2143     }
2144     }
2145
2146     if (VA.isRegLoc()) {
2147       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2148       if (isVarArg && IsWin64) {
2149         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2150         // shadow reg if callee is a varargs function.
2151         unsigned ShadowReg = 0;
2152         switch (VA.getLocReg()) {
2153         case X86::XMM0: ShadowReg = X86::RCX; break;
2154         case X86::XMM1: ShadowReg = X86::RDX; break;
2155         case X86::XMM2: ShadowReg = X86::R8; break;
2156         case X86::XMM3: ShadowReg = X86::R9; break;
2157         }
2158         if (ShadowReg)
2159           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2160       }
2161     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2162       assert(VA.isMemLoc());
2163       if (StackPtr.getNode() == 0)
2164         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2165       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2166                                              dl, DAG, VA, Flags));
2167     }
2168   }
2169
2170   if (!MemOpChains.empty())
2171     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2172                         &MemOpChains[0], MemOpChains.size());
2173
2174   // Build a sequence of copy-to-reg nodes chained together with token chain
2175   // and flag operands which copy the outgoing args into registers.
2176   SDValue InFlag;
2177   // Tail call byval lowering might overwrite argument registers so in case of
2178   // tail call optimization the copies to registers are lowered later.
2179   if (!isTailCall)
2180     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2181       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2182                                RegsToPass[i].second, InFlag);
2183       InFlag = Chain.getValue(1);
2184     }
2185
2186   if (Subtarget->isPICStyleGOT()) {
2187     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2188     // GOT pointer.
2189     if (!isTailCall) {
2190       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2191                                DAG.getNode(X86ISD::GlobalBaseReg,
2192                                            DebugLoc(), getPointerTy()),
2193                                InFlag);
2194       InFlag = Chain.getValue(1);
2195     } else {
2196       // If we are tail calling and generating PIC/GOT style code load the
2197       // address of the callee into ECX. The value in ecx is used as target of
2198       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2199       // for tail calls on PIC/GOT architectures. Normally we would just put the
2200       // address of GOT into ebx and then call target@PLT. But for tail calls
2201       // ebx would be restored (since ebx is callee saved) before jumping to the
2202       // target@PLT.
2203
2204       // Note: The actual moving to ECX is done further down.
2205       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2206       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2207           !G->getGlobal()->hasProtectedVisibility())
2208         Callee = LowerGlobalAddress(Callee, DAG);
2209       else if (isa<ExternalSymbolSDNode>(Callee))
2210         Callee = LowerExternalSymbol(Callee, DAG);
2211     }
2212   }
2213
2214   if (Is64Bit && isVarArg && !IsWin64) {
2215     // From AMD64 ABI document:
2216     // For calls that may call functions that use varargs or stdargs
2217     // (prototype-less calls or calls to functions containing ellipsis (...) in
2218     // the declaration) %al is used as hidden argument to specify the number
2219     // of SSE registers used. The contents of %al do not need to match exactly
2220     // the number of registers, but must be an ubound on the number of SSE
2221     // registers used and is in the range 0 - 8 inclusive.
2222
2223     // Count the number of XMM registers allocated.
2224     static const unsigned XMMArgRegs[] = {
2225       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2226       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2227     };
2228     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2229     assert((Subtarget->hasXMM() || !NumXMMRegs)
2230            && "SSE registers cannot be used when SSE is disabled");
2231
2232     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2233                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2234     InFlag = Chain.getValue(1);
2235   }
2236
2237
2238   // For tail calls lower the arguments to the 'real' stack slot.
2239   if (isTailCall) {
2240     // Force all the incoming stack arguments to be loaded from the stack
2241     // before any new outgoing arguments are stored to the stack, because the
2242     // outgoing stack slots may alias the incoming argument stack slots, and
2243     // the alias isn't otherwise explicit. This is slightly more conservative
2244     // than necessary, because it means that each store effectively depends
2245     // on every argument instead of just those arguments it would clobber.
2246     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2247
2248     SmallVector<SDValue, 8> MemOpChains2;
2249     SDValue FIN;
2250     int FI = 0;
2251     // Do not flag preceding copytoreg stuff together with the following stuff.
2252     InFlag = SDValue();
2253     if (GuaranteedTailCallOpt) {
2254       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2255         CCValAssign &VA = ArgLocs[i];
2256         if (VA.isRegLoc())
2257           continue;
2258         assert(VA.isMemLoc());
2259         SDValue Arg = OutVals[i];
2260         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2261         // Create frame index.
2262         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2263         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2264         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2265         FIN = DAG.getFrameIndex(FI, getPointerTy());
2266
2267         if (Flags.isByVal()) {
2268           // Copy relative to framepointer.
2269           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2270           if (StackPtr.getNode() == 0)
2271             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2272                                           getPointerTy());
2273           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2274
2275           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2276                                                            ArgChain,
2277                                                            Flags, DAG, dl));
2278         } else {
2279           // Store relative to framepointer.
2280           MemOpChains2.push_back(
2281             DAG.getStore(ArgChain, dl, Arg, FIN,
2282                          MachinePointerInfo::getFixedStack(FI),
2283                          false, false, 0));
2284         }
2285       }
2286     }
2287
2288     if (!MemOpChains2.empty())
2289       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2290                           &MemOpChains2[0], MemOpChains2.size());
2291
2292     // Copy arguments to their registers.
2293     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2294       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2295                                RegsToPass[i].second, InFlag);
2296       InFlag = Chain.getValue(1);
2297     }
2298     InFlag =SDValue();
2299
2300     // Store the return address to the appropriate stack slot.
2301     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2302                                      FPDiff, dl);
2303   }
2304
2305   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2306     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2307     // In the 64-bit large code model, we have to make all calls
2308     // through a register, since the call instruction's 32-bit
2309     // pc-relative offset may not be large enough to hold the whole
2310     // address.
2311   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2312     // If the callee is a GlobalAddress node (quite common, every direct call
2313     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2314     // it.
2315
2316     // We should use extra load for direct calls to dllimported functions in
2317     // non-JIT mode.
2318     const GlobalValue *GV = G->getGlobal();
2319     if (!GV->hasDLLImportLinkage()) {
2320       unsigned char OpFlags = 0;
2321       bool ExtraLoad = false;
2322       unsigned WrapperKind = ISD::DELETED_NODE;
2323
2324       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2325       // external symbols most go through the PLT in PIC mode.  If the symbol
2326       // has hidden or protected visibility, or if it is static or local, then
2327       // we don't need to use the PLT - we can directly call it.
2328       if (Subtarget->isTargetELF() &&
2329           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2330           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2331         OpFlags = X86II::MO_PLT;
2332       } else if (Subtarget->isPICStyleStubAny() &&
2333                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2334                  (!Subtarget->getTargetTriple().isMacOSX() ||
2335                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2336         // PC-relative references to external symbols should go through $stub,
2337         // unless we're building with the leopard linker or later, which
2338         // automatically synthesizes these stubs.
2339         OpFlags = X86II::MO_DARWIN_STUB;
2340       } else if (Subtarget->isPICStyleRIPRel() &&
2341                  isa<Function>(GV) &&
2342                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2343         // If the function is marked as non-lazy, generate an indirect call
2344         // which loads from the GOT directly. This avoids runtime overhead
2345         // at the cost of eager binding (and one extra byte of encoding).
2346         OpFlags = X86II::MO_GOTPCREL;
2347         WrapperKind = X86ISD::WrapperRIP;
2348         ExtraLoad = true;
2349       }
2350
2351       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2352                                           G->getOffset(), OpFlags);
2353
2354       // Add a wrapper if needed.
2355       if (WrapperKind != ISD::DELETED_NODE)
2356         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2357       // Add extra indirection if needed.
2358       if (ExtraLoad)
2359         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2360                              MachinePointerInfo::getGOT(),
2361                              false, false, 0);
2362     }
2363   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2364     unsigned char OpFlags = 0;
2365
2366     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2367     // external symbols should go through the PLT.
2368     if (Subtarget->isTargetELF() &&
2369         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2370       OpFlags = X86II::MO_PLT;
2371     } else if (Subtarget->isPICStyleStubAny() &&
2372                (!Subtarget->getTargetTriple().isMacOSX() ||
2373                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2374       // PC-relative references to external symbols should go through $stub,
2375       // unless we're building with the leopard linker or later, which
2376       // automatically synthesizes these stubs.
2377       OpFlags = X86II::MO_DARWIN_STUB;
2378     }
2379
2380     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2381                                          OpFlags);
2382   }
2383
2384   // Returns a chain & a flag for retval copy to use.
2385   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2386   SmallVector<SDValue, 8> Ops;
2387
2388   if (!IsSibcall && isTailCall) {
2389     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2390                            DAG.getIntPtrConstant(0, true), InFlag);
2391     InFlag = Chain.getValue(1);
2392   }
2393
2394   Ops.push_back(Chain);
2395   Ops.push_back(Callee);
2396
2397   if (isTailCall)
2398     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2399
2400   // Add argument registers to the end of the list so that they are known live
2401   // into the call.
2402   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2403     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2404                                   RegsToPass[i].second.getValueType()));
2405
2406   // Add an implicit use GOT pointer in EBX.
2407   if (!isTailCall && Subtarget->isPICStyleGOT())
2408     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2409
2410   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2411   if (Is64Bit && isVarArg && !IsWin64)
2412     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2413
2414   if (InFlag.getNode())
2415     Ops.push_back(InFlag);
2416
2417   if (isTailCall) {
2418     // We used to do:
2419     //// If this is the first return lowered for this function, add the regs
2420     //// to the liveout set for the function.
2421     // This isn't right, although it's probably harmless on x86; liveouts
2422     // should be computed from returns not tail calls.  Consider a void
2423     // function making a tail call to a function returning int.
2424     return DAG.getNode(X86ISD::TC_RETURN, dl,
2425                        NodeTys, &Ops[0], Ops.size());
2426   }
2427
2428   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2429   InFlag = Chain.getValue(1);
2430
2431   // Create the CALLSEQ_END node.
2432   unsigned NumBytesForCalleeToPush;
2433   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2434     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2435   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2436     // If this is a call to a struct-return function, the callee
2437     // pops the hidden struct pointer, so we have to push it back.
2438     // This is common for Darwin/X86, Linux & Mingw32 targets.
2439     NumBytesForCalleeToPush = 4;
2440   else
2441     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2442
2443   // Returns a flag for retval copy to use.
2444   if (!IsSibcall) {
2445     Chain = DAG.getCALLSEQ_END(Chain,
2446                                DAG.getIntPtrConstant(NumBytes, true),
2447                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2448                                                      true),
2449                                InFlag);
2450     InFlag = Chain.getValue(1);
2451   }
2452
2453   // Handle result values, copying them out of physregs into vregs that we
2454   // return.
2455   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2456                          Ins, dl, DAG, InVals);
2457 }
2458
2459
2460 //===----------------------------------------------------------------------===//
2461 //                Fast Calling Convention (tail call) implementation
2462 //===----------------------------------------------------------------------===//
2463
2464 //  Like std call, callee cleans arguments, convention except that ECX is
2465 //  reserved for storing the tail called function address. Only 2 registers are
2466 //  free for argument passing (inreg). Tail call optimization is performed
2467 //  provided:
2468 //                * tailcallopt is enabled
2469 //                * caller/callee are fastcc
2470 //  On X86_64 architecture with GOT-style position independent code only local
2471 //  (within module) calls are supported at the moment.
2472 //  To keep the stack aligned according to platform abi the function
2473 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2474 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2475 //  If a tail called function callee has more arguments than the caller the
2476 //  caller needs to make sure that there is room to move the RETADDR to. This is
2477 //  achieved by reserving an area the size of the argument delta right after the
2478 //  original REtADDR, but before the saved framepointer or the spilled registers
2479 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2480 //  stack layout:
2481 //    arg1
2482 //    arg2
2483 //    RETADDR
2484 //    [ new RETADDR
2485 //      move area ]
2486 //    (possible EBP)
2487 //    ESI
2488 //    EDI
2489 //    local1 ..
2490
2491 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2492 /// for a 16 byte align requirement.
2493 unsigned
2494 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2495                                                SelectionDAG& DAG) const {
2496   MachineFunction &MF = DAG.getMachineFunction();
2497   const TargetMachine &TM = MF.getTarget();
2498   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2499   unsigned StackAlignment = TFI.getStackAlignment();
2500   uint64_t AlignMask = StackAlignment - 1;
2501   int64_t Offset = StackSize;
2502   uint64_t SlotSize = TD->getPointerSize();
2503   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2504     // Number smaller than 12 so just add the difference.
2505     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2506   } else {
2507     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2508     Offset = ((~AlignMask) & Offset) + StackAlignment +
2509       (StackAlignment-SlotSize);
2510   }
2511   return Offset;
2512 }
2513
2514 /// MatchingStackOffset - Return true if the given stack call argument is
2515 /// already available in the same position (relatively) of the caller's
2516 /// incoming argument stack.
2517 static
2518 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2519                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2520                          const X86InstrInfo *TII) {
2521   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2522   int FI = INT_MAX;
2523   if (Arg.getOpcode() == ISD::CopyFromReg) {
2524     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2525     if (!TargetRegisterInfo::isVirtualRegister(VR))
2526       return false;
2527     MachineInstr *Def = MRI->getVRegDef(VR);
2528     if (!Def)
2529       return false;
2530     if (!Flags.isByVal()) {
2531       if (!TII->isLoadFromStackSlot(Def, FI))
2532         return false;
2533     } else {
2534       unsigned Opcode = Def->getOpcode();
2535       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2536           Def->getOperand(1).isFI()) {
2537         FI = Def->getOperand(1).getIndex();
2538         Bytes = Flags.getByValSize();
2539       } else
2540         return false;
2541     }
2542   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2543     if (Flags.isByVal())
2544       // ByVal argument is passed in as a pointer but it's now being
2545       // dereferenced. e.g.
2546       // define @foo(%struct.X* %A) {
2547       //   tail call @bar(%struct.X* byval %A)
2548       // }
2549       return false;
2550     SDValue Ptr = Ld->getBasePtr();
2551     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2552     if (!FINode)
2553       return false;
2554     FI = FINode->getIndex();
2555   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2556     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2557     FI = FINode->getIndex();
2558     Bytes = Flags.getByValSize();
2559   } else
2560     return false;
2561
2562   assert(FI != INT_MAX);
2563   if (!MFI->isFixedObjectIndex(FI))
2564     return false;
2565   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2566 }
2567
2568 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2569 /// for tail call optimization. Targets which want to do tail call
2570 /// optimization should implement this function.
2571 bool
2572 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2573                                                      CallingConv::ID CalleeCC,
2574                                                      bool isVarArg,
2575                                                      bool isCalleeStructRet,
2576                                                      bool isCallerStructRet,
2577                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2578                                     const SmallVectorImpl<SDValue> &OutVals,
2579                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2580                                                      SelectionDAG& DAG) const {
2581   if (!IsTailCallConvention(CalleeCC) &&
2582       CalleeCC != CallingConv::C)
2583     return false;
2584
2585   // If -tailcallopt is specified, make fastcc functions tail-callable.
2586   const MachineFunction &MF = DAG.getMachineFunction();
2587   const Function *CallerF = DAG.getMachineFunction().getFunction();
2588   CallingConv::ID CallerCC = CallerF->getCallingConv();
2589   bool CCMatch = CallerCC == CalleeCC;
2590
2591   if (GuaranteedTailCallOpt) {
2592     if (IsTailCallConvention(CalleeCC) && CCMatch)
2593       return true;
2594     return false;
2595   }
2596
2597   // Look for obvious safe cases to perform tail call optimization that do not
2598   // require ABI changes. This is what gcc calls sibcall.
2599
2600   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2601   // emit a special epilogue.
2602   if (RegInfo->needsStackRealignment(MF))
2603     return false;
2604
2605   // Also avoid sibcall optimization if either caller or callee uses struct
2606   // return semantics.
2607   if (isCalleeStructRet || isCallerStructRet)
2608     return false;
2609
2610   // An stdcall caller is expected to clean up its arguments; the callee
2611   // isn't going to do that.
2612   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2613     return false;
2614
2615   // Do not sibcall optimize vararg calls unless all arguments are passed via
2616   // registers.
2617   if (isVarArg && !Outs.empty()) {
2618
2619     // Optimizing for varargs on Win64 is unlikely to be safe without
2620     // additional testing.
2621     if (Subtarget->isTargetWin64())
2622       return false;
2623
2624     SmallVector<CCValAssign, 16> ArgLocs;
2625     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2626                    getTargetMachine(), ArgLocs, *DAG.getContext());
2627
2628     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2629     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2630       if (!ArgLocs[i].isRegLoc())
2631         return false;
2632   }
2633
2634   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2635   // Therefore if it's not used by the call it is not safe to optimize this into
2636   // a sibcall.
2637   bool Unused = false;
2638   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2639     if (!Ins[i].Used) {
2640       Unused = true;
2641       break;
2642     }
2643   }
2644   if (Unused) {
2645     SmallVector<CCValAssign, 16> RVLocs;
2646     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2647                    getTargetMachine(), RVLocs, *DAG.getContext());
2648     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2649     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2650       CCValAssign &VA = RVLocs[i];
2651       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2652         return false;
2653     }
2654   }
2655
2656   // If the calling conventions do not match, then we'd better make sure the
2657   // results are returned in the same way as what the caller expects.
2658   if (!CCMatch) {
2659     SmallVector<CCValAssign, 16> RVLocs1;
2660     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2661                     getTargetMachine(), RVLocs1, *DAG.getContext());
2662     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2663
2664     SmallVector<CCValAssign, 16> RVLocs2;
2665     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2666                     getTargetMachine(), RVLocs2, *DAG.getContext());
2667     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2668
2669     if (RVLocs1.size() != RVLocs2.size())
2670       return false;
2671     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2672       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2673         return false;
2674       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2675         return false;
2676       if (RVLocs1[i].isRegLoc()) {
2677         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2678           return false;
2679       } else {
2680         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2681           return false;
2682       }
2683     }
2684   }
2685
2686   // If the callee takes no arguments then go on to check the results of the
2687   // call.
2688   if (!Outs.empty()) {
2689     // Check if stack adjustment is needed. For now, do not do this if any
2690     // argument is passed on the stack.
2691     SmallVector<CCValAssign, 16> ArgLocs;
2692     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2693                    getTargetMachine(), ArgLocs, *DAG.getContext());
2694
2695     // Allocate shadow area for Win64
2696     if (Subtarget->isTargetWin64()) {
2697       CCInfo.AllocateStack(32, 8);
2698     }
2699
2700     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2701     if (CCInfo.getNextStackOffset()) {
2702       MachineFunction &MF = DAG.getMachineFunction();
2703       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2704         return false;
2705
2706       // Check if the arguments are already laid out in the right way as
2707       // the caller's fixed stack objects.
2708       MachineFrameInfo *MFI = MF.getFrameInfo();
2709       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2710       const X86InstrInfo *TII =
2711         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2712       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2713         CCValAssign &VA = ArgLocs[i];
2714         SDValue Arg = OutVals[i];
2715         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2716         if (VA.getLocInfo() == CCValAssign::Indirect)
2717           return false;
2718         if (!VA.isRegLoc()) {
2719           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2720                                    MFI, MRI, TII))
2721             return false;
2722         }
2723       }
2724     }
2725
2726     // If the tailcall address may be in a register, then make sure it's
2727     // possible to register allocate for it. In 32-bit, the call address can
2728     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2729     // callee-saved registers are restored. These happen to be the same
2730     // registers used to pass 'inreg' arguments so watch out for those.
2731     if (!Subtarget->is64Bit() &&
2732         !isa<GlobalAddressSDNode>(Callee) &&
2733         !isa<ExternalSymbolSDNode>(Callee)) {
2734       unsigned NumInRegs = 0;
2735       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2736         CCValAssign &VA = ArgLocs[i];
2737         if (!VA.isRegLoc())
2738           continue;
2739         unsigned Reg = VA.getLocReg();
2740         switch (Reg) {
2741         default: break;
2742         case X86::EAX: case X86::EDX: case X86::ECX:
2743           if (++NumInRegs == 3)
2744             return false;
2745           break;
2746         }
2747       }
2748     }
2749   }
2750
2751   return true;
2752 }
2753
2754 FastISel *
2755 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2756   return X86::createFastISel(funcInfo);
2757 }
2758
2759
2760 //===----------------------------------------------------------------------===//
2761 //                           Other Lowering Hooks
2762 //===----------------------------------------------------------------------===//
2763
2764 static bool MayFoldLoad(SDValue Op) {
2765   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2766 }
2767
2768 static bool MayFoldIntoStore(SDValue Op) {
2769   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2770 }
2771
2772 static bool isTargetShuffle(unsigned Opcode) {
2773   switch(Opcode) {
2774   default: return false;
2775   case X86ISD::PSHUFD:
2776   case X86ISD::PSHUFHW:
2777   case X86ISD::PSHUFLW:
2778   case X86ISD::SHUFPD:
2779   case X86ISD::PALIGN:
2780   case X86ISD::SHUFPS:
2781   case X86ISD::MOVLHPS:
2782   case X86ISD::MOVLHPD:
2783   case X86ISD::MOVHLPS:
2784   case X86ISD::MOVLPS:
2785   case X86ISD::MOVLPD:
2786   case X86ISD::MOVSHDUP:
2787   case X86ISD::MOVSLDUP:
2788   case X86ISD::MOVDDUP:
2789   case X86ISD::MOVSS:
2790   case X86ISD::MOVSD:
2791   case X86ISD::UNPCKLPS:
2792   case X86ISD::UNPCKLPD:
2793   case X86ISD::VUNPCKLPSY:
2794   case X86ISD::VUNPCKLPDY:
2795   case X86ISD::PUNPCKLWD:
2796   case X86ISD::PUNPCKLBW:
2797   case X86ISD::PUNPCKLDQ:
2798   case X86ISD::PUNPCKLQDQ:
2799   case X86ISD::UNPCKHPS:
2800   case X86ISD::UNPCKHPD:
2801   case X86ISD::VUNPCKHPSY:
2802   case X86ISD::VUNPCKHPDY:
2803   case X86ISD::PUNPCKHWD:
2804   case X86ISD::PUNPCKHBW:
2805   case X86ISD::PUNPCKHDQ:
2806   case X86ISD::PUNPCKHQDQ:
2807   case X86ISD::VPERMILPS:
2808   case X86ISD::VPERMILPSY:
2809   case X86ISD::VPERMILPD:
2810   case X86ISD::VPERMILPDY:
2811   case X86ISD::VPERM2F128:
2812     return true;
2813   }
2814   return false;
2815 }
2816
2817 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2818                                                SDValue V1, SelectionDAG &DAG) {
2819   switch(Opc) {
2820   default: llvm_unreachable("Unknown x86 shuffle node");
2821   case X86ISD::MOVSHDUP:
2822   case X86ISD::MOVSLDUP:
2823   case X86ISD::MOVDDUP:
2824     return DAG.getNode(Opc, dl, VT, V1);
2825   }
2826
2827   return SDValue();
2828 }
2829
2830 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2831                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2832   switch(Opc) {
2833   default: llvm_unreachable("Unknown x86 shuffle node");
2834   case X86ISD::PSHUFD:
2835   case X86ISD::PSHUFHW:
2836   case X86ISD::PSHUFLW:
2837   case X86ISD::VPERMILPS:
2838   case X86ISD::VPERMILPSY:
2839   case X86ISD::VPERMILPD:
2840   case X86ISD::VPERMILPDY:
2841     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2842   }
2843
2844   return SDValue();
2845 }
2846
2847 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2848                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2849   switch(Opc) {
2850   default: llvm_unreachable("Unknown x86 shuffle node");
2851   case X86ISD::PALIGN:
2852   case X86ISD::SHUFPD:
2853   case X86ISD::SHUFPS:
2854   case X86ISD::VPERM2F128:
2855     return DAG.getNode(Opc, dl, VT, V1, V2,
2856                        DAG.getConstant(TargetMask, MVT::i8));
2857   }
2858   return SDValue();
2859 }
2860
2861 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2862                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2863   switch(Opc) {
2864   default: llvm_unreachable("Unknown x86 shuffle node");
2865   case X86ISD::MOVLHPS:
2866   case X86ISD::MOVLHPD:
2867   case X86ISD::MOVHLPS:
2868   case X86ISD::MOVLPS:
2869   case X86ISD::MOVLPD:
2870   case X86ISD::MOVSS:
2871   case X86ISD::MOVSD:
2872   case X86ISD::UNPCKLPS:
2873   case X86ISD::UNPCKLPD:
2874   case X86ISD::VUNPCKLPSY:
2875   case X86ISD::VUNPCKLPDY:
2876   case X86ISD::PUNPCKLWD:
2877   case X86ISD::PUNPCKLBW:
2878   case X86ISD::PUNPCKLDQ:
2879   case X86ISD::PUNPCKLQDQ:
2880   case X86ISD::UNPCKHPS:
2881   case X86ISD::UNPCKHPD:
2882   case X86ISD::VUNPCKHPSY:
2883   case X86ISD::VUNPCKHPDY:
2884   case X86ISD::PUNPCKHWD:
2885   case X86ISD::PUNPCKHBW:
2886   case X86ISD::PUNPCKHDQ:
2887   case X86ISD::PUNPCKHQDQ:
2888     return DAG.getNode(Opc, dl, VT, V1, V2);
2889   }
2890   return SDValue();
2891 }
2892
2893 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2894   MachineFunction &MF = DAG.getMachineFunction();
2895   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2896   int ReturnAddrIndex = FuncInfo->getRAIndex();
2897
2898   if (ReturnAddrIndex == 0) {
2899     // Set up a frame object for the return address.
2900     uint64_t SlotSize = TD->getPointerSize();
2901     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2902                                                            false);
2903     FuncInfo->setRAIndex(ReturnAddrIndex);
2904   }
2905
2906   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2907 }
2908
2909
2910 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2911                                        bool hasSymbolicDisplacement) {
2912   // Offset should fit into 32 bit immediate field.
2913   if (!isInt<32>(Offset))
2914     return false;
2915
2916   // If we don't have a symbolic displacement - we don't have any extra
2917   // restrictions.
2918   if (!hasSymbolicDisplacement)
2919     return true;
2920
2921   // FIXME: Some tweaks might be needed for medium code model.
2922   if (M != CodeModel::Small && M != CodeModel::Kernel)
2923     return false;
2924
2925   // For small code model we assume that latest object is 16MB before end of 31
2926   // bits boundary. We may also accept pretty large negative constants knowing
2927   // that all objects are in the positive half of address space.
2928   if (M == CodeModel::Small && Offset < 16*1024*1024)
2929     return true;
2930
2931   // For kernel code model we know that all object resist in the negative half
2932   // of 32bits address space. We may not accept negative offsets, since they may
2933   // be just off and we may accept pretty large positive ones.
2934   if (M == CodeModel::Kernel && Offset > 0)
2935     return true;
2936
2937   return false;
2938 }
2939
2940 /// isCalleePop - Determines whether the callee is required to pop its
2941 /// own arguments. Callee pop is necessary to support tail calls.
2942 bool X86::isCalleePop(CallingConv::ID CallingConv,
2943                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2944   if (IsVarArg)
2945     return false;
2946
2947   switch (CallingConv) {
2948   default:
2949     return false;
2950   case CallingConv::X86_StdCall:
2951     return !is64Bit;
2952   case CallingConv::X86_FastCall:
2953     return !is64Bit;
2954   case CallingConv::X86_ThisCall:
2955     return !is64Bit;
2956   case CallingConv::Fast:
2957     return TailCallOpt;
2958   case CallingConv::GHC:
2959     return TailCallOpt;
2960   }
2961 }
2962
2963 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2964 /// specific condition code, returning the condition code and the LHS/RHS of the
2965 /// comparison to make.
2966 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2967                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2968   if (!isFP) {
2969     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2970       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2971         // X > -1   -> X == 0, jump !sign.
2972         RHS = DAG.getConstant(0, RHS.getValueType());
2973         return X86::COND_NS;
2974       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2975         // X < 0   -> X == 0, jump on sign.
2976         return X86::COND_S;
2977       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2978         // X < 1   -> X <= 0
2979         RHS = DAG.getConstant(0, RHS.getValueType());
2980         return X86::COND_LE;
2981       }
2982     }
2983
2984     switch (SetCCOpcode) {
2985     default: llvm_unreachable("Invalid integer condition!");
2986     case ISD::SETEQ:  return X86::COND_E;
2987     case ISD::SETGT:  return X86::COND_G;
2988     case ISD::SETGE:  return X86::COND_GE;
2989     case ISD::SETLT:  return X86::COND_L;
2990     case ISD::SETLE:  return X86::COND_LE;
2991     case ISD::SETNE:  return X86::COND_NE;
2992     case ISD::SETULT: return X86::COND_B;
2993     case ISD::SETUGT: return X86::COND_A;
2994     case ISD::SETULE: return X86::COND_BE;
2995     case ISD::SETUGE: return X86::COND_AE;
2996     }
2997   }
2998
2999   // First determine if it is required or is profitable to flip the operands.
3000
3001   // If LHS is a foldable load, but RHS is not, flip the condition.
3002   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3003       !ISD::isNON_EXTLoad(RHS.getNode())) {
3004     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3005     std::swap(LHS, RHS);
3006   }
3007
3008   switch (SetCCOpcode) {
3009   default: break;
3010   case ISD::SETOLT:
3011   case ISD::SETOLE:
3012   case ISD::SETUGT:
3013   case ISD::SETUGE:
3014     std::swap(LHS, RHS);
3015     break;
3016   }
3017
3018   // On a floating point condition, the flags are set as follows:
3019   // ZF  PF  CF   op
3020   //  0 | 0 | 0 | X > Y
3021   //  0 | 0 | 1 | X < Y
3022   //  1 | 0 | 0 | X == Y
3023   //  1 | 1 | 1 | unordered
3024   switch (SetCCOpcode) {
3025   default: llvm_unreachable("Condcode should be pre-legalized away");
3026   case ISD::SETUEQ:
3027   case ISD::SETEQ:   return X86::COND_E;
3028   case ISD::SETOLT:              // flipped
3029   case ISD::SETOGT:
3030   case ISD::SETGT:   return X86::COND_A;
3031   case ISD::SETOLE:              // flipped
3032   case ISD::SETOGE:
3033   case ISD::SETGE:   return X86::COND_AE;
3034   case ISD::SETUGT:              // flipped
3035   case ISD::SETULT:
3036   case ISD::SETLT:   return X86::COND_B;
3037   case ISD::SETUGE:              // flipped
3038   case ISD::SETULE:
3039   case ISD::SETLE:   return X86::COND_BE;
3040   case ISD::SETONE:
3041   case ISD::SETNE:   return X86::COND_NE;
3042   case ISD::SETUO:   return X86::COND_P;
3043   case ISD::SETO:    return X86::COND_NP;
3044   case ISD::SETOEQ:
3045   case ISD::SETUNE:  return X86::COND_INVALID;
3046   }
3047 }
3048
3049 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3050 /// code. Current x86 isa includes the following FP cmov instructions:
3051 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3052 static bool hasFPCMov(unsigned X86CC) {
3053   switch (X86CC) {
3054   default:
3055     return false;
3056   case X86::COND_B:
3057   case X86::COND_BE:
3058   case X86::COND_E:
3059   case X86::COND_P:
3060   case X86::COND_A:
3061   case X86::COND_AE:
3062   case X86::COND_NE:
3063   case X86::COND_NP:
3064     return true;
3065   }
3066 }
3067
3068 /// isFPImmLegal - Returns true if the target can instruction select the
3069 /// specified FP immediate natively. If false, the legalizer will
3070 /// materialize the FP immediate as a load from a constant pool.
3071 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3072   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3073     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3074       return true;
3075   }
3076   return false;
3077 }
3078
3079 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3080 /// the specified range (L, H].
3081 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3082   return (Val < 0) || (Val >= Low && Val < Hi);
3083 }
3084
3085 /// isUndefOrInRange - Return true if every element in Mask, begining
3086 /// from position Pos and ending in Pos+Size, falls within the specified
3087 /// range (L, L+Pos]. or is undef.
3088 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3089                              int Pos, int Size, int Low, int Hi) {
3090   for (int i = Pos, e = Pos+Size; i != e; ++i)
3091     if (!isUndefOrInRange(Mask[i], Low, Hi))
3092       return false;
3093   return true;
3094 }
3095
3096 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3097 /// specified value.
3098 static bool isUndefOrEqual(int Val, int CmpVal) {
3099   if (Val < 0 || Val == CmpVal)
3100     return true;
3101   return false;
3102 }
3103
3104 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3105 /// from position Pos and ending in Pos+Size, falls within the specified
3106 /// sequential range (L, L+Pos]. or is undef.
3107 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3108                                        int Pos, int Size, int Low) {
3109   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3110     if (!isUndefOrEqual(Mask[i], Low))
3111       return false;
3112   return true;
3113 }
3114
3115 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3116 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3117 /// the second operand.
3118 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3119   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3120     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3121   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3122     return (Mask[0] < 2 && Mask[1] < 2);
3123   return false;
3124 }
3125
3126 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3127   SmallVector<int, 8> M;
3128   N->getMask(M);
3129   return ::isPSHUFDMask(M, N->getValueType(0));
3130 }
3131
3132 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3133 /// is suitable for input to PSHUFHW.
3134 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3135   if (VT != MVT::v8i16)
3136     return false;
3137
3138   // Lower quadword copied in order or undef.
3139   for (int i = 0; i != 4; ++i)
3140     if (Mask[i] >= 0 && Mask[i] != i)
3141       return false;
3142
3143   // Upper quadword shuffled.
3144   for (int i = 4; i != 8; ++i)
3145     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3146       return false;
3147
3148   return true;
3149 }
3150
3151 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3152   SmallVector<int, 8> M;
3153   N->getMask(M);
3154   return ::isPSHUFHWMask(M, N->getValueType(0));
3155 }
3156
3157 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3158 /// is suitable for input to PSHUFLW.
3159 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3160   if (VT != MVT::v8i16)
3161     return false;
3162
3163   // Upper quadword copied in order.
3164   for (int i = 4; i != 8; ++i)
3165     if (Mask[i] >= 0 && Mask[i] != i)
3166       return false;
3167
3168   // Lower quadword shuffled.
3169   for (int i = 0; i != 4; ++i)
3170     if (Mask[i] >= 4)
3171       return false;
3172
3173   return true;
3174 }
3175
3176 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3177   SmallVector<int, 8> M;
3178   N->getMask(M);
3179   return ::isPSHUFLWMask(M, N->getValueType(0));
3180 }
3181
3182 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3183 /// is suitable for input to PALIGNR.
3184 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3185                           bool hasSSSE3OrAVX) {
3186   int i, e = VT.getVectorNumElements();
3187   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3188     return false;
3189
3190   // Do not handle v2i64 / v2f64 shuffles with palignr.
3191   if (e < 4 || !hasSSSE3OrAVX)
3192     return false;
3193
3194   for (i = 0; i != e; ++i)
3195     if (Mask[i] >= 0)
3196       break;
3197
3198   // All undef, not a palignr.
3199   if (i == e)
3200     return false;
3201
3202   // Make sure we're shifting in the right direction.
3203   if (Mask[i] <= i)
3204     return false;
3205
3206   int s = Mask[i] - i;
3207
3208   // Check the rest of the elements to see if they are consecutive.
3209   for (++i; i != e; ++i) {
3210     int m = Mask[i];
3211     if (m >= 0 && m != s+i)
3212       return false;
3213   }
3214   return true;
3215 }
3216
3217 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3218 /// specifies a shuffle of elements that is suitable for input to 256-bit
3219 /// VSHUFPSY.
3220 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3221                           const X86Subtarget *Subtarget) {
3222   int NumElems = VT.getVectorNumElements();
3223
3224   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3225     return false;
3226
3227   if (NumElems != 8)
3228     return false;
3229
3230   // VSHUFPSY divides the resulting vector into 4 chunks.
3231   // The sources are also splitted into 4 chunks, and each destination
3232   // chunk must come from a different source chunk.
3233   //
3234   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3235   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3236   //
3237   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3238   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3239   //
3240   int QuarterSize = NumElems/4;
3241   int HalfSize = QuarterSize*2;
3242   for (int i = 0; i < QuarterSize; ++i)
3243     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3244       return false;
3245   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3246     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3247       return false;
3248
3249   // The mask of the second half must be the same as the first but with
3250   // the appropriate offsets. This works in the same way as VPERMILPS
3251   // works with masks.
3252   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3253     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3254       return false;
3255     int FstHalfIdx = i-HalfSize;
3256     if (Mask[FstHalfIdx] < 0)
3257       continue;
3258     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3259       return false;
3260   }
3261   for (int i = QuarterSize*3; i < NumElems; ++i) {
3262     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3263       return false;
3264     int FstHalfIdx = i-HalfSize;
3265     if (Mask[FstHalfIdx] < 0)
3266       continue;
3267     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3268       return false;
3269
3270   }
3271
3272   return true;
3273 }
3274
3275 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3276 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3277 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3278   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3279   EVT VT = SVOp->getValueType(0);
3280   int NumElems = VT.getVectorNumElements();
3281
3282   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3283          "Only supports v8i32 and v8f32 types");
3284
3285   int HalfSize = NumElems/2;
3286   unsigned Mask = 0;
3287   for (int i = 0; i != NumElems ; ++i) {
3288     if (SVOp->getMaskElt(i) < 0)
3289       continue;
3290     // The mask of the first half must be equal to the second one.
3291     unsigned Shamt = (i%HalfSize)*2;
3292     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3293     Mask |= Elt << Shamt;
3294   }
3295
3296   return Mask;
3297 }
3298
3299 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3300 /// specifies a shuffle of elements that is suitable for input to 256-bit
3301 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3302 /// version and the mask of the second half isn't binded with the first
3303 /// one.
3304 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3305                            const X86Subtarget *Subtarget) {
3306   int NumElems = VT.getVectorNumElements();
3307
3308   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3309     return false;
3310
3311   if (NumElems != 4)
3312     return false;
3313
3314   // VSHUFPSY divides the resulting vector into 4 chunks.
3315   // The sources are also splitted into 4 chunks, and each destination
3316   // chunk must come from a different source chunk.
3317   //
3318   //  SRC1 =>      X3       X2       X1       X0
3319   //  SRC2 =>      Y3       Y2       Y1       Y0
3320   //
3321   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3322   //
3323   int QuarterSize = NumElems/4;
3324   int HalfSize = QuarterSize*2;
3325   for (int i = 0; i < QuarterSize; ++i)
3326     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3327       return false;
3328   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3329     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3330       return false;
3331   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3332     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3333       return false;
3334   for (int i = QuarterSize*3; i < NumElems; ++i)
3335     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3336       return false;
3337
3338   return true;
3339 }
3340
3341 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3342 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3343 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3344   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3345   EVT VT = SVOp->getValueType(0);
3346   int NumElems = VT.getVectorNumElements();
3347
3348   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3349          "Only supports v4i64 and v4f64 types");
3350
3351   int HalfSize = NumElems/2;
3352   unsigned Mask = 0;
3353   for (int i = 0; i != NumElems ; ++i) {
3354     if (SVOp->getMaskElt(i) < 0)
3355       continue;
3356     int Elt = SVOp->getMaskElt(i) % HalfSize;
3357     Mask |= Elt << i;
3358   }
3359
3360   return Mask;
3361 }
3362
3363 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3364 /// specifies a shuffle of elements that is suitable for input to 128-bit
3365 /// SHUFPS and SHUFPD.
3366 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3367   int NumElems = VT.getVectorNumElements();
3368
3369   if (VT.getSizeInBits() != 128)
3370     return false;
3371
3372   if (NumElems != 2 && NumElems != 4)
3373     return false;
3374
3375   int Half = NumElems / 2;
3376   for (int i = 0; i < Half; ++i)
3377     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3378       return false;
3379   for (int i = Half; i < NumElems; ++i)
3380     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3381       return false;
3382
3383   return true;
3384 }
3385
3386 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3387   SmallVector<int, 8> M;
3388   N->getMask(M);
3389   return ::isSHUFPMask(M, N->getValueType(0));
3390 }
3391
3392 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3393 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3394 /// half elements to come from vector 1 (which would equal the dest.) and
3395 /// the upper half to come from vector 2.
3396 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3397   int NumElems = VT.getVectorNumElements();
3398
3399   if (NumElems != 2 && NumElems != 4)
3400     return false;
3401
3402   int Half = NumElems / 2;
3403   for (int i = 0; i < Half; ++i)
3404     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3405       return false;
3406   for (int i = Half; i < NumElems; ++i)
3407     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3408       return false;
3409   return true;
3410 }
3411
3412 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3413   SmallVector<int, 8> M;
3414   N->getMask(M);
3415   return isCommutedSHUFPMask(M, N->getValueType(0));
3416 }
3417
3418 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3420 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3421   EVT VT = N->getValueType(0);
3422   unsigned NumElems = VT.getVectorNumElements();
3423
3424   if (VT.getSizeInBits() != 128)
3425     return false;
3426
3427   if (NumElems != 4)
3428     return false;
3429
3430   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3431   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3432          isUndefOrEqual(N->getMaskElt(1), 7) &&
3433          isUndefOrEqual(N->getMaskElt(2), 2) &&
3434          isUndefOrEqual(N->getMaskElt(3), 3);
3435 }
3436
3437 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3438 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3439 /// <2, 3, 2, 3>
3440 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3441   EVT VT = N->getValueType(0);
3442   unsigned NumElems = VT.getVectorNumElements();
3443
3444   if (VT.getSizeInBits() != 128)
3445     return false;
3446
3447   if (NumElems != 4)
3448     return false;
3449
3450   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3451          isUndefOrEqual(N->getMaskElt(1), 3) &&
3452          isUndefOrEqual(N->getMaskElt(2), 2) &&
3453          isUndefOrEqual(N->getMaskElt(3), 3);
3454 }
3455
3456 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3457 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3458 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3459   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3460
3461   if (NumElems != 2 && NumElems != 4)
3462     return false;
3463
3464   for (unsigned i = 0; i < NumElems/2; ++i)
3465     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3466       return false;
3467
3468   for (unsigned i = NumElems/2; i < NumElems; ++i)
3469     if (!isUndefOrEqual(N->getMaskElt(i), i))
3470       return false;
3471
3472   return true;
3473 }
3474
3475 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3476 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3477 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3478   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3479
3480   if ((NumElems != 2 && NumElems != 4)
3481       || N->getValueType(0).getSizeInBits() > 128)
3482     return false;
3483
3484   for (unsigned i = 0; i < NumElems/2; ++i)
3485     if (!isUndefOrEqual(N->getMaskElt(i), i))
3486       return false;
3487
3488   for (unsigned i = 0; i < NumElems/2; ++i)
3489     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3490       return false;
3491
3492   return true;
3493 }
3494
3495 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3497 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3498                          bool V2IsSplat = false) {
3499   int NumElts = VT.getVectorNumElements();
3500
3501   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3502          "Unsupported vector type for unpckh");
3503
3504   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3505     return false;
3506
3507   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3508   // independently on 128-bit lanes.
3509   unsigned NumLanes = VT.getSizeInBits()/128;
3510   unsigned NumLaneElts = NumElts/NumLanes;
3511
3512   unsigned Start = 0;
3513   unsigned End = NumLaneElts;
3514   for (unsigned s = 0; s < NumLanes; ++s) {
3515     for (unsigned i = Start, j = s * NumLaneElts;
3516          i != End;
3517          i += 2, ++j) {
3518       int BitI  = Mask[i];
3519       int BitI1 = Mask[i+1];
3520       if (!isUndefOrEqual(BitI, j))
3521         return false;
3522       if (V2IsSplat) {
3523         if (!isUndefOrEqual(BitI1, NumElts))
3524           return false;
3525       } else {
3526         if (!isUndefOrEqual(BitI1, j + NumElts))
3527           return false;
3528       }
3529     }
3530     // Process the next 128 bits.
3531     Start += NumLaneElts;
3532     End += NumLaneElts;
3533   }
3534
3535   return true;
3536 }
3537
3538 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3539   SmallVector<int, 8> M;
3540   N->getMask(M);
3541   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3542 }
3543
3544 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3545 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3546 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3547                          bool V2IsSplat = false) {
3548   int NumElts = VT.getVectorNumElements();
3549
3550   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3551          "Unsupported vector type for unpckh");
3552
3553   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3554     return false;
3555
3556   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3557   // independently on 128-bit lanes.
3558   unsigned NumLanes = VT.getSizeInBits()/128;
3559   unsigned NumLaneElts = NumElts/NumLanes;
3560
3561   unsigned Start = 0;
3562   unsigned End = NumLaneElts;
3563   for (unsigned l = 0; l != NumLanes; ++l) {
3564     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3565                              i != End; i += 2, ++j) {
3566       int BitI  = Mask[i];
3567       int BitI1 = Mask[i+1];
3568       if (!isUndefOrEqual(BitI, j))
3569         return false;
3570       if (V2IsSplat) {
3571         if (isUndefOrEqual(BitI1, NumElts))
3572           return false;
3573       } else {
3574         if (!isUndefOrEqual(BitI1, j+NumElts))
3575           return false;
3576       }
3577     }
3578     // Process the next 128 bits.
3579     Start += NumLaneElts;
3580     End += NumLaneElts;
3581   }
3582   return true;
3583 }
3584
3585 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3586   SmallVector<int, 8> M;
3587   N->getMask(M);
3588   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3589 }
3590
3591 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3592 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3593 /// <0, 0, 1, 1>
3594 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3595   int NumElems = VT.getVectorNumElements();
3596   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3597     return false;
3598
3599   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3600   // FIXME: Need a better way to get rid of this, there's no latency difference
3601   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3602   // the former later. We should also remove the "_undef" special mask.
3603   if (NumElems == 4 && VT.getSizeInBits() == 256)
3604     return false;
3605
3606   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3607   // independently on 128-bit lanes.
3608   unsigned NumLanes = VT.getSizeInBits() / 128;
3609   unsigned NumLaneElts = NumElems / NumLanes;
3610
3611   for (unsigned s = 0; s < NumLanes; ++s) {
3612     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3613          i != NumLaneElts * (s + 1);
3614          i += 2, ++j) {
3615       int BitI  = Mask[i];
3616       int BitI1 = Mask[i+1];
3617
3618       if (!isUndefOrEqual(BitI, j))
3619         return false;
3620       if (!isUndefOrEqual(BitI1, j))
3621         return false;
3622     }
3623   }
3624
3625   return true;
3626 }
3627
3628 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3629   SmallVector<int, 8> M;
3630   N->getMask(M);
3631   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3632 }
3633
3634 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3635 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3636 /// <2, 2, 3, 3>
3637 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3638   int NumElems = VT.getVectorNumElements();
3639   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3640     return false;
3641
3642   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3643     int BitI  = Mask[i];
3644     int BitI1 = Mask[i+1];
3645     if (!isUndefOrEqual(BitI, j))
3646       return false;
3647     if (!isUndefOrEqual(BitI1, j))
3648       return false;
3649   }
3650   return true;
3651 }
3652
3653 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3654   SmallVector<int, 8> M;
3655   N->getMask(M);
3656   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3657 }
3658
3659 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3660 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3661 /// MOVSD, and MOVD, i.e. setting the lowest element.
3662 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3663   if (VT.getVectorElementType().getSizeInBits() < 32)
3664     return false;
3665
3666   int NumElts = VT.getVectorNumElements();
3667
3668   if (!isUndefOrEqual(Mask[0], NumElts))
3669     return false;
3670
3671   for (int i = 1; i < NumElts; ++i)
3672     if (!isUndefOrEqual(Mask[i], i))
3673       return false;
3674
3675   return true;
3676 }
3677
3678 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3679   SmallVector<int, 8> M;
3680   N->getMask(M);
3681   return ::isMOVLMask(M, N->getValueType(0));
3682 }
3683
3684 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3685 /// as permutations between 128-bit chunks or halves. As an example: this
3686 /// shuffle bellow:
3687 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3688 /// The first half comes from the second half of V1 and the second half from the
3689 /// the second half of V2.
3690 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3691                              const X86Subtarget *Subtarget) {
3692   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3693     return false;
3694
3695   // The shuffle result is divided into half A and half B. In total the two
3696   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3697   // B must come from C, D, E or F.
3698   int HalfSize = VT.getVectorNumElements()/2;
3699   bool MatchA = false, MatchB = false;
3700
3701   // Check if A comes from one of C, D, E, F.
3702   for (int Half = 0; Half < 4; ++Half) {
3703     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3704       MatchA = true;
3705       break;
3706     }
3707   }
3708
3709   // Check if B comes from one of C, D, E, F.
3710   for (int Half = 0; Half < 4; ++Half) {
3711     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3712       MatchB = true;
3713       break;
3714     }
3715   }
3716
3717   return MatchA && MatchB;
3718 }
3719
3720 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3721 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3722 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3723   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3724   EVT VT = SVOp->getValueType(0);
3725
3726   int HalfSize = VT.getVectorNumElements()/2;
3727
3728   int FstHalf = 0, SndHalf = 0;
3729   for (int i = 0; i < HalfSize; ++i) {
3730     if (SVOp->getMaskElt(i) > 0) {
3731       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3732       break;
3733     }
3734   }
3735   for (int i = HalfSize; i < HalfSize*2; ++i) {
3736     if (SVOp->getMaskElt(i) > 0) {
3737       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3738       break;
3739     }
3740   }
3741
3742   return (FstHalf | (SndHalf << 4));
3743 }
3744
3745 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3746 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3747 /// Note that VPERMIL mask matching is different depending whether theunderlying
3748 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3749 /// to the same elements of the low, but to the higher half of the source.
3750 /// In VPERMILPD the two lanes could be shuffled independently of each other
3751 /// with the same restriction that lanes can't be crossed.
3752 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3753                             const X86Subtarget *Subtarget) {
3754   int NumElts = VT.getVectorNumElements();
3755   int NumLanes = VT.getSizeInBits()/128;
3756
3757   if (!Subtarget->hasAVX())
3758     return false;
3759
3760   // Match any permutation of 128-bit vector with 64-bit types
3761   if (NumLanes == 1 && NumElts != 2)
3762     return false;
3763
3764   // Only match 256-bit with 32 types
3765   if (VT.getSizeInBits() == 256 && NumElts != 4)
3766     return false;
3767
3768   // The mask on the high lane is independent of the low. Both can match
3769   // any element in inside its own lane, but can't cross.
3770   int LaneSize = NumElts/NumLanes;
3771   for (int l = 0; l < NumLanes; ++l)
3772     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3773       int LaneStart = l*LaneSize;
3774       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3775         return false;
3776     }
3777
3778   return true;
3779 }
3780
3781 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3782 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3783 /// Note that VPERMIL mask matching is different depending whether theunderlying
3784 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3785 /// to the same elements of the low, but to the higher half of the source.
3786 /// In VPERMILPD the two lanes could be shuffled independently of each other
3787 /// with the same restriction that lanes can't be crossed.
3788 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3789                             const X86Subtarget *Subtarget) {
3790   unsigned NumElts = VT.getVectorNumElements();
3791   unsigned NumLanes = VT.getSizeInBits()/128;
3792
3793   if (!Subtarget->hasAVX())
3794     return false;
3795
3796   // Match any permutation of 128-bit vector with 32-bit types
3797   if (NumLanes == 1 && NumElts != 4)
3798     return false;
3799
3800   // Only match 256-bit with 32 types
3801   if (VT.getSizeInBits() == 256 && NumElts != 8)
3802     return false;
3803
3804   // The mask on the high lane should be the same as the low. Actually,
3805   // they can differ if any of the corresponding index in a lane is undef
3806   // and the other stays in range.
3807   int LaneSize = NumElts/NumLanes;
3808   for (int i = 0; i < LaneSize; ++i) {
3809     int HighElt = i+LaneSize;
3810     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3811     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3812
3813     if (!HighValid || !LowValid)
3814       return false;
3815     if (Mask[i] < 0 || Mask[HighElt] < 0)
3816       continue;
3817     if (Mask[HighElt]-Mask[i] != LaneSize)
3818       return false;
3819   }
3820
3821   return true;
3822 }
3823
3824 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3825 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3826 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3827   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3828   EVT VT = SVOp->getValueType(0);
3829
3830   int NumElts = VT.getVectorNumElements();
3831   int NumLanes = VT.getSizeInBits()/128;
3832   int LaneSize = NumElts/NumLanes;
3833
3834   // Although the mask is equal for both lanes do it twice to get the cases
3835   // where a mask will match because the same mask element is undef on the
3836   // first half but valid on the second. This would get pathological cases
3837   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3838   unsigned Mask = 0;
3839   for (int l = 0; l < NumLanes; ++l) {
3840     for (int i = 0; i < LaneSize; ++i) {
3841       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3842       if (MaskElt < 0)
3843         continue;
3844       if (MaskElt >= LaneSize)
3845         MaskElt -= LaneSize;
3846       Mask |= MaskElt << (i*2);
3847     }
3848   }
3849
3850   return Mask;
3851 }
3852
3853 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3854 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3855 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3856   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3857   EVT VT = SVOp->getValueType(0);
3858
3859   int NumElts = VT.getVectorNumElements();
3860   int NumLanes = VT.getSizeInBits()/128;
3861
3862   unsigned Mask = 0;
3863   int LaneSize = NumElts/NumLanes;
3864   for (int l = 0; l < NumLanes; ++l)
3865     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3866       int MaskElt = SVOp->getMaskElt(i);
3867       if (MaskElt < 0)
3868         continue;
3869       Mask |= (MaskElt-l*LaneSize) << i;
3870     }
3871
3872   return Mask;
3873 }
3874
3875 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3876 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3877 /// element of vector 2 and the other elements to come from vector 1 in order.
3878 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3879                                bool V2IsSplat = false, bool V2IsUndef = false) {
3880   int NumOps = VT.getVectorNumElements();
3881   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3882     return false;
3883
3884   if (!isUndefOrEqual(Mask[0], 0))
3885     return false;
3886
3887   for (int i = 1; i < NumOps; ++i)
3888     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3889           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3890           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3891       return false;
3892
3893   return true;
3894 }
3895
3896 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3897                            bool V2IsUndef = false) {
3898   SmallVector<int, 8> M;
3899   N->getMask(M);
3900   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3901 }
3902
3903 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3905 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3906 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3907                          const X86Subtarget *Subtarget) {
3908   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3909     return false;
3910
3911   // The second vector must be undef
3912   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3913     return false;
3914
3915   EVT VT = N->getValueType(0);
3916   unsigned NumElems = VT.getVectorNumElements();
3917
3918   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3919       (VT.getSizeInBits() == 256 && NumElems != 8))
3920     return false;
3921
3922   // "i+1" is the value the indexed mask element must have
3923   for (unsigned i = 0; i < NumElems; i += 2)
3924     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3925         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3926       return false;
3927
3928   return true;
3929 }
3930
3931 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3932 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3933 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3934 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3935                          const X86Subtarget *Subtarget) {
3936   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3937     return false;
3938
3939   // The second vector must be undef
3940   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3941     return false;
3942
3943   EVT VT = N->getValueType(0);
3944   unsigned NumElems = VT.getVectorNumElements();
3945
3946   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3947       (VT.getSizeInBits() == 256 && NumElems != 8))
3948     return false;
3949
3950   // "i" is the value the indexed mask element must have
3951   for (unsigned i = 0; i < NumElems; i += 2)
3952     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3953         !isUndefOrEqual(N->getMaskElt(i+1), i))
3954       return false;
3955
3956   return true;
3957 }
3958
3959 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to 256-bit
3961 /// version of MOVDDUP.
3962 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3963                            const X86Subtarget *Subtarget) {
3964   EVT VT = N->getValueType(0);
3965   int NumElts = VT.getVectorNumElements();
3966   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3967
3968   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3969       !V2IsUndef || NumElts != 4)
3970     return false;
3971
3972   for (int i = 0; i != NumElts/2; ++i)
3973     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3974       return false;
3975   for (int i = NumElts/2; i != NumElts; ++i)
3976     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3977       return false;
3978   return true;
3979 }
3980
3981 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to 128-bit
3983 /// version of MOVDDUP.
3984 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3985   EVT VT = N->getValueType(0);
3986
3987   if (VT.getSizeInBits() != 128)
3988     return false;
3989
3990   int e = VT.getVectorNumElements() / 2;
3991   for (int i = 0; i < e; ++i)
3992     if (!isUndefOrEqual(N->getMaskElt(i), i))
3993       return false;
3994   for (int i = 0; i < e; ++i)
3995     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3996       return false;
3997   return true;
3998 }
3999
4000 /// isVEXTRACTF128Index - Return true if the specified
4001 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4002 /// suitable for input to VEXTRACTF128.
4003 bool X86::isVEXTRACTF128Index(SDNode *N) {
4004   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4005     return false;
4006
4007   // The index should be aligned on a 128-bit boundary.
4008   uint64_t Index =
4009     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4010
4011   unsigned VL = N->getValueType(0).getVectorNumElements();
4012   unsigned VBits = N->getValueType(0).getSizeInBits();
4013   unsigned ElSize = VBits / VL;
4014   bool Result = (Index * ElSize) % 128 == 0;
4015
4016   return Result;
4017 }
4018
4019 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4020 /// operand specifies a subvector insert that is suitable for input to
4021 /// VINSERTF128.
4022 bool X86::isVINSERTF128Index(SDNode *N) {
4023   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4024     return false;
4025
4026   // The index should be aligned on a 128-bit boundary.
4027   uint64_t Index =
4028     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4029
4030   unsigned VL = N->getValueType(0).getVectorNumElements();
4031   unsigned VBits = N->getValueType(0).getSizeInBits();
4032   unsigned ElSize = VBits / VL;
4033   bool Result = (Index * ElSize) % 128 == 0;
4034
4035   return Result;
4036 }
4037
4038 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4039 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4040 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4041   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4042   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4043
4044   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4045   unsigned Mask = 0;
4046   for (int i = 0; i < NumOperands; ++i) {
4047     int Val = SVOp->getMaskElt(NumOperands-i-1);
4048     if (Val < 0) Val = 0;
4049     if (Val >= NumOperands) Val -= NumOperands;
4050     Mask |= Val;
4051     if (i != NumOperands - 1)
4052       Mask <<= Shift;
4053   }
4054   return Mask;
4055 }
4056
4057 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4058 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4059 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4060   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4061   unsigned Mask = 0;
4062   // 8 nodes, but we only care about the last 4.
4063   for (unsigned i = 7; i >= 4; --i) {
4064     int Val = SVOp->getMaskElt(i);
4065     if (Val >= 0)
4066       Mask |= (Val - 4);
4067     if (i != 4)
4068       Mask <<= 2;
4069   }
4070   return Mask;
4071 }
4072
4073 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4074 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4075 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4076   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4077   unsigned Mask = 0;
4078   // 8 nodes, but we only care about the first 4.
4079   for (int i = 3; i >= 0; --i) {
4080     int Val = SVOp->getMaskElt(i);
4081     if (Val >= 0)
4082       Mask |= Val;
4083     if (i != 0)
4084       Mask <<= 2;
4085   }
4086   return Mask;
4087 }
4088
4089 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4090 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4091 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4092   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4093   EVT VVT = N->getValueType(0);
4094   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4095   int Val = 0;
4096
4097   unsigned i, e;
4098   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4099     Val = SVOp->getMaskElt(i);
4100     if (Val >= 0)
4101       break;
4102   }
4103   assert(Val - i > 0 && "PALIGNR imm should be positive");
4104   return (Val - i) * EltSize;
4105 }
4106
4107 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4108 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4109 /// instructions.
4110 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4111   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4112     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4113
4114   uint64_t Index =
4115     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4116
4117   EVT VecVT = N->getOperand(0).getValueType();
4118   EVT ElVT = VecVT.getVectorElementType();
4119
4120   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4121   return Index / NumElemsPerChunk;
4122 }
4123
4124 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4125 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4126 /// instructions.
4127 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4128   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4129     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4130
4131   uint64_t Index =
4132     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4133
4134   EVT VecVT = N->getValueType(0);
4135   EVT ElVT = VecVT.getVectorElementType();
4136
4137   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4138   return Index / NumElemsPerChunk;
4139 }
4140
4141 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4142 /// constant +0.0.
4143 bool X86::isZeroNode(SDValue Elt) {
4144   return ((isa<ConstantSDNode>(Elt) &&
4145            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4146           (isa<ConstantFPSDNode>(Elt) &&
4147            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4148 }
4149
4150 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4151 /// their permute mask.
4152 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4153                                     SelectionDAG &DAG) {
4154   EVT VT = SVOp->getValueType(0);
4155   unsigned NumElems = VT.getVectorNumElements();
4156   SmallVector<int, 8> MaskVec;
4157
4158   for (unsigned i = 0; i != NumElems; ++i) {
4159     int idx = SVOp->getMaskElt(i);
4160     if (idx < 0)
4161       MaskVec.push_back(idx);
4162     else if (idx < (int)NumElems)
4163       MaskVec.push_back(idx + NumElems);
4164     else
4165       MaskVec.push_back(idx - NumElems);
4166   }
4167   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4168                               SVOp->getOperand(0), &MaskVec[0]);
4169 }
4170
4171 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4172 /// the two vector operands have swapped position.
4173 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4174   unsigned NumElems = VT.getVectorNumElements();
4175   for (unsigned i = 0; i != NumElems; ++i) {
4176     int idx = Mask[i];
4177     if (idx < 0)
4178       continue;
4179     else if (idx < (int)NumElems)
4180       Mask[i] = idx + NumElems;
4181     else
4182       Mask[i] = idx - NumElems;
4183   }
4184 }
4185
4186 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4187 /// match movhlps. The lower half elements should come from upper half of
4188 /// V1 (and in order), and the upper half elements should come from the upper
4189 /// half of V2 (and in order).
4190 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4191   EVT VT = Op->getValueType(0);
4192   if (VT.getSizeInBits() != 128)
4193     return false;
4194   if (VT.getVectorNumElements() != 4)
4195     return false;
4196   for (unsigned i = 0, e = 2; i != e; ++i)
4197     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4198       return false;
4199   for (unsigned i = 2; i != 4; ++i)
4200     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4201       return false;
4202   return true;
4203 }
4204
4205 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4206 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4207 /// required.
4208 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4209   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4210     return false;
4211   N = N->getOperand(0).getNode();
4212   if (!ISD::isNON_EXTLoad(N))
4213     return false;
4214   if (LD)
4215     *LD = cast<LoadSDNode>(N);
4216   return true;
4217 }
4218
4219 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4220 /// match movlp{s|d}. The lower half elements should come from lower half of
4221 /// V1 (and in order), and the upper half elements should come from the upper
4222 /// half of V2 (and in order). And since V1 will become the source of the
4223 /// MOVLP, it must be either a vector load or a scalar load to vector.
4224 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4225                                ShuffleVectorSDNode *Op) {
4226   EVT VT = Op->getValueType(0);
4227   if (VT.getSizeInBits() != 128)
4228     return false;
4229
4230   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4231     return false;
4232   // Is V2 is a vector load, don't do this transformation. We will try to use
4233   // load folding shufps op.
4234   if (ISD::isNON_EXTLoad(V2))
4235     return false;
4236
4237   unsigned NumElems = VT.getVectorNumElements();
4238
4239   if (NumElems != 2 && NumElems != 4)
4240     return false;
4241   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4242     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4243       return false;
4244   for (unsigned i = NumElems/2; i != NumElems; ++i)
4245     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4246       return false;
4247   return true;
4248 }
4249
4250 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4251 /// all the same.
4252 static bool isSplatVector(SDNode *N) {
4253   if (N->getOpcode() != ISD::BUILD_VECTOR)
4254     return false;
4255
4256   SDValue SplatValue = N->getOperand(0);
4257   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4258     if (N->getOperand(i) != SplatValue)
4259       return false;
4260   return true;
4261 }
4262
4263 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4264 /// to an zero vector.
4265 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4266 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4267   SDValue V1 = N->getOperand(0);
4268   SDValue V2 = N->getOperand(1);
4269   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4270   for (unsigned i = 0; i != NumElems; ++i) {
4271     int Idx = N->getMaskElt(i);
4272     if (Idx >= (int)NumElems) {
4273       unsigned Opc = V2.getOpcode();
4274       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4275         continue;
4276       if (Opc != ISD::BUILD_VECTOR ||
4277           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4278         return false;
4279     } else if (Idx >= 0) {
4280       unsigned Opc = V1.getOpcode();
4281       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4282         continue;
4283       if (Opc != ISD::BUILD_VECTOR ||
4284           !X86::isZeroNode(V1.getOperand(Idx)))
4285         return false;
4286     }
4287   }
4288   return true;
4289 }
4290
4291 /// getZeroVector - Returns a vector of specified type with all zero elements.
4292 ///
4293 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4294                              DebugLoc dl) {
4295   assert(VT.isVector() && "Expected a vector type");
4296
4297   // Always build SSE zero vectors as <4 x i32> bitcasted
4298   // to their dest type. This ensures they get CSE'd.
4299   SDValue Vec;
4300   if (VT.getSizeInBits() == 128) {  // SSE
4301     if (HasXMMInt) {  // SSE2
4302       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4303       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4304     } else { // SSE1
4305       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4306       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4307     }
4308   } else if (VT.getSizeInBits() == 256) { // AVX
4309     // 256-bit logic and arithmetic instructions in AVX are
4310     // all floating-point, no support for integer ops. Default
4311     // to emitting fp zeroed vectors then.
4312     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4313     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4314     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4315   }
4316   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4317 }
4318
4319 /// getOnesVector - Returns a vector of specified type with all bits set.
4320 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4321 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4322 /// original type, ensuring they get CSE'd.
4323 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4324   assert(VT.isVector() && "Expected a vector type");
4325   assert((VT.is128BitVector() || VT.is256BitVector())
4326          && "Expected a 128-bit or 256-bit vector type");
4327
4328   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4329   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4330                             Cst, Cst, Cst, Cst);
4331
4332   if (VT.is256BitVector()) {
4333     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4334                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4335     Vec = Insert128BitVector(InsV, Vec,
4336                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4337   }
4338
4339   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4340 }
4341
4342 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4343 /// that point to V2 points to its first element.
4344 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4345   EVT VT = SVOp->getValueType(0);
4346   unsigned NumElems = VT.getVectorNumElements();
4347
4348   bool Changed = false;
4349   SmallVector<int, 8> MaskVec;
4350   SVOp->getMask(MaskVec);
4351
4352   for (unsigned i = 0; i != NumElems; ++i) {
4353     if (MaskVec[i] > (int)NumElems) {
4354       MaskVec[i] = NumElems;
4355       Changed = true;
4356     }
4357   }
4358   if (Changed)
4359     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4360                                 SVOp->getOperand(1), &MaskVec[0]);
4361   return SDValue(SVOp, 0);
4362 }
4363
4364 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4365 /// operation of specified width.
4366 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4367                        SDValue V2) {
4368   unsigned NumElems = VT.getVectorNumElements();
4369   SmallVector<int, 8> Mask;
4370   Mask.push_back(NumElems);
4371   for (unsigned i = 1; i != NumElems; ++i)
4372     Mask.push_back(i);
4373   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4374 }
4375
4376 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4377 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4378                           SDValue V2) {
4379   unsigned NumElems = VT.getVectorNumElements();
4380   SmallVector<int, 8> Mask;
4381   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4382     Mask.push_back(i);
4383     Mask.push_back(i + NumElems);
4384   }
4385   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4386 }
4387
4388 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4389 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4390                           SDValue V2) {
4391   unsigned NumElems = VT.getVectorNumElements();
4392   unsigned Half = NumElems/2;
4393   SmallVector<int, 8> Mask;
4394   for (unsigned i = 0; i != Half; ++i) {
4395     Mask.push_back(i + Half);
4396     Mask.push_back(i + NumElems + Half);
4397   }
4398   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4399 }
4400
4401 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4402 // a generic shuffle instruction because the target has no such instructions.
4403 // Generate shuffles which repeat i16 and i8 several times until they can be
4404 // represented by v4f32 and then be manipulated by target suported shuffles.
4405 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4406   EVT VT = V.getValueType();
4407   int NumElems = VT.getVectorNumElements();
4408   DebugLoc dl = V.getDebugLoc();
4409
4410   while (NumElems > 4) {
4411     if (EltNo < NumElems/2) {
4412       V = getUnpackl(DAG, dl, VT, V, V);
4413     } else {
4414       V = getUnpackh(DAG, dl, VT, V, V);
4415       EltNo -= NumElems/2;
4416     }
4417     NumElems >>= 1;
4418   }
4419   return V;
4420 }
4421
4422 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4423 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4424   EVT VT = V.getValueType();
4425   DebugLoc dl = V.getDebugLoc();
4426   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4427          && "Vector size not supported");
4428
4429   if (VT.getSizeInBits() == 128) {
4430     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4431     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4432     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4433                              &SplatMask[0]);
4434   } else {
4435     // To use VPERMILPS to splat scalars, the second half of indicies must
4436     // refer to the higher part, which is a duplication of the lower one,
4437     // because VPERMILPS can only handle in-lane permutations.
4438     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4439                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4440
4441     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4442     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4443                              &SplatMask[0]);
4444   }
4445
4446   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4447 }
4448
4449 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4450 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4451   EVT SrcVT = SV->getValueType(0);
4452   SDValue V1 = SV->getOperand(0);
4453   DebugLoc dl = SV->getDebugLoc();
4454
4455   int EltNo = SV->getSplatIndex();
4456   int NumElems = SrcVT.getVectorNumElements();
4457   unsigned Size = SrcVT.getSizeInBits();
4458
4459   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4460           "Unknown how to promote splat for type");
4461
4462   // Extract the 128-bit part containing the splat element and update
4463   // the splat element index when it refers to the higher register.
4464   if (Size == 256) {
4465     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4466     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4467     if (Idx > 0)
4468       EltNo -= NumElems/2;
4469   }
4470
4471   // All i16 and i8 vector types can't be used directly by a generic shuffle
4472   // instruction because the target has no such instruction. Generate shuffles
4473   // which repeat i16 and i8 several times until they fit in i32, and then can
4474   // be manipulated by target suported shuffles.
4475   EVT EltVT = SrcVT.getVectorElementType();
4476   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4477     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4478
4479   // Recreate the 256-bit vector and place the same 128-bit vector
4480   // into the low and high part. This is necessary because we want
4481   // to use VPERM* to shuffle the vectors
4482   if (Size == 256) {
4483     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4484                          DAG.getConstant(0, MVT::i32), DAG, dl);
4485     V1 = Insert128BitVector(InsV, V1,
4486                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4487   }
4488
4489   return getLegalSplat(DAG, V1, EltNo);
4490 }
4491
4492 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4493 /// vector of zero or undef vector.  This produces a shuffle where the low
4494 /// element of V2 is swizzled into the zero/undef vector, landing at element
4495 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4496 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4497                                            bool isZero, bool HasXMMInt,
4498                                            SelectionDAG &DAG) {
4499   EVT VT = V2.getValueType();
4500   SDValue V1 = isZero
4501     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4502   unsigned NumElems = VT.getVectorNumElements();
4503   SmallVector<int, 16> MaskVec;
4504   for (unsigned i = 0; i != NumElems; ++i)
4505     // If this is the insertion idx, put the low elt of V2 here.
4506     MaskVec.push_back(i == Idx ? NumElems : i);
4507   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4508 }
4509
4510 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4511 /// element of the result of the vector shuffle.
4512 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4513                                    unsigned Depth) {
4514   if (Depth == 6)
4515     return SDValue();  // Limit search depth.
4516
4517   SDValue V = SDValue(N, 0);
4518   EVT VT = V.getValueType();
4519   unsigned Opcode = V.getOpcode();
4520
4521   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4522   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4523     Index = SV->getMaskElt(Index);
4524
4525     if (Index < 0)
4526       return DAG.getUNDEF(VT.getVectorElementType());
4527
4528     int NumElems = VT.getVectorNumElements();
4529     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4530     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4531   }
4532
4533   // Recurse into target specific vector shuffles to find scalars.
4534   if (isTargetShuffle(Opcode)) {
4535     int NumElems = VT.getVectorNumElements();
4536     SmallVector<unsigned, 16> ShuffleMask;
4537     SDValue ImmN;
4538
4539     switch(Opcode) {
4540     case X86ISD::SHUFPS:
4541     case X86ISD::SHUFPD:
4542       ImmN = N->getOperand(N->getNumOperands()-1);
4543       DecodeSHUFPSMask(NumElems,
4544                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4545                        ShuffleMask);
4546       break;
4547     case X86ISD::PUNPCKHBW:
4548     case X86ISD::PUNPCKHWD:
4549     case X86ISD::PUNPCKHDQ:
4550     case X86ISD::PUNPCKHQDQ:
4551       DecodePUNPCKHMask(NumElems, ShuffleMask);
4552       break;
4553     case X86ISD::UNPCKHPS:
4554     case X86ISD::UNPCKHPD:
4555     case X86ISD::VUNPCKHPSY:
4556     case X86ISD::VUNPCKHPDY:
4557       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4558       break;
4559     case X86ISD::PUNPCKLBW:
4560     case X86ISD::PUNPCKLWD:
4561     case X86ISD::PUNPCKLDQ:
4562     case X86ISD::PUNPCKLQDQ:
4563       DecodePUNPCKLMask(VT, ShuffleMask);
4564       break;
4565     case X86ISD::UNPCKLPS:
4566     case X86ISD::UNPCKLPD:
4567     case X86ISD::VUNPCKLPSY:
4568     case X86ISD::VUNPCKLPDY:
4569       DecodeUNPCKLPMask(VT, ShuffleMask);
4570       break;
4571     case X86ISD::MOVHLPS:
4572       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4573       break;
4574     case X86ISD::MOVLHPS:
4575       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4576       break;
4577     case X86ISD::PSHUFD:
4578       ImmN = N->getOperand(N->getNumOperands()-1);
4579       DecodePSHUFMask(NumElems,
4580                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4581                       ShuffleMask);
4582       break;
4583     case X86ISD::PSHUFHW:
4584       ImmN = N->getOperand(N->getNumOperands()-1);
4585       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4586                         ShuffleMask);
4587       break;
4588     case X86ISD::PSHUFLW:
4589       ImmN = N->getOperand(N->getNumOperands()-1);
4590       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4591                         ShuffleMask);
4592       break;
4593     case X86ISD::MOVSS:
4594     case X86ISD::MOVSD: {
4595       // The index 0 always comes from the first element of the second source,
4596       // this is why MOVSS and MOVSD are used in the first place. The other
4597       // elements come from the other positions of the first source vector.
4598       unsigned OpNum = (Index == 0) ? 1 : 0;
4599       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4600                                  Depth+1);
4601     }
4602     case X86ISD::VPERMILPS:
4603       ImmN = N->getOperand(N->getNumOperands()-1);
4604       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4605                         ShuffleMask);
4606       break;
4607     case X86ISD::VPERMILPSY:
4608       ImmN = N->getOperand(N->getNumOperands()-1);
4609       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4610                         ShuffleMask);
4611       break;
4612     case X86ISD::VPERMILPD:
4613       ImmN = N->getOperand(N->getNumOperands()-1);
4614       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4615                         ShuffleMask);
4616       break;
4617     case X86ISD::VPERMILPDY:
4618       ImmN = N->getOperand(N->getNumOperands()-1);
4619       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4620                         ShuffleMask);
4621       break;
4622     case X86ISD::VPERM2F128:
4623       ImmN = N->getOperand(N->getNumOperands()-1);
4624       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4625                            ShuffleMask);
4626       break;
4627     case X86ISD::MOVDDUP:
4628     case X86ISD::MOVLHPD:
4629     case X86ISD::MOVLPD:
4630     case X86ISD::MOVLPS:
4631     case X86ISD::MOVSHDUP:
4632     case X86ISD::MOVSLDUP:
4633     case X86ISD::PALIGN:
4634       return SDValue(); // Not yet implemented.
4635     default:
4636       assert(0 && "unknown target shuffle node");
4637       return SDValue();
4638     }
4639
4640     Index = ShuffleMask[Index];
4641     if (Index < 0)
4642       return DAG.getUNDEF(VT.getVectorElementType());
4643
4644     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4645     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4646                                Depth+1);
4647   }
4648
4649   // Actual nodes that may contain scalar elements
4650   if (Opcode == ISD::BITCAST) {
4651     V = V.getOperand(0);
4652     EVT SrcVT = V.getValueType();
4653     unsigned NumElems = VT.getVectorNumElements();
4654
4655     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4656       return SDValue();
4657   }
4658
4659   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4660     return (Index == 0) ? V.getOperand(0)
4661                           : DAG.getUNDEF(VT.getVectorElementType());
4662
4663   if (V.getOpcode() == ISD::BUILD_VECTOR)
4664     return V.getOperand(Index);
4665
4666   return SDValue();
4667 }
4668
4669 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4670 /// shuffle operation which come from a consecutively from a zero. The
4671 /// search can start in two different directions, from left or right.
4672 static
4673 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4674                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4675   int i = 0;
4676
4677   while (i < NumElems) {
4678     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4679     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4680     if (!(Elt.getNode() &&
4681          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4682       break;
4683     ++i;
4684   }
4685
4686   return i;
4687 }
4688
4689 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4690 /// MaskE correspond consecutively to elements from one of the vector operands,
4691 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4692 static
4693 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4694                               int OpIdx, int NumElems, unsigned &OpNum) {
4695   bool SeenV1 = false;
4696   bool SeenV2 = false;
4697
4698   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4699     int Idx = SVOp->getMaskElt(i);
4700     // Ignore undef indicies
4701     if (Idx < 0)
4702       continue;
4703
4704     if (Idx < NumElems)
4705       SeenV1 = true;
4706     else
4707       SeenV2 = true;
4708
4709     // Only accept consecutive elements from the same vector
4710     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4711       return false;
4712   }
4713
4714   OpNum = SeenV1 ? 0 : 1;
4715   return true;
4716 }
4717
4718 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4719 /// logical left shift of a vector.
4720 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4721                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4722   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4723   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4724               false /* check zeros from right */, DAG);
4725   unsigned OpSrc;
4726
4727   if (!NumZeros)
4728     return false;
4729
4730   // Considering the elements in the mask that are not consecutive zeros,
4731   // check if they consecutively come from only one of the source vectors.
4732   //
4733   //               V1 = {X, A, B, C}     0
4734   //                         \  \  \    /
4735   //   vector_shuffle V1, V2 <1, 2, 3, X>
4736   //
4737   if (!isShuffleMaskConsecutive(SVOp,
4738             0,                   // Mask Start Index
4739             NumElems-NumZeros-1, // Mask End Index
4740             NumZeros,            // Where to start looking in the src vector
4741             NumElems,            // Number of elements in vector
4742             OpSrc))              // Which source operand ?
4743     return false;
4744
4745   isLeft = false;
4746   ShAmt = NumZeros;
4747   ShVal = SVOp->getOperand(OpSrc);
4748   return true;
4749 }
4750
4751 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4752 /// logical left shift of a vector.
4753 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4754                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4755   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4756   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4757               true /* check zeros from left */, DAG);
4758   unsigned OpSrc;
4759
4760   if (!NumZeros)
4761     return false;
4762
4763   // Considering the elements in the mask that are not consecutive zeros,
4764   // check if they consecutively come from only one of the source vectors.
4765   //
4766   //                           0    { A, B, X, X } = V2
4767   //                          / \    /  /
4768   //   vector_shuffle V1, V2 <X, X, 4, 5>
4769   //
4770   if (!isShuffleMaskConsecutive(SVOp,
4771             NumZeros,     // Mask Start Index
4772             NumElems-1,   // Mask End Index
4773             0,            // Where to start looking in the src vector
4774             NumElems,     // Number of elements in vector
4775             OpSrc))       // Which source operand ?
4776     return false;
4777
4778   isLeft = true;
4779   ShAmt = NumZeros;
4780   ShVal = SVOp->getOperand(OpSrc);
4781   return true;
4782 }
4783
4784 /// isVectorShift - Returns true if the shuffle can be implemented as a
4785 /// logical left or right shift of a vector.
4786 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4787                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4788   // Although the logic below support any bitwidth size, there are no
4789   // shift instructions which handle more than 128-bit vectors.
4790   if (SVOp->getValueType(0).getSizeInBits() > 128)
4791     return false;
4792
4793   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4794       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4795     return true;
4796
4797   return false;
4798 }
4799
4800 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4801 ///
4802 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4803                                        unsigned NumNonZero, unsigned NumZero,
4804                                        SelectionDAG &DAG,
4805                                        const TargetLowering &TLI) {
4806   if (NumNonZero > 8)
4807     return SDValue();
4808
4809   DebugLoc dl = Op.getDebugLoc();
4810   SDValue V(0, 0);
4811   bool First = true;
4812   for (unsigned i = 0; i < 16; ++i) {
4813     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4814     if (ThisIsNonZero && First) {
4815       if (NumZero)
4816         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4817       else
4818         V = DAG.getUNDEF(MVT::v8i16);
4819       First = false;
4820     }
4821
4822     if ((i & 1) != 0) {
4823       SDValue ThisElt(0, 0), LastElt(0, 0);
4824       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4825       if (LastIsNonZero) {
4826         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4827                               MVT::i16, Op.getOperand(i-1));
4828       }
4829       if (ThisIsNonZero) {
4830         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4831         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4832                               ThisElt, DAG.getConstant(8, MVT::i8));
4833         if (LastIsNonZero)
4834           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4835       } else
4836         ThisElt = LastElt;
4837
4838       if (ThisElt.getNode())
4839         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4840                         DAG.getIntPtrConstant(i/2));
4841     }
4842   }
4843
4844   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4845 }
4846
4847 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4848 ///
4849 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4850                                      unsigned NumNonZero, unsigned NumZero,
4851                                      SelectionDAG &DAG,
4852                                      const TargetLowering &TLI) {
4853   if (NumNonZero > 4)
4854     return SDValue();
4855
4856   DebugLoc dl = Op.getDebugLoc();
4857   SDValue V(0, 0);
4858   bool First = true;
4859   for (unsigned i = 0; i < 8; ++i) {
4860     bool isNonZero = (NonZeros & (1 << i)) != 0;
4861     if (isNonZero) {
4862       if (First) {
4863         if (NumZero)
4864           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4865         else
4866           V = DAG.getUNDEF(MVT::v8i16);
4867         First = false;
4868       }
4869       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4870                       MVT::v8i16, V, Op.getOperand(i),
4871                       DAG.getIntPtrConstant(i));
4872     }
4873   }
4874
4875   return V;
4876 }
4877
4878 /// getVShift - Return a vector logical shift node.
4879 ///
4880 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4881                          unsigned NumBits, SelectionDAG &DAG,
4882                          const TargetLowering &TLI, DebugLoc dl) {
4883   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4884   EVT ShVT = MVT::v2i64;
4885   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4886   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4887   return DAG.getNode(ISD::BITCAST, dl, VT,
4888                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4889                              DAG.getConstant(NumBits,
4890                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4891 }
4892
4893 SDValue
4894 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4895                                           SelectionDAG &DAG) const {
4896
4897   // Check if the scalar load can be widened into a vector load. And if
4898   // the address is "base + cst" see if the cst can be "absorbed" into
4899   // the shuffle mask.
4900   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4901     SDValue Ptr = LD->getBasePtr();
4902     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4903       return SDValue();
4904     EVT PVT = LD->getValueType(0);
4905     if (PVT != MVT::i32 && PVT != MVT::f32)
4906       return SDValue();
4907
4908     int FI = -1;
4909     int64_t Offset = 0;
4910     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4911       FI = FINode->getIndex();
4912       Offset = 0;
4913     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4914                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4915       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4916       Offset = Ptr.getConstantOperandVal(1);
4917       Ptr = Ptr.getOperand(0);
4918     } else {
4919       return SDValue();
4920     }
4921
4922     // FIXME: 256-bit vector instructions don't require a strict alignment,
4923     // improve this code to support it better.
4924     unsigned RequiredAlign = VT.getSizeInBits()/8;
4925     SDValue Chain = LD->getChain();
4926     // Make sure the stack object alignment is at least 16 or 32.
4927     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4928     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4929       if (MFI->isFixedObjectIndex(FI)) {
4930         // Can't change the alignment. FIXME: It's possible to compute
4931         // the exact stack offset and reference FI + adjust offset instead.
4932         // If someone *really* cares about this. That's the way to implement it.
4933         return SDValue();
4934       } else {
4935         MFI->setObjectAlignment(FI, RequiredAlign);
4936       }
4937     }
4938
4939     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4940     // Ptr + (Offset & ~15).
4941     if (Offset < 0)
4942       return SDValue();
4943     if ((Offset % RequiredAlign) & 3)
4944       return SDValue();
4945     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4946     if (StartOffset)
4947       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4948                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4949
4950     int EltNo = (Offset - StartOffset) >> 2;
4951     int NumElems = VT.getVectorNumElements();
4952
4953     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4954     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4955     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4956                              LD->getPointerInfo().getWithOffset(StartOffset),
4957                              false, false, 0);
4958
4959     // Canonicalize it to a v4i32 or v8i32 shuffle.
4960     SmallVector<int, 8> Mask;
4961     for (int i = 0; i < NumElems; ++i)
4962       Mask.push_back(EltNo);
4963
4964     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4965     return DAG.getNode(ISD::BITCAST, dl, NVT,
4966                        DAG.getVectorShuffle(CanonVT, dl, V1,
4967                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4968   }
4969
4970   return SDValue();
4971 }
4972
4973 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4974 /// vector of type 'VT', see if the elements can be replaced by a single large
4975 /// load which has the same value as a build_vector whose operands are 'elts'.
4976 ///
4977 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4978 ///
4979 /// FIXME: we'd also like to handle the case where the last elements are zero
4980 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4981 /// There's even a handy isZeroNode for that purpose.
4982 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4983                                         DebugLoc &DL, SelectionDAG &DAG) {
4984   EVT EltVT = VT.getVectorElementType();
4985   unsigned NumElems = Elts.size();
4986
4987   LoadSDNode *LDBase = NULL;
4988   unsigned LastLoadedElt = -1U;
4989
4990   // For each element in the initializer, see if we've found a load or an undef.
4991   // If we don't find an initial load element, or later load elements are
4992   // non-consecutive, bail out.
4993   for (unsigned i = 0; i < NumElems; ++i) {
4994     SDValue Elt = Elts[i];
4995
4996     if (!Elt.getNode() ||
4997         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4998       return SDValue();
4999     if (!LDBase) {
5000       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5001         return SDValue();
5002       LDBase = cast<LoadSDNode>(Elt.getNode());
5003       LastLoadedElt = i;
5004       continue;
5005     }
5006     if (Elt.getOpcode() == ISD::UNDEF)
5007       continue;
5008
5009     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5010     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5011       return SDValue();
5012     LastLoadedElt = i;
5013   }
5014
5015   // If we have found an entire vector of loads and undefs, then return a large
5016   // load of the entire vector width starting at the base pointer.  If we found
5017   // consecutive loads for the low half, generate a vzext_load node.
5018   if (LastLoadedElt == NumElems - 1) {
5019     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5020       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5021                          LDBase->getPointerInfo(),
5022                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5023     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5024                        LDBase->getPointerInfo(),
5025                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5026                        LDBase->getAlignment());
5027   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5028              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5029     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5030     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5031     SDValue ResNode =
5032         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5033                                 LDBase->getPointerInfo(),
5034                                 LDBase->getAlignment(),
5035                                 false/*isVolatile*/, true/*ReadMem*/,
5036                                 false/*WriteMem*/);
5037     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5038   }
5039   return SDValue();
5040 }
5041
5042 SDValue
5043 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5044   DebugLoc dl = Op.getDebugLoc();
5045
5046   EVT VT = Op.getValueType();
5047   EVT ExtVT = VT.getVectorElementType();
5048   unsigned NumElems = Op.getNumOperands();
5049
5050   // Vectors containing all zeros can be matched by pxor and xorps later
5051   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5052     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5053     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5054     if (Op.getValueType() == MVT::v4i32 ||
5055         Op.getValueType() == MVT::v8i32)
5056       return Op;
5057
5058     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5059   }
5060
5061   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5062   // vectors or broken into v4i32 operations on 256-bit vectors.
5063   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5064     if (Op.getValueType() == MVT::v4i32)
5065       return Op;
5066
5067     return getOnesVector(Op.getValueType(), DAG, dl);
5068   }
5069
5070   unsigned EVTBits = ExtVT.getSizeInBits();
5071
5072   unsigned NumZero  = 0;
5073   unsigned NumNonZero = 0;
5074   unsigned NonZeros = 0;
5075   bool IsAllConstants = true;
5076   SmallSet<SDValue, 8> Values;
5077   for (unsigned i = 0; i < NumElems; ++i) {
5078     SDValue Elt = Op.getOperand(i);
5079     if (Elt.getOpcode() == ISD::UNDEF)
5080       continue;
5081     Values.insert(Elt);
5082     if (Elt.getOpcode() != ISD::Constant &&
5083         Elt.getOpcode() != ISD::ConstantFP)
5084       IsAllConstants = false;
5085     if (X86::isZeroNode(Elt))
5086       NumZero++;
5087     else {
5088       NonZeros |= (1 << i);
5089       NumNonZero++;
5090     }
5091   }
5092
5093   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5094   if (NumNonZero == 0)
5095     return DAG.getUNDEF(VT);
5096
5097   // Special case for single non-zero, non-undef, element.
5098   if (NumNonZero == 1) {
5099     unsigned Idx = CountTrailingZeros_32(NonZeros);
5100     SDValue Item = Op.getOperand(Idx);
5101
5102     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5103     // the value are obviously zero, truncate the value to i32 and do the
5104     // insertion that way.  Only do this if the value is non-constant or if the
5105     // value is a constant being inserted into element 0.  It is cheaper to do
5106     // a constant pool load than it is to do a movd + shuffle.
5107     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5108         (!IsAllConstants || Idx == 0)) {
5109       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5110         // Handle SSE only.
5111         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5112         EVT VecVT = MVT::v4i32;
5113         unsigned VecElts = 4;
5114
5115         // Truncate the value (which may itself be a constant) to i32, and
5116         // convert it to a vector with movd (S2V+shuffle to zero extend).
5117         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5118         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5119         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5120                                            Subtarget->hasXMMInt(), DAG);
5121
5122         // Now we have our 32-bit value zero extended in the low element of
5123         // a vector.  If Idx != 0, swizzle it into place.
5124         if (Idx != 0) {
5125           SmallVector<int, 4> Mask;
5126           Mask.push_back(Idx);
5127           for (unsigned i = 1; i != VecElts; ++i)
5128             Mask.push_back(i);
5129           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5130                                       DAG.getUNDEF(Item.getValueType()),
5131                                       &Mask[0]);
5132         }
5133         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5134       }
5135     }
5136
5137     // If we have a constant or non-constant insertion into the low element of
5138     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5139     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5140     // depending on what the source datatype is.
5141     if (Idx == 0) {
5142       if (NumZero == 0) {
5143         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5144       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5145           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5146         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5147         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5148         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5149                                            DAG);
5150       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5151         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5152         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5153         EVT MiddleVT = MVT::v4i32;
5154         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5155         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5156                                            Subtarget->hasXMMInt(), DAG);
5157         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5158       }
5159     }
5160
5161     // Is it a vector logical left shift?
5162     if (NumElems == 2 && Idx == 1 &&
5163         X86::isZeroNode(Op.getOperand(0)) &&
5164         !X86::isZeroNode(Op.getOperand(1))) {
5165       unsigned NumBits = VT.getSizeInBits();
5166       return getVShift(true, VT,
5167                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5168                                    VT, Op.getOperand(1)),
5169                        NumBits/2, DAG, *this, dl);
5170     }
5171
5172     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5173       return SDValue();
5174
5175     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5176     // is a non-constant being inserted into an element other than the low one,
5177     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5178     // movd/movss) to move this into the low element, then shuffle it into
5179     // place.
5180     if (EVTBits == 32) {
5181       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5182
5183       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5184       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5185                                          Subtarget->hasXMMInt(), DAG);
5186       SmallVector<int, 8> MaskVec;
5187       for (unsigned i = 0; i < NumElems; i++)
5188         MaskVec.push_back(i == Idx ? 0 : 1);
5189       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5190     }
5191   }
5192
5193   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5194   if (Values.size() == 1) {
5195     if (EVTBits == 32) {
5196       // Instead of a shuffle like this:
5197       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5198       // Check if it's possible to issue this instead.
5199       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5200       unsigned Idx = CountTrailingZeros_32(NonZeros);
5201       SDValue Item = Op.getOperand(Idx);
5202       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5203         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5204     }
5205     return SDValue();
5206   }
5207
5208   // A vector full of immediates; various special cases are already
5209   // handled, so this is best done with a single constant-pool load.
5210   if (IsAllConstants)
5211     return SDValue();
5212
5213   // For AVX-length vectors, build the individual 128-bit pieces and use
5214   // shuffles to put them in place.
5215   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5216     SmallVector<SDValue, 32> V;
5217     for (unsigned i = 0; i < NumElems; ++i)
5218       V.push_back(Op.getOperand(i));
5219
5220     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5221
5222     // Build both the lower and upper subvector.
5223     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5224     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5225                                 NumElems/2);
5226
5227     // Recreate the wider vector with the lower and upper part.
5228     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5229                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5230     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5231                               DAG, dl);
5232   }
5233
5234   // Let legalizer expand 2-wide build_vectors.
5235   if (EVTBits == 64) {
5236     if (NumNonZero == 1) {
5237       // One half is zero or undef.
5238       unsigned Idx = CountTrailingZeros_32(NonZeros);
5239       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5240                                  Op.getOperand(Idx));
5241       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5242                                          Subtarget->hasXMMInt(), DAG);
5243     }
5244     return SDValue();
5245   }
5246
5247   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5248   if (EVTBits == 8 && NumElems == 16) {
5249     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5250                                         *this);
5251     if (V.getNode()) return V;
5252   }
5253
5254   if (EVTBits == 16 && NumElems == 8) {
5255     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5256                                       *this);
5257     if (V.getNode()) return V;
5258   }
5259
5260   // If element VT is == 32 bits, turn it into a number of shuffles.
5261   SmallVector<SDValue, 8> V;
5262   V.resize(NumElems);
5263   if (NumElems == 4 && NumZero > 0) {
5264     for (unsigned i = 0; i < 4; ++i) {
5265       bool isZero = !(NonZeros & (1 << i));
5266       if (isZero)
5267         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5268       else
5269         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5270     }
5271
5272     for (unsigned i = 0; i < 2; ++i) {
5273       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5274         default: break;
5275         case 0:
5276           V[i] = V[i*2];  // Must be a zero vector.
5277           break;
5278         case 1:
5279           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5280           break;
5281         case 2:
5282           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5283           break;
5284         case 3:
5285           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5286           break;
5287       }
5288     }
5289
5290     SmallVector<int, 8> MaskVec;
5291     bool Reverse = (NonZeros & 0x3) == 2;
5292     for (unsigned i = 0; i < 2; ++i)
5293       MaskVec.push_back(Reverse ? 1-i : i);
5294     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5295     for (unsigned i = 0; i < 2; ++i)
5296       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5297     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5298   }
5299
5300   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5301     // Check for a build vector of consecutive loads.
5302     for (unsigned i = 0; i < NumElems; ++i)
5303       V[i] = Op.getOperand(i);
5304
5305     // Check for elements which are consecutive loads.
5306     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5307     if (LD.getNode())
5308       return LD;
5309
5310     // For SSE 4.1, use insertps to put the high elements into the low element.
5311     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5312       SDValue Result;
5313       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5314         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5315       else
5316         Result = DAG.getUNDEF(VT);
5317
5318       for (unsigned i = 1; i < NumElems; ++i) {
5319         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5320         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5321                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5322       }
5323       return Result;
5324     }
5325
5326     // Otherwise, expand into a number of unpckl*, start by extending each of
5327     // our (non-undef) elements to the full vector width with the element in the
5328     // bottom slot of the vector (which generates no code for SSE).
5329     for (unsigned i = 0; i < NumElems; ++i) {
5330       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5331         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5332       else
5333         V[i] = DAG.getUNDEF(VT);
5334     }
5335
5336     // Next, we iteratively mix elements, e.g. for v4f32:
5337     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5338     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5339     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5340     unsigned EltStride = NumElems >> 1;
5341     while (EltStride != 0) {
5342       for (unsigned i = 0; i < EltStride; ++i) {
5343         // If V[i+EltStride] is undef and this is the first round of mixing,
5344         // then it is safe to just drop this shuffle: V[i] is already in the
5345         // right place, the one element (since it's the first round) being
5346         // inserted as undef can be dropped.  This isn't safe for successive
5347         // rounds because they will permute elements within both vectors.
5348         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5349             EltStride == NumElems/2)
5350           continue;
5351
5352         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5353       }
5354       EltStride >>= 1;
5355     }
5356     return V[0];
5357   }
5358   return SDValue();
5359 }
5360
5361 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5362 // them in a MMX register.  This is better than doing a stack convert.
5363 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5364   DebugLoc dl = Op.getDebugLoc();
5365   EVT ResVT = Op.getValueType();
5366
5367   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5368          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5369   int Mask[2];
5370   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5371   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5372   InVec = Op.getOperand(1);
5373   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5374     unsigned NumElts = ResVT.getVectorNumElements();
5375     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5376     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5377                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5378   } else {
5379     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5380     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5381     Mask[0] = 0; Mask[1] = 2;
5382     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5383   }
5384   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5385 }
5386
5387 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5388 // to create 256-bit vectors from two other 128-bit ones.
5389 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5390   DebugLoc dl = Op.getDebugLoc();
5391   EVT ResVT = Op.getValueType();
5392
5393   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5394
5395   SDValue V1 = Op.getOperand(0);
5396   SDValue V2 = Op.getOperand(1);
5397   unsigned NumElems = ResVT.getVectorNumElements();
5398
5399   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5400                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5401   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5402                             DAG, dl);
5403 }
5404
5405 SDValue
5406 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5407   EVT ResVT = Op.getValueType();
5408
5409   assert(Op.getNumOperands() == 2);
5410   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5411          "Unsupported CONCAT_VECTORS for value type");
5412
5413   // We support concatenate two MMX registers and place them in a MMX register.
5414   // This is better than doing a stack convert.
5415   if (ResVT.is128BitVector())
5416     return LowerMMXCONCAT_VECTORS(Op, DAG);
5417
5418   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5419   // from two other 128-bit ones.
5420   return LowerAVXCONCAT_VECTORS(Op, DAG);
5421 }
5422
5423 // v8i16 shuffles - Prefer shuffles in the following order:
5424 // 1. [all]   pshuflw, pshufhw, optional move
5425 // 2. [ssse3] 1 x pshufb
5426 // 3. [ssse3] 2 x pshufb + 1 x por
5427 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5428 SDValue
5429 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5430                                             SelectionDAG &DAG) const {
5431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5432   SDValue V1 = SVOp->getOperand(0);
5433   SDValue V2 = SVOp->getOperand(1);
5434   DebugLoc dl = SVOp->getDebugLoc();
5435   SmallVector<int, 8> MaskVals;
5436
5437   // Determine if more than 1 of the words in each of the low and high quadwords
5438   // of the result come from the same quadword of one of the two inputs.  Undef
5439   // mask values count as coming from any quadword, for better codegen.
5440   SmallVector<unsigned, 4> LoQuad(4);
5441   SmallVector<unsigned, 4> HiQuad(4);
5442   BitVector InputQuads(4);
5443   for (unsigned i = 0; i < 8; ++i) {
5444     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5445     int EltIdx = SVOp->getMaskElt(i);
5446     MaskVals.push_back(EltIdx);
5447     if (EltIdx < 0) {
5448       ++Quad[0];
5449       ++Quad[1];
5450       ++Quad[2];
5451       ++Quad[3];
5452       continue;
5453     }
5454     ++Quad[EltIdx / 4];
5455     InputQuads.set(EltIdx / 4);
5456   }
5457
5458   int BestLoQuad = -1;
5459   unsigned MaxQuad = 1;
5460   for (unsigned i = 0; i < 4; ++i) {
5461     if (LoQuad[i] > MaxQuad) {
5462       BestLoQuad = i;
5463       MaxQuad = LoQuad[i];
5464     }
5465   }
5466
5467   int BestHiQuad = -1;
5468   MaxQuad = 1;
5469   for (unsigned i = 0; i < 4; ++i) {
5470     if (HiQuad[i] > MaxQuad) {
5471       BestHiQuad = i;
5472       MaxQuad = HiQuad[i];
5473     }
5474   }
5475
5476   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5477   // of the two input vectors, shuffle them into one input vector so only a
5478   // single pshufb instruction is necessary. If There are more than 2 input
5479   // quads, disable the next transformation since it does not help SSSE3.
5480   bool V1Used = InputQuads[0] || InputQuads[1];
5481   bool V2Used = InputQuads[2] || InputQuads[3];
5482   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5483     if (InputQuads.count() == 2 && V1Used && V2Used) {
5484       BestLoQuad = InputQuads.find_first();
5485       BestHiQuad = InputQuads.find_next(BestLoQuad);
5486     }
5487     if (InputQuads.count() > 2) {
5488       BestLoQuad = -1;
5489       BestHiQuad = -1;
5490     }
5491   }
5492
5493   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5494   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5495   // words from all 4 input quadwords.
5496   SDValue NewV;
5497   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5498     SmallVector<int, 8> MaskV;
5499     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5500     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5501     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5502                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5503                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5504     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5505
5506     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5507     // source words for the shuffle, to aid later transformations.
5508     bool AllWordsInNewV = true;
5509     bool InOrder[2] = { true, true };
5510     for (unsigned i = 0; i != 8; ++i) {
5511       int idx = MaskVals[i];
5512       if (idx != (int)i)
5513         InOrder[i/4] = false;
5514       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5515         continue;
5516       AllWordsInNewV = false;
5517       break;
5518     }
5519
5520     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5521     if (AllWordsInNewV) {
5522       for (int i = 0; i != 8; ++i) {
5523         int idx = MaskVals[i];
5524         if (idx < 0)
5525           continue;
5526         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5527         if ((idx != i) && idx < 4)
5528           pshufhw = false;
5529         if ((idx != i) && idx > 3)
5530           pshuflw = false;
5531       }
5532       V1 = NewV;
5533       V2Used = false;
5534       BestLoQuad = 0;
5535       BestHiQuad = 1;
5536     }
5537
5538     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5539     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5540     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5541       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5542       unsigned TargetMask = 0;
5543       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5544                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5545       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5546                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5547       V1 = NewV.getOperand(0);
5548       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5549     }
5550   }
5551
5552   // If we have SSSE3, and all words of the result are from 1 input vector,
5553   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5554   // is present, fall back to case 4.
5555   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5556     SmallVector<SDValue,16> pshufbMask;
5557
5558     // If we have elements from both input vectors, set the high bit of the
5559     // shuffle mask element to zero out elements that come from V2 in the V1
5560     // mask, and elements that come from V1 in the V2 mask, so that the two
5561     // results can be OR'd together.
5562     bool TwoInputs = V1Used && V2Used;
5563     for (unsigned i = 0; i != 8; ++i) {
5564       int EltIdx = MaskVals[i] * 2;
5565       if (TwoInputs && (EltIdx >= 16)) {
5566         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5567         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5568         continue;
5569       }
5570       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5571       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5572     }
5573     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5574     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5575                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5576                                  MVT::v16i8, &pshufbMask[0], 16));
5577     if (!TwoInputs)
5578       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5579
5580     // Calculate the shuffle mask for the second input, shuffle it, and
5581     // OR it with the first shuffled input.
5582     pshufbMask.clear();
5583     for (unsigned i = 0; i != 8; ++i) {
5584       int EltIdx = MaskVals[i] * 2;
5585       if (EltIdx < 16) {
5586         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5587         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5588         continue;
5589       }
5590       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5591       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5592     }
5593     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5594     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5595                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5596                                  MVT::v16i8, &pshufbMask[0], 16));
5597     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5598     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5599   }
5600
5601   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5602   // and update MaskVals with new element order.
5603   BitVector InOrder(8);
5604   if (BestLoQuad >= 0) {
5605     SmallVector<int, 8> MaskV;
5606     for (int i = 0; i != 4; ++i) {
5607       int idx = MaskVals[i];
5608       if (idx < 0) {
5609         MaskV.push_back(-1);
5610         InOrder.set(i);
5611       } else if ((idx / 4) == BestLoQuad) {
5612         MaskV.push_back(idx & 3);
5613         InOrder.set(i);
5614       } else {
5615         MaskV.push_back(-1);
5616       }
5617     }
5618     for (unsigned i = 4; i != 8; ++i)
5619       MaskV.push_back(i);
5620     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5621                                 &MaskV[0]);
5622
5623     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5624         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5625       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5626                                NewV.getOperand(0),
5627                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5628                                DAG);
5629   }
5630
5631   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5632   // and update MaskVals with the new element order.
5633   if (BestHiQuad >= 0) {
5634     SmallVector<int, 8> MaskV;
5635     for (unsigned i = 0; i != 4; ++i)
5636       MaskV.push_back(i);
5637     for (unsigned i = 4; i != 8; ++i) {
5638       int idx = MaskVals[i];
5639       if (idx < 0) {
5640         MaskV.push_back(-1);
5641         InOrder.set(i);
5642       } else if ((idx / 4) == BestHiQuad) {
5643         MaskV.push_back((idx & 3) + 4);
5644         InOrder.set(i);
5645       } else {
5646         MaskV.push_back(-1);
5647       }
5648     }
5649     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5650                                 &MaskV[0]);
5651
5652     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5653         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5654       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5655                               NewV.getOperand(0),
5656                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5657                               DAG);
5658   }
5659
5660   // In case BestHi & BestLo were both -1, which means each quadword has a word
5661   // from each of the four input quadwords, calculate the InOrder bitvector now
5662   // before falling through to the insert/extract cleanup.
5663   if (BestLoQuad == -1 && BestHiQuad == -1) {
5664     NewV = V1;
5665     for (int i = 0; i != 8; ++i)
5666       if (MaskVals[i] < 0 || MaskVals[i] == i)
5667         InOrder.set(i);
5668   }
5669
5670   // The other elements are put in the right place using pextrw and pinsrw.
5671   for (unsigned i = 0; i != 8; ++i) {
5672     if (InOrder[i])
5673       continue;
5674     int EltIdx = MaskVals[i];
5675     if (EltIdx < 0)
5676       continue;
5677     SDValue ExtOp = (EltIdx < 8)
5678     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5679                   DAG.getIntPtrConstant(EltIdx))
5680     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5681                   DAG.getIntPtrConstant(EltIdx - 8));
5682     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5683                        DAG.getIntPtrConstant(i));
5684   }
5685   return NewV;
5686 }
5687
5688 // v16i8 shuffles - Prefer shuffles in the following order:
5689 // 1. [ssse3] 1 x pshufb
5690 // 2. [ssse3] 2 x pshufb + 1 x por
5691 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5692 static
5693 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5694                                  SelectionDAG &DAG,
5695                                  const X86TargetLowering &TLI) {
5696   SDValue V1 = SVOp->getOperand(0);
5697   SDValue V2 = SVOp->getOperand(1);
5698   DebugLoc dl = SVOp->getDebugLoc();
5699   SmallVector<int, 16> MaskVals;
5700   SVOp->getMask(MaskVals);
5701
5702   // If we have SSSE3, case 1 is generated when all result bytes come from
5703   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5704   // present, fall back to case 3.
5705   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5706   bool V1Only = true;
5707   bool V2Only = true;
5708   for (unsigned i = 0; i < 16; ++i) {
5709     int EltIdx = MaskVals[i];
5710     if (EltIdx < 0)
5711       continue;
5712     if (EltIdx < 16)
5713       V2Only = false;
5714     else
5715       V1Only = false;
5716   }
5717
5718   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5719   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5720     SmallVector<SDValue,16> pshufbMask;
5721
5722     // If all result elements are from one input vector, then only translate
5723     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5724     //
5725     // Otherwise, we have elements from both input vectors, and must zero out
5726     // elements that come from V2 in the first mask, and V1 in the second mask
5727     // so that we can OR them together.
5728     bool TwoInputs = !(V1Only || V2Only);
5729     for (unsigned i = 0; i != 16; ++i) {
5730       int EltIdx = MaskVals[i];
5731       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5732         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5733         continue;
5734       }
5735       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5736     }
5737     // If all the elements are from V2, assign it to V1 and return after
5738     // building the first pshufb.
5739     if (V2Only)
5740       V1 = V2;
5741     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5742                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5743                                  MVT::v16i8, &pshufbMask[0], 16));
5744     if (!TwoInputs)
5745       return V1;
5746
5747     // Calculate the shuffle mask for the second input, shuffle it, and
5748     // OR it with the first shuffled input.
5749     pshufbMask.clear();
5750     for (unsigned i = 0; i != 16; ++i) {
5751       int EltIdx = MaskVals[i];
5752       if (EltIdx < 16) {
5753         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5754         continue;
5755       }
5756       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5757     }
5758     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5759                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5760                                  MVT::v16i8, &pshufbMask[0], 16));
5761     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5762   }
5763
5764   // No SSSE3 - Calculate in place words and then fix all out of place words
5765   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5766   // the 16 different words that comprise the two doublequadword input vectors.
5767   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5768   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5769   SDValue NewV = V2Only ? V2 : V1;
5770   for (int i = 0; i != 8; ++i) {
5771     int Elt0 = MaskVals[i*2];
5772     int Elt1 = MaskVals[i*2+1];
5773
5774     // This word of the result is all undef, skip it.
5775     if (Elt0 < 0 && Elt1 < 0)
5776       continue;
5777
5778     // This word of the result is already in the correct place, skip it.
5779     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5780       continue;
5781     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5782       continue;
5783
5784     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5785     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5786     SDValue InsElt;
5787
5788     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5789     // using a single extract together, load it and store it.
5790     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5791       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5792                            DAG.getIntPtrConstant(Elt1 / 2));
5793       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5794                         DAG.getIntPtrConstant(i));
5795       continue;
5796     }
5797
5798     // If Elt1 is defined, extract it from the appropriate source.  If the
5799     // source byte is not also odd, shift the extracted word left 8 bits
5800     // otherwise clear the bottom 8 bits if we need to do an or.
5801     if (Elt1 >= 0) {
5802       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5803                            DAG.getIntPtrConstant(Elt1 / 2));
5804       if ((Elt1 & 1) == 0)
5805         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5806                              DAG.getConstant(8,
5807                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5808       else if (Elt0 >= 0)
5809         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5810                              DAG.getConstant(0xFF00, MVT::i16));
5811     }
5812     // If Elt0 is defined, extract it from the appropriate source.  If the
5813     // source byte is not also even, shift the extracted word right 8 bits. If
5814     // Elt1 was also defined, OR the extracted values together before
5815     // inserting them in the result.
5816     if (Elt0 >= 0) {
5817       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5818                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5819       if ((Elt0 & 1) != 0)
5820         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5821                               DAG.getConstant(8,
5822                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5823       else if (Elt1 >= 0)
5824         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5825                              DAG.getConstant(0x00FF, MVT::i16));
5826       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5827                          : InsElt0;
5828     }
5829     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5830                        DAG.getIntPtrConstant(i));
5831   }
5832   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5833 }
5834
5835 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5836 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5837 /// done when every pair / quad of shuffle mask elements point to elements in
5838 /// the right sequence. e.g.
5839 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5840 static
5841 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5842                                  SelectionDAG &DAG, DebugLoc dl) {
5843   EVT VT = SVOp->getValueType(0);
5844   SDValue V1 = SVOp->getOperand(0);
5845   SDValue V2 = SVOp->getOperand(1);
5846   unsigned NumElems = VT.getVectorNumElements();
5847   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5848   EVT NewVT;
5849   switch (VT.getSimpleVT().SimpleTy) {
5850   default: assert(false && "Unexpected!");
5851   case MVT::v4f32: NewVT = MVT::v2f64; break;
5852   case MVT::v4i32: NewVT = MVT::v2i64; break;
5853   case MVT::v8i16: NewVT = MVT::v4i32; break;
5854   case MVT::v16i8: NewVT = MVT::v4i32; break;
5855   }
5856
5857   int Scale = NumElems / NewWidth;
5858   SmallVector<int, 8> MaskVec;
5859   for (unsigned i = 0; i < NumElems; i += Scale) {
5860     int StartIdx = -1;
5861     for (int j = 0; j < Scale; ++j) {
5862       int EltIdx = SVOp->getMaskElt(i+j);
5863       if (EltIdx < 0)
5864         continue;
5865       if (StartIdx == -1)
5866         StartIdx = EltIdx - (EltIdx % Scale);
5867       if (EltIdx != StartIdx + j)
5868         return SDValue();
5869     }
5870     if (StartIdx == -1)
5871       MaskVec.push_back(-1);
5872     else
5873       MaskVec.push_back(StartIdx / Scale);
5874   }
5875
5876   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5877   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5878   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5879 }
5880
5881 /// getVZextMovL - Return a zero-extending vector move low node.
5882 ///
5883 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5884                             SDValue SrcOp, SelectionDAG &DAG,
5885                             const X86Subtarget *Subtarget, DebugLoc dl) {
5886   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5887     LoadSDNode *LD = NULL;
5888     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5889       LD = dyn_cast<LoadSDNode>(SrcOp);
5890     if (!LD) {
5891       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5892       // instead.
5893       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5894       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5895           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5896           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5897           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5898         // PR2108
5899         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5900         return DAG.getNode(ISD::BITCAST, dl, VT,
5901                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5902                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5903                                                    OpVT,
5904                                                    SrcOp.getOperand(0)
5905                                                           .getOperand(0))));
5906       }
5907     }
5908   }
5909
5910   return DAG.getNode(ISD::BITCAST, dl, VT,
5911                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5912                                  DAG.getNode(ISD::BITCAST, dl,
5913                                              OpVT, SrcOp)));
5914 }
5915
5916 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5917 /// shuffle node referes to only one lane in the sources.
5918 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5919   EVT VT = SVOp->getValueType(0);
5920   int NumElems = VT.getVectorNumElements();
5921   int HalfSize = NumElems/2;
5922   SmallVector<int, 16> M;
5923   SVOp->getMask(M);
5924   bool MatchA = false, MatchB = false;
5925
5926   for (int l = 0; l < NumElems*2; l += HalfSize) {
5927     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5928       MatchA = true;
5929       break;
5930     }
5931   }
5932
5933   for (int l = 0; l < NumElems*2; l += HalfSize) {
5934     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5935       MatchB = true;
5936       break;
5937     }
5938   }
5939
5940   return MatchA && MatchB;
5941 }
5942
5943 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5944 /// which could not be matched by any known target speficic shuffle
5945 static SDValue
5946 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5947   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5948     // If each half of a vector shuffle node referes to only one lane in the
5949     // source vectors, extract each used 128-bit lane and shuffle them using
5950     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5951     // the work to the legalizer.
5952     DebugLoc dl = SVOp->getDebugLoc();
5953     EVT VT = SVOp->getValueType(0);
5954     int NumElems = VT.getVectorNumElements();
5955     int HalfSize = NumElems/2;
5956
5957     // Extract the reference for each half
5958     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5959     int FstVecOpNum = 0, SndVecOpNum = 0;
5960     for (int i = 0; i < HalfSize; ++i) {
5961       int Elt = SVOp->getMaskElt(i);
5962       if (SVOp->getMaskElt(i) < 0)
5963         continue;
5964       FstVecOpNum = Elt/NumElems;
5965       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5966       break;
5967     }
5968     for (int i = HalfSize; i < NumElems; ++i) {
5969       int Elt = SVOp->getMaskElt(i);
5970       if (SVOp->getMaskElt(i) < 0)
5971         continue;
5972       SndVecOpNum = Elt/NumElems;
5973       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5974       break;
5975     }
5976
5977     // Extract the subvectors
5978     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5979                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5980     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5981                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5982
5983     // Generate 128-bit shuffles
5984     SmallVector<int, 16> MaskV1, MaskV2;
5985     for (int i = 0; i < HalfSize; ++i) {
5986       int Elt = SVOp->getMaskElt(i);
5987       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5988     }
5989     for (int i = HalfSize; i < NumElems; ++i) {
5990       int Elt = SVOp->getMaskElt(i);
5991       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5992     }
5993
5994     EVT NVT = V1.getValueType();
5995     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5996     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5997
5998     // Concatenate the result back
5999     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6000                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6001     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6002                               DAG, dl);
6003   }
6004
6005   return SDValue();
6006 }
6007
6008 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6009 /// 4 elements, and match them with several different shuffle types.
6010 static SDValue
6011 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6012   SDValue V1 = SVOp->getOperand(0);
6013   SDValue V2 = SVOp->getOperand(1);
6014   DebugLoc dl = SVOp->getDebugLoc();
6015   EVT VT = SVOp->getValueType(0);
6016
6017   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6018
6019   SmallVector<std::pair<int, int>, 8> Locs;
6020   Locs.resize(4);
6021   SmallVector<int, 8> Mask1(4U, -1);
6022   SmallVector<int, 8> PermMask;
6023   SVOp->getMask(PermMask);
6024
6025   unsigned NumHi = 0;
6026   unsigned NumLo = 0;
6027   for (unsigned i = 0; i != 4; ++i) {
6028     int Idx = PermMask[i];
6029     if (Idx < 0) {
6030       Locs[i] = std::make_pair(-1, -1);
6031     } else {
6032       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6033       if (Idx < 4) {
6034         Locs[i] = std::make_pair(0, NumLo);
6035         Mask1[NumLo] = Idx;
6036         NumLo++;
6037       } else {
6038         Locs[i] = std::make_pair(1, NumHi);
6039         if (2+NumHi < 4)
6040           Mask1[2+NumHi] = Idx;
6041         NumHi++;
6042       }
6043     }
6044   }
6045
6046   if (NumLo <= 2 && NumHi <= 2) {
6047     // If no more than two elements come from either vector. This can be
6048     // implemented with two shuffles. First shuffle gather the elements.
6049     // The second shuffle, which takes the first shuffle as both of its
6050     // vector operands, put the elements into the right order.
6051     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6052
6053     SmallVector<int, 8> Mask2(4U, -1);
6054
6055     for (unsigned i = 0; i != 4; ++i) {
6056       if (Locs[i].first == -1)
6057         continue;
6058       else {
6059         unsigned Idx = (i < 2) ? 0 : 4;
6060         Idx += Locs[i].first * 2 + Locs[i].second;
6061         Mask2[i] = Idx;
6062       }
6063     }
6064
6065     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6066   } else if (NumLo == 3 || NumHi == 3) {
6067     // Otherwise, we must have three elements from one vector, call it X, and
6068     // one element from the other, call it Y.  First, use a shufps to build an
6069     // intermediate vector with the one element from Y and the element from X
6070     // that will be in the same half in the final destination (the indexes don't
6071     // matter). Then, use a shufps to build the final vector, taking the half
6072     // containing the element from Y from the intermediate, and the other half
6073     // from X.
6074     if (NumHi == 3) {
6075       // Normalize it so the 3 elements come from V1.
6076       CommuteVectorShuffleMask(PermMask, VT);
6077       std::swap(V1, V2);
6078     }
6079
6080     // Find the element from V2.
6081     unsigned HiIndex;
6082     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6083       int Val = PermMask[HiIndex];
6084       if (Val < 0)
6085         continue;
6086       if (Val >= 4)
6087         break;
6088     }
6089
6090     Mask1[0] = PermMask[HiIndex];
6091     Mask1[1] = -1;
6092     Mask1[2] = PermMask[HiIndex^1];
6093     Mask1[3] = -1;
6094     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6095
6096     if (HiIndex >= 2) {
6097       Mask1[0] = PermMask[0];
6098       Mask1[1] = PermMask[1];
6099       Mask1[2] = HiIndex & 1 ? 6 : 4;
6100       Mask1[3] = HiIndex & 1 ? 4 : 6;
6101       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6102     } else {
6103       Mask1[0] = HiIndex & 1 ? 2 : 0;
6104       Mask1[1] = HiIndex & 1 ? 0 : 2;
6105       Mask1[2] = PermMask[2];
6106       Mask1[3] = PermMask[3];
6107       if (Mask1[2] >= 0)
6108         Mask1[2] += 4;
6109       if (Mask1[3] >= 0)
6110         Mask1[3] += 4;
6111       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6112     }
6113   }
6114
6115   // Break it into (shuffle shuffle_hi, shuffle_lo).
6116   Locs.clear();
6117   Locs.resize(4);
6118   SmallVector<int,8> LoMask(4U, -1);
6119   SmallVector<int,8> HiMask(4U, -1);
6120
6121   SmallVector<int,8> *MaskPtr = &LoMask;
6122   unsigned MaskIdx = 0;
6123   unsigned LoIdx = 0;
6124   unsigned HiIdx = 2;
6125   for (unsigned i = 0; i != 4; ++i) {
6126     if (i == 2) {
6127       MaskPtr = &HiMask;
6128       MaskIdx = 1;
6129       LoIdx = 0;
6130       HiIdx = 2;
6131     }
6132     int Idx = PermMask[i];
6133     if (Idx < 0) {
6134       Locs[i] = std::make_pair(-1, -1);
6135     } else if (Idx < 4) {
6136       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6137       (*MaskPtr)[LoIdx] = Idx;
6138       LoIdx++;
6139     } else {
6140       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6141       (*MaskPtr)[HiIdx] = Idx;
6142       HiIdx++;
6143     }
6144   }
6145
6146   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6147   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6148   SmallVector<int, 8> MaskOps;
6149   for (unsigned i = 0; i != 4; ++i) {
6150     if (Locs[i].first == -1) {
6151       MaskOps.push_back(-1);
6152     } else {
6153       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6154       MaskOps.push_back(Idx);
6155     }
6156   }
6157   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6158 }
6159
6160 static bool MayFoldVectorLoad(SDValue V) {
6161   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6162     V = V.getOperand(0);
6163   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6164     V = V.getOperand(0);
6165   if (MayFoldLoad(V))
6166     return true;
6167   return false;
6168 }
6169
6170 // FIXME: the version above should always be used. Since there's
6171 // a bug where several vector shuffles can't be folded because the
6172 // DAG is not updated during lowering and a node claims to have two
6173 // uses while it only has one, use this version, and let isel match
6174 // another instruction if the load really happens to have more than
6175 // one use. Remove this version after this bug get fixed.
6176 // rdar://8434668, PR8156
6177 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6178   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6179     V = V.getOperand(0);
6180   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6181     V = V.getOperand(0);
6182   if (ISD::isNormalLoad(V.getNode()))
6183     return true;
6184   return false;
6185 }
6186
6187 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6188 /// a vector extract, and if both can be later optimized into a single load.
6189 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6190 /// here because otherwise a target specific shuffle node is going to be
6191 /// emitted for this shuffle, and the optimization not done.
6192 /// FIXME: This is probably not the best approach, but fix the problem
6193 /// until the right path is decided.
6194 static
6195 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6196                                          const TargetLowering &TLI) {
6197   EVT VT = V.getValueType();
6198   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6199
6200   // Be sure that the vector shuffle is present in a pattern like this:
6201   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6202   if (!V.hasOneUse())
6203     return false;
6204
6205   SDNode *N = *V.getNode()->use_begin();
6206   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6207     return false;
6208
6209   SDValue EltNo = N->getOperand(1);
6210   if (!isa<ConstantSDNode>(EltNo))
6211     return false;
6212
6213   // If the bit convert changed the number of elements, it is unsafe
6214   // to examine the mask.
6215   bool HasShuffleIntoBitcast = false;
6216   if (V.getOpcode() == ISD::BITCAST) {
6217     EVT SrcVT = V.getOperand(0).getValueType();
6218     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6219       return false;
6220     V = V.getOperand(0);
6221     HasShuffleIntoBitcast = true;
6222   }
6223
6224   // Select the input vector, guarding against out of range extract vector.
6225   unsigned NumElems = VT.getVectorNumElements();
6226   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6227   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6228   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6229
6230   // Skip one more bit_convert if necessary
6231   if (V.getOpcode() == ISD::BITCAST)
6232     V = V.getOperand(0);
6233
6234   if (ISD::isNormalLoad(V.getNode())) {
6235     // Is the original load suitable?
6236     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6237
6238     // FIXME: avoid the multi-use bug that is preventing lots of
6239     // of foldings to be detected, this is still wrong of course, but
6240     // give the temporary desired behavior, and if it happens that
6241     // the load has real more uses, during isel it will not fold, and
6242     // will generate poor code.
6243     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6244       return false;
6245
6246     if (!HasShuffleIntoBitcast)
6247       return true;
6248
6249     // If there's a bitcast before the shuffle, check if the load type and
6250     // alignment is valid.
6251     unsigned Align = LN0->getAlignment();
6252     unsigned NewAlign =
6253       TLI.getTargetData()->getABITypeAlignment(
6254                                     VT.getTypeForEVT(*DAG.getContext()));
6255
6256     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6257       return false;
6258   }
6259
6260   return true;
6261 }
6262
6263 static
6264 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6265   EVT VT = Op.getValueType();
6266
6267   // Canonizalize to v2f64.
6268   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6269   return DAG.getNode(ISD::BITCAST, dl, VT,
6270                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6271                                           V1, DAG));
6272 }
6273
6274 static
6275 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6276                         bool HasXMMInt) {
6277   SDValue V1 = Op.getOperand(0);
6278   SDValue V2 = Op.getOperand(1);
6279   EVT VT = Op.getValueType();
6280
6281   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6282
6283   if (HasXMMInt && VT == MVT::v2f64)
6284     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6285
6286   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6287   return DAG.getNode(ISD::BITCAST, dl, VT,
6288                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6289                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6290                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6291 }
6292
6293 static
6294 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6295   SDValue V1 = Op.getOperand(0);
6296   SDValue V2 = Op.getOperand(1);
6297   EVT VT = Op.getValueType();
6298
6299   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6300          "unsupported shuffle type");
6301
6302   if (V2.getOpcode() == ISD::UNDEF)
6303     V2 = V1;
6304
6305   // v4i32 or v4f32
6306   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6307 }
6308
6309 static inline unsigned getSHUFPOpcode(EVT VT) {
6310   switch(VT.getSimpleVT().SimpleTy) {
6311   case MVT::v8i32: // Use fp unit for int unpack.
6312   case MVT::v8f32:
6313   case MVT::v4i32: // Use fp unit for int unpack.
6314   case MVT::v4f32: return X86ISD::SHUFPS;
6315   case MVT::v4i64: // Use fp unit for int unpack.
6316   case MVT::v4f64:
6317   case MVT::v2i64: // Use fp unit for int unpack.
6318   case MVT::v2f64: return X86ISD::SHUFPD;
6319   default:
6320     llvm_unreachable("Unknown type for shufp*");
6321   }
6322   return 0;
6323 }
6324
6325 static
6326 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6327   SDValue V1 = Op.getOperand(0);
6328   SDValue V2 = Op.getOperand(1);
6329   EVT VT = Op.getValueType();
6330   unsigned NumElems = VT.getVectorNumElements();
6331
6332   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6333   // operand of these instructions is only memory, so check if there's a
6334   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6335   // same masks.
6336   bool CanFoldLoad = false;
6337
6338   // Trivial case, when V2 comes from a load.
6339   if (MayFoldVectorLoad(V2))
6340     CanFoldLoad = true;
6341
6342   // When V1 is a load, it can be folded later into a store in isel, example:
6343   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6344   //    turns into:
6345   //  (MOVLPSmr addr:$src1, VR128:$src2)
6346   // So, recognize this potential and also use MOVLPS or MOVLPD
6347   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6348     CanFoldLoad = true;
6349
6350   // Both of them can't be memory operations though.
6351   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6352     CanFoldLoad = false;
6353
6354   if (CanFoldLoad) {
6355     if (HasXMMInt && NumElems == 2)
6356       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6357
6358     if (NumElems == 4)
6359       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6360   }
6361
6362   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6363   // movl and movlp will both match v2i64, but v2i64 is never matched by
6364   // movl earlier because we make it strict to avoid messing with the movlp load
6365   // folding logic (see the code above getMOVLP call). Match it here then,
6366   // this is horrible, but will stay like this until we move all shuffle
6367   // matching to x86 specific nodes. Note that for the 1st condition all
6368   // types are matched with movsd.
6369   if (HasXMMInt) {
6370     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6371     // as to remove this logic from here, as much as possible
6372     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6373       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6374     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6375   }
6376
6377   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6378
6379   // Invert the operand order and use SHUFPS to match it.
6380   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6381                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6382 }
6383
6384 static inline unsigned getUNPCKLOpcode(EVT VT) {
6385   switch(VT.getSimpleVT().SimpleTy) {
6386   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6387   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6388   case MVT::v4f32: return X86ISD::UNPCKLPS;
6389   case MVT::v2f64: return X86ISD::UNPCKLPD;
6390   case MVT::v8i32: // Use fp unit for int unpack.
6391   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6392   case MVT::v4i64: // Use fp unit for int unpack.
6393   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6394   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6395   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6396   default:
6397     llvm_unreachable("Unknown type for unpckl");
6398   }
6399   return 0;
6400 }
6401
6402 static inline unsigned getUNPCKHOpcode(EVT VT) {
6403   switch(VT.getSimpleVT().SimpleTy) {
6404   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6405   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6406   case MVT::v4f32: return X86ISD::UNPCKHPS;
6407   case MVT::v2f64: return X86ISD::UNPCKHPD;
6408   case MVT::v8i32: // Use fp unit for int unpack.
6409   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6410   case MVT::v4i64: // Use fp unit for int unpack.
6411   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6412   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6413   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6414   default:
6415     llvm_unreachable("Unknown type for unpckh");
6416   }
6417   return 0;
6418 }
6419
6420 static inline unsigned getVPERMILOpcode(EVT VT) {
6421   switch(VT.getSimpleVT().SimpleTy) {
6422   case MVT::v4i32:
6423   case MVT::v4f32: return X86ISD::VPERMILPS;
6424   case MVT::v2i64:
6425   case MVT::v2f64: return X86ISD::VPERMILPD;
6426   case MVT::v8i32:
6427   case MVT::v8f32: return X86ISD::VPERMILPSY;
6428   case MVT::v4i64:
6429   case MVT::v4f64: return X86ISD::VPERMILPDY;
6430   default:
6431     llvm_unreachable("Unknown type for vpermil");
6432   }
6433   return 0;
6434 }
6435
6436 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6437 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6438 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6439 static bool isVectorBroadcast(SDValue &Op) {
6440   EVT VT = Op.getValueType();
6441   bool Is256 = VT.getSizeInBits() == 256;
6442
6443   assert((VT.getSizeInBits() == 128 || Is256) &&
6444          "Unsupported type for vbroadcast node");
6445
6446   SDValue V = Op;
6447   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6448     V = V.getOperand(0);
6449
6450   if (Is256 && !(V.hasOneUse() &&
6451                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6452                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6453     return false;
6454
6455   if (Is256)
6456     V = V.getOperand(1);
6457
6458   if (!V.hasOneUse())
6459     return false;
6460
6461   // Check the source scalar_to_vector type. 256-bit broadcasts are
6462   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6463   // for 32-bit scalars.
6464   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6465     return false;
6466
6467   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6468   if (ScalarSize != 32 && ScalarSize != 64)
6469     return false;
6470   if (!Is256 && ScalarSize == 64)
6471     return false;
6472
6473   V = V.getOperand(0);
6474   if (!MayFoldLoad(V))
6475     return false;
6476
6477   // Return the load node
6478   Op = V;
6479   return true;
6480 }
6481
6482 static
6483 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6484                                const TargetLowering &TLI,
6485                                const X86Subtarget *Subtarget) {
6486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6487   EVT VT = Op.getValueType();
6488   DebugLoc dl = Op.getDebugLoc();
6489   SDValue V1 = Op.getOperand(0);
6490   SDValue V2 = Op.getOperand(1);
6491
6492   if (isZeroShuffle(SVOp))
6493     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6494
6495   // Handle splat operations
6496   if (SVOp->isSplat()) {
6497     unsigned NumElem = VT.getVectorNumElements();
6498     int Size = VT.getSizeInBits();
6499     // Special case, this is the only place now where it's allowed to return
6500     // a vector_shuffle operation without using a target specific node, because
6501     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6502     // this be moved to DAGCombine instead?
6503     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6504       return Op;
6505
6506     // Use vbroadcast whenever the splat comes from a foldable load
6507     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6508       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6509
6510     // Handle splats by matching through known shuffle masks
6511     if ((Size == 128 && NumElem <= 4) ||
6512         (Size == 256 && NumElem < 8))
6513       return SDValue();
6514
6515     // All remaning splats are promoted to target supported vector shuffles.
6516     return PromoteSplat(SVOp, DAG);
6517   }
6518
6519   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6520   // do it!
6521   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6522     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6523     if (NewOp.getNode())
6524       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6525   } else if ((VT == MVT::v4i32 ||
6526              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6527     // FIXME: Figure out a cleaner way to do this.
6528     // Try to make use of movq to zero out the top part.
6529     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6530       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6531       if (NewOp.getNode()) {
6532         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6533           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6534                               DAG, Subtarget, dl);
6535       }
6536     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6537       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6538       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6539         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6540                             DAG, Subtarget, dl);
6541     }
6542   }
6543   return SDValue();
6544 }
6545
6546 SDValue
6547 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6548   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6549   SDValue V1 = Op.getOperand(0);
6550   SDValue V2 = Op.getOperand(1);
6551   EVT VT = Op.getValueType();
6552   DebugLoc dl = Op.getDebugLoc();
6553   unsigned NumElems = VT.getVectorNumElements();
6554   bool isMMX = VT.getSizeInBits() == 64;
6555   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6556   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6557   bool V1IsSplat = false;
6558   bool V2IsSplat = false;
6559   bool HasXMMInt = Subtarget->hasXMMInt();
6560   MachineFunction &MF = DAG.getMachineFunction();
6561   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6562
6563   // Shuffle operations on MMX not supported.
6564   if (isMMX)
6565     return Op;
6566
6567   // Vector shuffle lowering takes 3 steps:
6568   //
6569   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6570   //    narrowing and commutation of operands should be handled.
6571   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6572   //    shuffle nodes.
6573   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6574   //    so the shuffle can be broken into other shuffles and the legalizer can
6575   //    try the lowering again.
6576   //
6577   // The general ideia is that no vector_shuffle operation should be left to
6578   // be matched during isel, all of them must be converted to a target specific
6579   // node here.
6580
6581   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6582   // narrowing and commutation of operands should be handled. The actual code
6583   // doesn't include all of those, work in progress...
6584   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6585   if (NewOp.getNode())
6586     return NewOp;
6587
6588   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6589   // unpckh_undef). Only use pshufd if speed is more important than size.
6590   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6591     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6592   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6593     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6594
6595   if (X86::isMOVDDUPMask(SVOp) &&
6596       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6597       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6598     return getMOVDDup(Op, dl, V1, DAG);
6599
6600   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6601     return getMOVHighToLow(Op, dl, DAG);
6602
6603   // Use to match splats
6604   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6605       (VT == MVT::v2f64 || VT == MVT::v2i64))
6606     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6607
6608   if (X86::isPSHUFDMask(SVOp)) {
6609     // The actual implementation will match the mask in the if above and then
6610     // during isel it can match several different instructions, not only pshufd
6611     // as its name says, sad but true, emulate the behavior for now...
6612     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6613         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6614
6615     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6616
6617     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6618       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6619
6620     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6621                                 TargetMask, DAG);
6622   }
6623
6624   // Check if this can be converted into a logical shift.
6625   bool isLeft = false;
6626   unsigned ShAmt = 0;
6627   SDValue ShVal;
6628   bool isShift = getSubtarget()->hasXMMInt() &&
6629                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6630   if (isShift && ShVal.hasOneUse()) {
6631     // If the shifted value has multiple uses, it may be cheaper to use
6632     // v_set0 + movlhps or movhlps, etc.
6633     EVT EltVT = VT.getVectorElementType();
6634     ShAmt *= EltVT.getSizeInBits();
6635     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6636   }
6637
6638   if (X86::isMOVLMask(SVOp)) {
6639     if (V1IsUndef)
6640       return V2;
6641     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6642       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6643     if (!X86::isMOVLPMask(SVOp)) {
6644       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6645         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6646
6647       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6648         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6649     }
6650   }
6651
6652   // FIXME: fold these into legal mask.
6653   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6654     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6655
6656   if (X86::isMOVHLPSMask(SVOp))
6657     return getMOVHighToLow(Op, dl, DAG);
6658
6659   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6660     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6661
6662   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6663     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6664
6665   if (X86::isMOVLPMask(SVOp))
6666     return getMOVLP(Op, dl, DAG, HasXMMInt);
6667
6668   if (ShouldXformToMOVHLPS(SVOp) ||
6669       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6670     return CommuteVectorShuffle(SVOp, DAG);
6671
6672   if (isShift) {
6673     // No better options. Use a vshl / vsrl.
6674     EVT EltVT = VT.getVectorElementType();
6675     ShAmt *= EltVT.getSizeInBits();
6676     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6677   }
6678
6679   bool Commuted = false;
6680   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6681   // 1,1,1,1 -> v8i16 though.
6682   V1IsSplat = isSplatVector(V1.getNode());
6683   V2IsSplat = isSplatVector(V2.getNode());
6684
6685   // Canonicalize the splat or undef, if present, to be on the RHS.
6686   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6687     Op = CommuteVectorShuffle(SVOp, DAG);
6688     SVOp = cast<ShuffleVectorSDNode>(Op);
6689     V1 = SVOp->getOperand(0);
6690     V2 = SVOp->getOperand(1);
6691     std::swap(V1IsSplat, V2IsSplat);
6692     std::swap(V1IsUndef, V2IsUndef);
6693     Commuted = true;
6694   }
6695
6696   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6697     // Shuffling low element of v1 into undef, just return v1.
6698     if (V2IsUndef)
6699       return V1;
6700     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6701     // the instruction selector will not match, so get a canonical MOVL with
6702     // swapped operands to undo the commute.
6703     return getMOVL(DAG, dl, VT, V2, V1);
6704   }
6705
6706   if (X86::isUNPCKLMask(SVOp))
6707     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6708
6709   if (X86::isUNPCKHMask(SVOp))
6710     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6711
6712   if (V2IsSplat) {
6713     // Normalize mask so all entries that point to V2 points to its first
6714     // element then try to match unpck{h|l} again. If match, return a
6715     // new vector_shuffle with the corrected mask.
6716     SDValue NewMask = NormalizeMask(SVOp, DAG);
6717     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6718     if (NSVOp != SVOp) {
6719       if (X86::isUNPCKLMask(NSVOp, true)) {
6720         return NewMask;
6721       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6722         return NewMask;
6723       }
6724     }
6725   }
6726
6727   if (Commuted) {
6728     // Commute is back and try unpck* again.
6729     // FIXME: this seems wrong.
6730     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6731     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6732
6733     if (X86::isUNPCKLMask(NewSVOp))
6734       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6735
6736     if (X86::isUNPCKHMask(NewSVOp))
6737       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6738   }
6739
6740   // Normalize the node to match x86 shuffle ops if needed
6741   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6742     return CommuteVectorShuffle(SVOp, DAG);
6743
6744   // The checks below are all present in isShuffleMaskLegal, but they are
6745   // inlined here right now to enable us to directly emit target specific
6746   // nodes, and remove one by one until they don't return Op anymore.
6747   SmallVector<int, 16> M;
6748   SVOp->getMask(M);
6749
6750   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6751     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6752                                 X86::getShufflePALIGNRImmediate(SVOp),
6753                                 DAG);
6754
6755   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6756       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6757     if (VT == MVT::v2f64)
6758       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6759     if (VT == MVT::v2i64)
6760       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6761   }
6762
6763   if (isPSHUFHWMask(M, VT))
6764     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6765                                 X86::getShufflePSHUFHWImmediate(SVOp),
6766                                 DAG);
6767
6768   if (isPSHUFLWMask(M, VT))
6769     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6770                                 X86::getShufflePSHUFLWImmediate(SVOp),
6771                                 DAG);
6772
6773   if (isSHUFPMask(M, VT))
6774     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6775                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6776
6777   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6778     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6779   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6780     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6781
6782   //===--------------------------------------------------------------------===//
6783   // Generate target specific nodes for 128 or 256-bit shuffles only
6784   // supported in the AVX instruction set.
6785   //
6786
6787   // Handle VMOVDDUPY permutations
6788   if (isMOVDDUPYMask(SVOp, Subtarget))
6789     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6790
6791   // Handle VPERMILPS* permutations
6792   if (isVPERMILPSMask(M, VT, Subtarget))
6793     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6794                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6795
6796   // Handle VPERMILPD* permutations
6797   if (isVPERMILPDMask(M, VT, Subtarget))
6798     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6799                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6800
6801   // Handle VPERM2F128 permutations
6802   if (isVPERM2F128Mask(M, VT, Subtarget))
6803     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6804                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6805
6806   // Handle VSHUFPSY permutations
6807   if (isVSHUFPSYMask(M, VT, Subtarget))
6808     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6809                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6810
6811   // Handle VSHUFPDY permutations
6812   if (isVSHUFPDYMask(M, VT, Subtarget))
6813     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6814                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6815
6816   //===--------------------------------------------------------------------===//
6817   // Since no target specific shuffle was selected for this generic one,
6818   // lower it into other known shuffles. FIXME: this isn't true yet, but
6819   // this is the plan.
6820   //
6821
6822   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6823   if (VT == MVT::v8i16) {
6824     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6825     if (NewOp.getNode())
6826       return NewOp;
6827   }
6828
6829   if (VT == MVT::v16i8) {
6830     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6831     if (NewOp.getNode())
6832       return NewOp;
6833   }
6834
6835   // Handle all 128-bit wide vectors with 4 elements, and match them with
6836   // several different shuffle types.
6837   if (NumElems == 4 && VT.getSizeInBits() == 128)
6838     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6839
6840   // Handle general 256-bit shuffles
6841   if (VT.is256BitVector())
6842     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6843
6844   return SDValue();
6845 }
6846
6847 SDValue
6848 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6849                                                 SelectionDAG &DAG) const {
6850   EVT VT = Op.getValueType();
6851   DebugLoc dl = Op.getDebugLoc();
6852
6853   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6854     return SDValue();
6855
6856   if (VT.getSizeInBits() == 8) {
6857     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6858                                     Op.getOperand(0), Op.getOperand(1));
6859     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6860                                     DAG.getValueType(VT));
6861     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6862   } else if (VT.getSizeInBits() == 16) {
6863     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6864     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6865     if (Idx == 0)
6866       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6867                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6868                                      DAG.getNode(ISD::BITCAST, dl,
6869                                                  MVT::v4i32,
6870                                                  Op.getOperand(0)),
6871                                      Op.getOperand(1)));
6872     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6873                                     Op.getOperand(0), Op.getOperand(1));
6874     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6875                                     DAG.getValueType(VT));
6876     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6877   } else if (VT == MVT::f32) {
6878     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6879     // the result back to FR32 register. It's only worth matching if the
6880     // result has a single use which is a store or a bitcast to i32.  And in
6881     // the case of a store, it's not worth it if the index is a constant 0,
6882     // because a MOVSSmr can be used instead, which is smaller and faster.
6883     if (!Op.hasOneUse())
6884       return SDValue();
6885     SDNode *User = *Op.getNode()->use_begin();
6886     if ((User->getOpcode() != ISD::STORE ||
6887          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6888           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6889         (User->getOpcode() != ISD::BITCAST ||
6890          User->getValueType(0) != MVT::i32))
6891       return SDValue();
6892     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6893                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6894                                               Op.getOperand(0)),
6895                                               Op.getOperand(1));
6896     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6897   } else if (VT == MVT::i32) {
6898     // ExtractPS works with constant index.
6899     if (isa<ConstantSDNode>(Op.getOperand(1)))
6900       return Op;
6901   }
6902   return SDValue();
6903 }
6904
6905
6906 SDValue
6907 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6908                                            SelectionDAG &DAG) const {
6909   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6910     return SDValue();
6911
6912   SDValue Vec = Op.getOperand(0);
6913   EVT VecVT = Vec.getValueType();
6914
6915   // If this is a 256-bit vector result, first extract the 128-bit vector and
6916   // then extract the element from the 128-bit vector.
6917   if (VecVT.getSizeInBits() == 256) {
6918     DebugLoc dl = Op.getNode()->getDebugLoc();
6919     unsigned NumElems = VecVT.getVectorNumElements();
6920     SDValue Idx = Op.getOperand(1);
6921     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6922
6923     // Get the 128-bit vector.
6924     bool Upper = IdxVal >= NumElems/2;
6925     Vec = Extract128BitVector(Vec,
6926                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6927
6928     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6929                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6930   }
6931
6932   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6933
6934   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6935     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6936     if (Res.getNode())
6937       return Res;
6938   }
6939
6940   EVT VT = Op.getValueType();
6941   DebugLoc dl = Op.getDebugLoc();
6942   // TODO: handle v16i8.
6943   if (VT.getSizeInBits() == 16) {
6944     SDValue Vec = Op.getOperand(0);
6945     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6946     if (Idx == 0)
6947       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6948                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6949                                      DAG.getNode(ISD::BITCAST, dl,
6950                                                  MVT::v4i32, Vec),
6951                                      Op.getOperand(1)));
6952     // Transform it so it match pextrw which produces a 32-bit result.
6953     EVT EltVT = MVT::i32;
6954     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6955                                     Op.getOperand(0), Op.getOperand(1));
6956     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6957                                     DAG.getValueType(VT));
6958     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6959   } else if (VT.getSizeInBits() == 32) {
6960     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6961     if (Idx == 0)
6962       return Op;
6963
6964     // SHUFPS the element to the lowest double word, then movss.
6965     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6966     EVT VVT = Op.getOperand(0).getValueType();
6967     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6968                                        DAG.getUNDEF(VVT), Mask);
6969     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6970                        DAG.getIntPtrConstant(0));
6971   } else if (VT.getSizeInBits() == 64) {
6972     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6973     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6974     //        to match extract_elt for f64.
6975     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6976     if (Idx == 0)
6977       return Op;
6978
6979     // UNPCKHPD the element to the lowest double word, then movsd.
6980     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6981     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6982     int Mask[2] = { 1, -1 };
6983     EVT VVT = Op.getOperand(0).getValueType();
6984     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6985                                        DAG.getUNDEF(VVT), Mask);
6986     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6987                        DAG.getIntPtrConstant(0));
6988   }
6989
6990   return SDValue();
6991 }
6992
6993 SDValue
6994 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6995                                                SelectionDAG &DAG) const {
6996   EVT VT = Op.getValueType();
6997   EVT EltVT = VT.getVectorElementType();
6998   DebugLoc dl = Op.getDebugLoc();
6999
7000   SDValue N0 = Op.getOperand(0);
7001   SDValue N1 = Op.getOperand(1);
7002   SDValue N2 = Op.getOperand(2);
7003
7004   if (VT.getSizeInBits() == 256)
7005     return SDValue();
7006
7007   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7008       isa<ConstantSDNode>(N2)) {
7009     unsigned Opc;
7010     if (VT == MVT::v8i16)
7011       Opc = X86ISD::PINSRW;
7012     else if (VT == MVT::v16i8)
7013       Opc = X86ISD::PINSRB;
7014     else
7015       Opc = X86ISD::PINSRB;
7016
7017     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7018     // argument.
7019     if (N1.getValueType() != MVT::i32)
7020       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7021     if (N2.getValueType() != MVT::i32)
7022       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7023     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7024   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7025     // Bits [7:6] of the constant are the source select.  This will always be
7026     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7027     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7028     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7029     // Bits [5:4] of the constant are the destination select.  This is the
7030     //  value of the incoming immediate.
7031     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7032     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7033     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7034     // Create this as a scalar to vector..
7035     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7036     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7037   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7038     // PINSR* works with constant index.
7039     return Op;
7040   }
7041   return SDValue();
7042 }
7043
7044 SDValue
7045 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7046   EVT VT = Op.getValueType();
7047   EVT EltVT = VT.getVectorElementType();
7048
7049   DebugLoc dl = Op.getDebugLoc();
7050   SDValue N0 = Op.getOperand(0);
7051   SDValue N1 = Op.getOperand(1);
7052   SDValue N2 = Op.getOperand(2);
7053
7054   // If this is a 256-bit vector result, first extract the 128-bit vector,
7055   // insert the element into the extracted half and then place it back.
7056   if (VT.getSizeInBits() == 256) {
7057     if (!isa<ConstantSDNode>(N2))
7058       return SDValue();
7059
7060     // Get the desired 128-bit vector half.
7061     unsigned NumElems = VT.getVectorNumElements();
7062     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7063     bool Upper = IdxVal >= NumElems/2;
7064     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7065     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7066
7067     // Insert the element into the desired half.
7068     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7069                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7070
7071     // Insert the changed part back to the 256-bit vector
7072     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7073   }
7074
7075   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7076     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7077
7078   if (EltVT == MVT::i8)
7079     return SDValue();
7080
7081   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7082     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7083     // as its second argument.
7084     if (N1.getValueType() != MVT::i32)
7085       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7086     if (N2.getValueType() != MVT::i32)
7087       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7088     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7089   }
7090   return SDValue();
7091 }
7092
7093 SDValue
7094 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7095   LLVMContext *Context = DAG.getContext();
7096   DebugLoc dl = Op.getDebugLoc();
7097   EVT OpVT = Op.getValueType();
7098
7099   // If this is a 256-bit vector result, first insert into a 128-bit
7100   // vector and then insert into the 256-bit vector.
7101   if (OpVT.getSizeInBits() > 128) {
7102     // Insert into a 128-bit vector.
7103     EVT VT128 = EVT::getVectorVT(*Context,
7104                                  OpVT.getVectorElementType(),
7105                                  OpVT.getVectorNumElements() / 2);
7106
7107     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7108
7109     // Insert the 128-bit vector.
7110     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7111                               DAG.getConstant(0, MVT::i32),
7112                               DAG, dl);
7113   }
7114
7115   if (Op.getValueType() == MVT::v1i64 &&
7116       Op.getOperand(0).getValueType() == MVT::i64)
7117     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7118
7119   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7120   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7121          "Expected an SSE type!");
7122   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7123                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7124 }
7125
7126 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7127 // a simple subregister reference or explicit instructions to grab
7128 // upper bits of a vector.
7129 SDValue
7130 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7131   if (Subtarget->hasAVX()) {
7132     DebugLoc dl = Op.getNode()->getDebugLoc();
7133     SDValue Vec = Op.getNode()->getOperand(0);
7134     SDValue Idx = Op.getNode()->getOperand(1);
7135
7136     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7137         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7138         return Extract128BitVector(Vec, Idx, DAG, dl);
7139     }
7140   }
7141   return SDValue();
7142 }
7143
7144 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7145 // simple superregister reference or explicit instructions to insert
7146 // the upper bits of a vector.
7147 SDValue
7148 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7149   if (Subtarget->hasAVX()) {
7150     DebugLoc dl = Op.getNode()->getDebugLoc();
7151     SDValue Vec = Op.getNode()->getOperand(0);
7152     SDValue SubVec = Op.getNode()->getOperand(1);
7153     SDValue Idx = Op.getNode()->getOperand(2);
7154
7155     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7156         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7157       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7158     }
7159   }
7160   return SDValue();
7161 }
7162
7163 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7164 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7165 // one of the above mentioned nodes. It has to be wrapped because otherwise
7166 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7167 // be used to form addressing mode. These wrapped nodes will be selected
7168 // into MOV32ri.
7169 SDValue
7170 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7171   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7172
7173   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7174   // global base reg.
7175   unsigned char OpFlag = 0;
7176   unsigned WrapperKind = X86ISD::Wrapper;
7177   CodeModel::Model M = getTargetMachine().getCodeModel();
7178
7179   if (Subtarget->isPICStyleRIPRel() &&
7180       (M == CodeModel::Small || M == CodeModel::Kernel))
7181     WrapperKind = X86ISD::WrapperRIP;
7182   else if (Subtarget->isPICStyleGOT())
7183     OpFlag = X86II::MO_GOTOFF;
7184   else if (Subtarget->isPICStyleStubPIC())
7185     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7186
7187   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7188                                              CP->getAlignment(),
7189                                              CP->getOffset(), OpFlag);
7190   DebugLoc DL = CP->getDebugLoc();
7191   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7192   // With PIC, the address is actually $g + Offset.
7193   if (OpFlag) {
7194     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7195                          DAG.getNode(X86ISD::GlobalBaseReg,
7196                                      DebugLoc(), getPointerTy()),
7197                          Result);
7198   }
7199
7200   return Result;
7201 }
7202
7203 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7204   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7205
7206   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7207   // global base reg.
7208   unsigned char OpFlag = 0;
7209   unsigned WrapperKind = X86ISD::Wrapper;
7210   CodeModel::Model M = getTargetMachine().getCodeModel();
7211
7212   if (Subtarget->isPICStyleRIPRel() &&
7213       (M == CodeModel::Small || M == CodeModel::Kernel))
7214     WrapperKind = X86ISD::WrapperRIP;
7215   else if (Subtarget->isPICStyleGOT())
7216     OpFlag = X86II::MO_GOTOFF;
7217   else if (Subtarget->isPICStyleStubPIC())
7218     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7219
7220   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7221                                           OpFlag);
7222   DebugLoc DL = JT->getDebugLoc();
7223   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7224
7225   // With PIC, the address is actually $g + Offset.
7226   if (OpFlag)
7227     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7228                          DAG.getNode(X86ISD::GlobalBaseReg,
7229                                      DebugLoc(), getPointerTy()),
7230                          Result);
7231
7232   return Result;
7233 }
7234
7235 SDValue
7236 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7237   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7238
7239   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7240   // global base reg.
7241   unsigned char OpFlag = 0;
7242   unsigned WrapperKind = X86ISD::Wrapper;
7243   CodeModel::Model M = getTargetMachine().getCodeModel();
7244
7245   if (Subtarget->isPICStyleRIPRel() &&
7246       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7247     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7248       OpFlag = X86II::MO_GOTPCREL;
7249     WrapperKind = X86ISD::WrapperRIP;
7250   } else if (Subtarget->isPICStyleGOT()) {
7251     OpFlag = X86II::MO_GOT;
7252   } else if (Subtarget->isPICStyleStubPIC()) {
7253     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7254   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7255     OpFlag = X86II::MO_DARWIN_NONLAZY;
7256   }
7257
7258   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7259
7260   DebugLoc DL = Op.getDebugLoc();
7261   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7262
7263
7264   // With PIC, the address is actually $g + Offset.
7265   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7266       !Subtarget->is64Bit()) {
7267     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7268                          DAG.getNode(X86ISD::GlobalBaseReg,
7269                                      DebugLoc(), getPointerTy()),
7270                          Result);
7271   }
7272
7273   // For symbols that require a load from a stub to get the address, emit the
7274   // load.
7275   if (isGlobalStubReference(OpFlag))
7276     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7277                          MachinePointerInfo::getGOT(), false, false, 0);
7278
7279   return Result;
7280 }
7281
7282 SDValue
7283 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7284   // Create the TargetBlockAddressAddress node.
7285   unsigned char OpFlags =
7286     Subtarget->ClassifyBlockAddressReference();
7287   CodeModel::Model M = getTargetMachine().getCodeModel();
7288   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7289   DebugLoc dl = Op.getDebugLoc();
7290   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7291                                        /*isTarget=*/true, OpFlags);
7292
7293   if (Subtarget->isPICStyleRIPRel() &&
7294       (M == CodeModel::Small || M == CodeModel::Kernel))
7295     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7296   else
7297     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7298
7299   // With PIC, the address is actually $g + Offset.
7300   if (isGlobalRelativeToPICBase(OpFlags)) {
7301     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7302                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7303                          Result);
7304   }
7305
7306   return Result;
7307 }
7308
7309 SDValue
7310 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7311                                       int64_t Offset,
7312                                       SelectionDAG &DAG) const {
7313   // Create the TargetGlobalAddress node, folding in the constant
7314   // offset if it is legal.
7315   unsigned char OpFlags =
7316     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7317   CodeModel::Model M = getTargetMachine().getCodeModel();
7318   SDValue Result;
7319   if (OpFlags == X86II::MO_NO_FLAG &&
7320       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7321     // A direct static reference to a global.
7322     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7323     Offset = 0;
7324   } else {
7325     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7326   }
7327
7328   if (Subtarget->isPICStyleRIPRel() &&
7329       (M == CodeModel::Small || M == CodeModel::Kernel))
7330     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7331   else
7332     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7333
7334   // With PIC, the address is actually $g + Offset.
7335   if (isGlobalRelativeToPICBase(OpFlags)) {
7336     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7337                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7338                          Result);
7339   }
7340
7341   // For globals that require a load from a stub to get the address, emit the
7342   // load.
7343   if (isGlobalStubReference(OpFlags))
7344     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7345                          MachinePointerInfo::getGOT(), false, false, 0);
7346
7347   // If there was a non-zero offset that we didn't fold, create an explicit
7348   // addition for it.
7349   if (Offset != 0)
7350     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7351                          DAG.getConstant(Offset, getPointerTy()));
7352
7353   return Result;
7354 }
7355
7356 SDValue
7357 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7358   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7359   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7360   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7361 }
7362
7363 static SDValue
7364 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7365            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7366            unsigned char OperandFlags) {
7367   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7368   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7369   DebugLoc dl = GA->getDebugLoc();
7370   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7371                                            GA->getValueType(0),
7372                                            GA->getOffset(),
7373                                            OperandFlags);
7374   if (InFlag) {
7375     SDValue Ops[] = { Chain,  TGA, *InFlag };
7376     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7377   } else {
7378     SDValue Ops[]  = { Chain, TGA };
7379     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7380   }
7381
7382   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7383   MFI->setAdjustsStack(true);
7384
7385   SDValue Flag = Chain.getValue(1);
7386   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7387 }
7388
7389 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7390 static SDValue
7391 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7392                                 const EVT PtrVT) {
7393   SDValue InFlag;
7394   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7395   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7396                                      DAG.getNode(X86ISD::GlobalBaseReg,
7397                                                  DebugLoc(), PtrVT), InFlag);
7398   InFlag = Chain.getValue(1);
7399
7400   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7401 }
7402
7403 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7404 static SDValue
7405 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7406                                 const EVT PtrVT) {
7407   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7408                     X86::RAX, X86II::MO_TLSGD);
7409 }
7410
7411 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7412 // "local exec" model.
7413 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7414                                    const EVT PtrVT, TLSModel::Model model,
7415                                    bool is64Bit) {
7416   DebugLoc dl = GA->getDebugLoc();
7417
7418   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7419   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7420                                                          is64Bit ? 257 : 256));
7421
7422   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7423                                       DAG.getIntPtrConstant(0),
7424                                       MachinePointerInfo(Ptr), false, false, 0);
7425
7426   unsigned char OperandFlags = 0;
7427   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7428   // initialexec.
7429   unsigned WrapperKind = X86ISD::Wrapper;
7430   if (model == TLSModel::LocalExec) {
7431     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7432   } else if (is64Bit) {
7433     assert(model == TLSModel::InitialExec);
7434     OperandFlags = X86II::MO_GOTTPOFF;
7435     WrapperKind = X86ISD::WrapperRIP;
7436   } else {
7437     assert(model == TLSModel::InitialExec);
7438     OperandFlags = X86II::MO_INDNTPOFF;
7439   }
7440
7441   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7442   // exec)
7443   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7444                                            GA->getValueType(0),
7445                                            GA->getOffset(), OperandFlags);
7446   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7447
7448   if (model == TLSModel::InitialExec)
7449     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7450                          MachinePointerInfo::getGOT(), false, false, 0);
7451
7452   // The address of the thread local variable is the add of the thread
7453   // pointer with the offset of the variable.
7454   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7455 }
7456
7457 SDValue
7458 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7459
7460   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7461   const GlobalValue *GV = GA->getGlobal();
7462
7463   if (Subtarget->isTargetELF()) {
7464     // TODO: implement the "local dynamic" model
7465     // TODO: implement the "initial exec"model for pic executables
7466
7467     // If GV is an alias then use the aliasee for determining
7468     // thread-localness.
7469     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7470       GV = GA->resolveAliasedGlobal(false);
7471
7472     TLSModel::Model model
7473       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7474
7475     switch (model) {
7476       case TLSModel::GeneralDynamic:
7477       case TLSModel::LocalDynamic: // not implemented
7478         if (Subtarget->is64Bit())
7479           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7480         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7481
7482       case TLSModel::InitialExec:
7483       case TLSModel::LocalExec:
7484         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7485                                    Subtarget->is64Bit());
7486     }
7487   } else if (Subtarget->isTargetDarwin()) {
7488     // Darwin only has one model of TLS.  Lower to that.
7489     unsigned char OpFlag = 0;
7490     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7491                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7492
7493     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7494     // global base reg.
7495     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7496                   !Subtarget->is64Bit();
7497     if (PIC32)
7498       OpFlag = X86II::MO_TLVP_PIC_BASE;
7499     else
7500       OpFlag = X86II::MO_TLVP;
7501     DebugLoc DL = Op.getDebugLoc();
7502     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7503                                                 GA->getValueType(0),
7504                                                 GA->getOffset(), OpFlag);
7505     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7506
7507     // With PIC32, the address is actually $g + Offset.
7508     if (PIC32)
7509       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7510                            DAG.getNode(X86ISD::GlobalBaseReg,
7511                                        DebugLoc(), getPointerTy()),
7512                            Offset);
7513
7514     // Lowering the machine isd will make sure everything is in the right
7515     // location.
7516     SDValue Chain = DAG.getEntryNode();
7517     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7518     SDValue Args[] = { Chain, Offset };
7519     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7520
7521     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7522     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7523     MFI->setAdjustsStack(true);
7524
7525     // And our return value (tls address) is in the standard call return value
7526     // location.
7527     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7528     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7529   }
7530
7531   assert(false &&
7532          "TLS not implemented for this target.");
7533
7534   llvm_unreachable("Unreachable");
7535   return SDValue();
7536 }
7537
7538
7539 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7540 /// take a 2 x i32 value to shift plus a shift amount.
7541 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7542   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7543   EVT VT = Op.getValueType();
7544   unsigned VTBits = VT.getSizeInBits();
7545   DebugLoc dl = Op.getDebugLoc();
7546   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7547   SDValue ShOpLo = Op.getOperand(0);
7548   SDValue ShOpHi = Op.getOperand(1);
7549   SDValue ShAmt  = Op.getOperand(2);
7550   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7551                                      DAG.getConstant(VTBits - 1, MVT::i8))
7552                        : DAG.getConstant(0, VT);
7553
7554   SDValue Tmp2, Tmp3;
7555   if (Op.getOpcode() == ISD::SHL_PARTS) {
7556     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7557     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7558   } else {
7559     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7560     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7561   }
7562
7563   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7564                                 DAG.getConstant(VTBits, MVT::i8));
7565   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7566                              AndNode, DAG.getConstant(0, MVT::i8));
7567
7568   SDValue Hi, Lo;
7569   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7570   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7571   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7572
7573   if (Op.getOpcode() == ISD::SHL_PARTS) {
7574     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7575     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7576   } else {
7577     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7578     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7579   }
7580
7581   SDValue Ops[2] = { Lo, Hi };
7582   return DAG.getMergeValues(Ops, 2, dl);
7583 }
7584
7585 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7586                                            SelectionDAG &DAG) const {
7587   EVT SrcVT = Op.getOperand(0).getValueType();
7588
7589   if (SrcVT.isVector())
7590     return SDValue();
7591
7592   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7593          "Unknown SINT_TO_FP to lower!");
7594
7595   // These are really Legal; return the operand so the caller accepts it as
7596   // Legal.
7597   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7598     return Op;
7599   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7600       Subtarget->is64Bit()) {
7601     return Op;
7602   }
7603
7604   DebugLoc dl = Op.getDebugLoc();
7605   unsigned Size = SrcVT.getSizeInBits()/8;
7606   MachineFunction &MF = DAG.getMachineFunction();
7607   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7608   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7609   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7610                                StackSlot,
7611                                MachinePointerInfo::getFixedStack(SSFI),
7612                                false, false, 0);
7613   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7614 }
7615
7616 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7617                                      SDValue StackSlot,
7618                                      SelectionDAG &DAG) const {
7619   // Build the FILD
7620   DebugLoc DL = Op.getDebugLoc();
7621   SDVTList Tys;
7622   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7623   if (useSSE)
7624     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7625   else
7626     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7627
7628   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7629
7630   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7631   MachineMemOperand *MMO;
7632   if (FI) {
7633     int SSFI = FI->getIndex();
7634     MMO =
7635       DAG.getMachineFunction()
7636       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7637                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7638   } else {
7639     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7640     StackSlot = StackSlot.getOperand(1);
7641   }
7642   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7643   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7644                                            X86ISD::FILD, DL,
7645                                            Tys, Ops, array_lengthof(Ops),
7646                                            SrcVT, MMO);
7647
7648   if (useSSE) {
7649     Chain = Result.getValue(1);
7650     SDValue InFlag = Result.getValue(2);
7651
7652     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7653     // shouldn't be necessary except that RFP cannot be live across
7654     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7655     MachineFunction &MF = DAG.getMachineFunction();
7656     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7657     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7658     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7659     Tys = DAG.getVTList(MVT::Other);
7660     SDValue Ops[] = {
7661       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7662     };
7663     MachineMemOperand *MMO =
7664       DAG.getMachineFunction()
7665       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7666                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7667
7668     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7669                                     Ops, array_lengthof(Ops),
7670                                     Op.getValueType(), MMO);
7671     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7672                          MachinePointerInfo::getFixedStack(SSFI),
7673                          false, false, 0);
7674   }
7675
7676   return Result;
7677 }
7678
7679 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7680 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7681                                                SelectionDAG &DAG) const {
7682   // This algorithm is not obvious. Here it is in C code, more or less:
7683   /*
7684     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7685       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7686       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7687
7688       // Copy ints to xmm registers.
7689       __m128i xh = _mm_cvtsi32_si128( hi );
7690       __m128i xl = _mm_cvtsi32_si128( lo );
7691
7692       // Combine into low half of a single xmm register.
7693       __m128i x = _mm_unpacklo_epi32( xh, xl );
7694       __m128d d;
7695       double sd;
7696
7697       // Merge in appropriate exponents to give the integer bits the right
7698       // magnitude.
7699       x = _mm_unpacklo_epi32( x, exp );
7700
7701       // Subtract away the biases to deal with the IEEE-754 double precision
7702       // implicit 1.
7703       d = _mm_sub_pd( (__m128d) x, bias );
7704
7705       // All conversions up to here are exact. The correctly rounded result is
7706       // calculated using the current rounding mode using the following
7707       // horizontal add.
7708       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7709       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7710                                 // store doesn't really need to be here (except
7711                                 // maybe to zero the other double)
7712       return sd;
7713     }
7714   */
7715
7716   DebugLoc dl = Op.getDebugLoc();
7717   LLVMContext *Context = DAG.getContext();
7718
7719   // Build some magic constants.
7720   std::vector<Constant*> CV0;
7721   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7722   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7723   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7724   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7725   Constant *C0 = ConstantVector::get(CV0);
7726   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7727
7728   std::vector<Constant*> CV1;
7729   CV1.push_back(
7730     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7731   CV1.push_back(
7732     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7733   Constant *C1 = ConstantVector::get(CV1);
7734   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7735
7736   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7737                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7738                                         Op.getOperand(0),
7739                                         DAG.getIntPtrConstant(1)));
7740   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7741                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7742                                         Op.getOperand(0),
7743                                         DAG.getIntPtrConstant(0)));
7744   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7745   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7746                               MachinePointerInfo::getConstantPool(),
7747                               false, false, 16);
7748   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7749   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7750   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7751                               MachinePointerInfo::getConstantPool(),
7752                               false, false, 16);
7753   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7754
7755   // Add the halves; easiest way is to swap them into another reg first.
7756   int ShufMask[2] = { 1, -1 };
7757   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7758                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7759   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7760   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7761                      DAG.getIntPtrConstant(0));
7762 }
7763
7764 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7765 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7766                                                SelectionDAG &DAG) const {
7767   DebugLoc dl = Op.getDebugLoc();
7768   // FP constant to bias correct the final result.
7769   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7770                                    MVT::f64);
7771
7772   // Load the 32-bit value into an XMM register.
7773   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7774                              Op.getOperand(0));
7775
7776   // Zero out the upper parts of the register.
7777   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7778                                      DAG);
7779
7780   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7781                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7782                      DAG.getIntPtrConstant(0));
7783
7784   // Or the load with the bias.
7785   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7786                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7787                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7788                                                    MVT::v2f64, Load)),
7789                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7790                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7791                                                    MVT::v2f64, Bias)));
7792   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7793                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7794                    DAG.getIntPtrConstant(0));
7795
7796   // Subtract the bias.
7797   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7798
7799   // Handle final rounding.
7800   EVT DestVT = Op.getValueType();
7801
7802   if (DestVT.bitsLT(MVT::f64)) {
7803     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7804                        DAG.getIntPtrConstant(0));
7805   } else if (DestVT.bitsGT(MVT::f64)) {
7806     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7807   }
7808
7809   // Handle final rounding.
7810   return Sub;
7811 }
7812
7813 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7814                                            SelectionDAG &DAG) const {
7815   SDValue N0 = Op.getOperand(0);
7816   DebugLoc dl = Op.getDebugLoc();
7817
7818   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7819   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7820   // the optimization here.
7821   if (DAG.SignBitIsZero(N0))
7822     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7823
7824   EVT SrcVT = N0.getValueType();
7825   EVT DstVT = Op.getValueType();
7826   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7827     return LowerUINT_TO_FP_i64(Op, DAG);
7828   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7829     return LowerUINT_TO_FP_i32(Op, DAG);
7830
7831   // Make a 64-bit buffer, and use it to build an FILD.
7832   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7833   if (SrcVT == MVT::i32) {
7834     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7835     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7836                                      getPointerTy(), StackSlot, WordOff);
7837     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7838                                   StackSlot, MachinePointerInfo(),
7839                                   false, false, 0);
7840     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7841                                   OffsetSlot, MachinePointerInfo(),
7842                                   false, false, 0);
7843     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7844     return Fild;
7845   }
7846
7847   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7848   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7849                                 StackSlot, MachinePointerInfo(),
7850                                false, false, 0);
7851   // For i64 source, we need to add the appropriate power of 2 if the input
7852   // was negative.  This is the same as the optimization in
7853   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7854   // we must be careful to do the computation in x87 extended precision, not
7855   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7856   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7857   MachineMemOperand *MMO =
7858     DAG.getMachineFunction()
7859     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7860                           MachineMemOperand::MOLoad, 8, 8);
7861
7862   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7863   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7864   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7865                                          MVT::i64, MMO);
7866
7867   APInt FF(32, 0x5F800000ULL);
7868
7869   // Check whether the sign bit is set.
7870   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7871                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7872                                  ISD::SETLT);
7873
7874   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7875   SDValue FudgePtr = DAG.getConstantPool(
7876                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7877                                          getPointerTy());
7878
7879   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7880   SDValue Zero = DAG.getIntPtrConstant(0);
7881   SDValue Four = DAG.getIntPtrConstant(4);
7882   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7883                                Zero, Four);
7884   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7885
7886   // Load the value out, extending it from f32 to f80.
7887   // FIXME: Avoid the extend by constructing the right constant pool?
7888   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7889                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7890                                  MVT::f32, false, false, 4);
7891   // Extend everything to 80 bits to force it to be done on x87.
7892   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7893   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7894 }
7895
7896 std::pair<SDValue,SDValue> X86TargetLowering::
7897 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7898   DebugLoc DL = Op.getDebugLoc();
7899
7900   EVT DstTy = Op.getValueType();
7901
7902   if (!IsSigned) {
7903     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7904     DstTy = MVT::i64;
7905   }
7906
7907   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7908          DstTy.getSimpleVT() >= MVT::i16 &&
7909          "Unknown FP_TO_SINT to lower!");
7910
7911   // These are really Legal.
7912   if (DstTy == MVT::i32 &&
7913       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7914     return std::make_pair(SDValue(), SDValue());
7915   if (Subtarget->is64Bit() &&
7916       DstTy == MVT::i64 &&
7917       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7918     return std::make_pair(SDValue(), SDValue());
7919
7920   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7921   // stack slot.
7922   MachineFunction &MF = DAG.getMachineFunction();
7923   unsigned MemSize = DstTy.getSizeInBits()/8;
7924   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7925   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7926
7927
7928
7929   unsigned Opc;
7930   switch (DstTy.getSimpleVT().SimpleTy) {
7931   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7932   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7933   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7934   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7935   }
7936
7937   SDValue Chain = DAG.getEntryNode();
7938   SDValue Value = Op.getOperand(0);
7939   EVT TheVT = Op.getOperand(0).getValueType();
7940   if (isScalarFPTypeInSSEReg(TheVT)) {
7941     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7942     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7943                          MachinePointerInfo::getFixedStack(SSFI),
7944                          false, false, 0);
7945     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7946     SDValue Ops[] = {
7947       Chain, StackSlot, DAG.getValueType(TheVT)
7948     };
7949
7950     MachineMemOperand *MMO =
7951       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7952                               MachineMemOperand::MOLoad, MemSize, MemSize);
7953     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7954                                     DstTy, MMO);
7955     Chain = Value.getValue(1);
7956     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7957     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7958   }
7959
7960   MachineMemOperand *MMO =
7961     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7962                             MachineMemOperand::MOStore, MemSize, MemSize);
7963
7964   // Build the FP_TO_INT*_IN_MEM
7965   SDValue Ops[] = { Chain, Value, StackSlot };
7966   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7967                                          Ops, 3, DstTy, MMO);
7968
7969   return std::make_pair(FIST, StackSlot);
7970 }
7971
7972 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7973                                            SelectionDAG &DAG) const {
7974   if (Op.getValueType().isVector())
7975     return SDValue();
7976
7977   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7978   SDValue FIST = Vals.first, StackSlot = Vals.second;
7979   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7980   if (FIST.getNode() == 0) return Op;
7981
7982   // Load the result.
7983   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7984                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7985 }
7986
7987 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7988                                            SelectionDAG &DAG) const {
7989   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7990   SDValue FIST = Vals.first, StackSlot = Vals.second;
7991   assert(FIST.getNode() && "Unexpected failure");
7992
7993   // Load the result.
7994   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7995                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7996 }
7997
7998 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7999                                      SelectionDAG &DAG) const {
8000   LLVMContext *Context = DAG.getContext();
8001   DebugLoc dl = Op.getDebugLoc();
8002   EVT VT = Op.getValueType();
8003   EVT EltVT = VT;
8004   if (VT.isVector())
8005     EltVT = VT.getVectorElementType();
8006   std::vector<Constant*> CV;
8007   if (EltVT == MVT::f64) {
8008     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8009     CV.push_back(C);
8010     CV.push_back(C);
8011   } else {
8012     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8013     CV.push_back(C);
8014     CV.push_back(C);
8015     CV.push_back(C);
8016     CV.push_back(C);
8017   }
8018   Constant *C = ConstantVector::get(CV);
8019   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8020   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8021                              MachinePointerInfo::getConstantPool(),
8022                              false, false, 16);
8023   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8024 }
8025
8026 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8027   LLVMContext *Context = DAG.getContext();
8028   DebugLoc dl = Op.getDebugLoc();
8029   EVT VT = Op.getValueType();
8030   EVT EltVT = VT;
8031   if (VT.isVector())
8032     EltVT = VT.getVectorElementType();
8033   std::vector<Constant*> CV;
8034   if (EltVT == MVT::f64) {
8035     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8036     CV.push_back(C);
8037     CV.push_back(C);
8038   } else {
8039     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8040     CV.push_back(C);
8041     CV.push_back(C);
8042     CV.push_back(C);
8043     CV.push_back(C);
8044   }
8045   Constant *C = ConstantVector::get(CV);
8046   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8047   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8048                              MachinePointerInfo::getConstantPool(),
8049                              false, false, 16);
8050   if (VT.isVector()) {
8051     return DAG.getNode(ISD::BITCAST, dl, VT,
8052                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8053                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8054                                 Op.getOperand(0)),
8055                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8056   } else {
8057     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8058   }
8059 }
8060
8061 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8062   LLVMContext *Context = DAG.getContext();
8063   SDValue Op0 = Op.getOperand(0);
8064   SDValue Op1 = Op.getOperand(1);
8065   DebugLoc dl = Op.getDebugLoc();
8066   EVT VT = Op.getValueType();
8067   EVT SrcVT = Op1.getValueType();
8068
8069   // If second operand is smaller, extend it first.
8070   if (SrcVT.bitsLT(VT)) {
8071     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8072     SrcVT = VT;
8073   }
8074   // And if it is bigger, shrink it first.
8075   if (SrcVT.bitsGT(VT)) {
8076     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8077     SrcVT = VT;
8078   }
8079
8080   // At this point the operands and the result should have the same
8081   // type, and that won't be f80 since that is not custom lowered.
8082
8083   // First get the sign bit of second operand.
8084   std::vector<Constant*> CV;
8085   if (SrcVT == MVT::f64) {
8086     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8087     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8088   } else {
8089     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8090     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8091     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8092     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8093   }
8094   Constant *C = ConstantVector::get(CV);
8095   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8096   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8097                               MachinePointerInfo::getConstantPool(),
8098                               false, false, 16);
8099   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8100
8101   // Shift sign bit right or left if the two operands have different types.
8102   if (SrcVT.bitsGT(VT)) {
8103     // Op0 is MVT::f32, Op1 is MVT::f64.
8104     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8105     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8106                           DAG.getConstant(32, MVT::i32));
8107     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8108     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8109                           DAG.getIntPtrConstant(0));
8110   }
8111
8112   // Clear first operand sign bit.
8113   CV.clear();
8114   if (VT == MVT::f64) {
8115     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8116     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8117   } else {
8118     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8119     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8120     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8121     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8122   }
8123   C = ConstantVector::get(CV);
8124   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8125   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8126                               MachinePointerInfo::getConstantPool(),
8127                               false, false, 16);
8128   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8129
8130   // Or the value with the sign bit.
8131   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8132 }
8133
8134 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8135   SDValue N0 = Op.getOperand(0);
8136   DebugLoc dl = Op.getDebugLoc();
8137   EVT VT = Op.getValueType();
8138
8139   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8140   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8141                                   DAG.getConstant(1, VT));
8142   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8143 }
8144
8145 /// Emit nodes that will be selected as "test Op0,Op0", or something
8146 /// equivalent.
8147 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8148                                     SelectionDAG &DAG) const {
8149   DebugLoc dl = Op.getDebugLoc();
8150
8151   // CF and OF aren't always set the way we want. Determine which
8152   // of these we need.
8153   bool NeedCF = false;
8154   bool NeedOF = false;
8155   switch (X86CC) {
8156   default: break;
8157   case X86::COND_A: case X86::COND_AE:
8158   case X86::COND_B: case X86::COND_BE:
8159     NeedCF = true;
8160     break;
8161   case X86::COND_G: case X86::COND_GE:
8162   case X86::COND_L: case X86::COND_LE:
8163   case X86::COND_O: case X86::COND_NO:
8164     NeedOF = true;
8165     break;
8166   }
8167
8168   // See if we can use the EFLAGS value from the operand instead of
8169   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8170   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8171   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8172     // Emit a CMP with 0, which is the TEST pattern.
8173     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8174                        DAG.getConstant(0, Op.getValueType()));
8175
8176   unsigned Opcode = 0;
8177   unsigned NumOperands = 0;
8178   switch (Op.getNode()->getOpcode()) {
8179   case ISD::ADD:
8180     // Due to an isel shortcoming, be conservative if this add is likely to be
8181     // selected as part of a load-modify-store instruction. When the root node
8182     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8183     // uses of other nodes in the match, such as the ADD in this case. This
8184     // leads to the ADD being left around and reselected, with the result being
8185     // two adds in the output.  Alas, even if none our users are stores, that
8186     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8187     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8188     // climbing the DAG back to the root, and it doesn't seem to be worth the
8189     // effort.
8190     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8191            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8192       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8193         goto default_case;
8194
8195     if (ConstantSDNode *C =
8196         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8197       // An add of one will be selected as an INC.
8198       if (C->getAPIntValue() == 1) {
8199         Opcode = X86ISD::INC;
8200         NumOperands = 1;
8201         break;
8202       }
8203
8204       // An add of negative one (subtract of one) will be selected as a DEC.
8205       if (C->getAPIntValue().isAllOnesValue()) {
8206         Opcode = X86ISD::DEC;
8207         NumOperands = 1;
8208         break;
8209       }
8210     }
8211
8212     // Otherwise use a regular EFLAGS-setting add.
8213     Opcode = X86ISD::ADD;
8214     NumOperands = 2;
8215     break;
8216   case ISD::AND: {
8217     // If the primary and result isn't used, don't bother using X86ISD::AND,
8218     // because a TEST instruction will be better.
8219     bool NonFlagUse = false;
8220     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8221            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8222       SDNode *User = *UI;
8223       unsigned UOpNo = UI.getOperandNo();
8224       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8225         // Look pass truncate.
8226         UOpNo = User->use_begin().getOperandNo();
8227         User = *User->use_begin();
8228       }
8229
8230       if (User->getOpcode() != ISD::BRCOND &&
8231           User->getOpcode() != ISD::SETCC &&
8232           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8233         NonFlagUse = true;
8234         break;
8235       }
8236     }
8237
8238     if (!NonFlagUse)
8239       break;
8240   }
8241     // FALL THROUGH
8242   case ISD::SUB:
8243   case ISD::OR:
8244   case ISD::XOR:
8245     // Due to the ISEL shortcoming noted above, be conservative if this op is
8246     // likely to be selected as part of a load-modify-store instruction.
8247     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8248            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8249       if (UI->getOpcode() == ISD::STORE)
8250         goto default_case;
8251
8252     // Otherwise use a regular EFLAGS-setting instruction.
8253     switch (Op.getNode()->getOpcode()) {
8254     default: llvm_unreachable("unexpected operator!");
8255     case ISD::SUB: Opcode = X86ISD::SUB; break;
8256     case ISD::OR:  Opcode = X86ISD::OR;  break;
8257     case ISD::XOR: Opcode = X86ISD::XOR; break;
8258     case ISD::AND: Opcode = X86ISD::AND; break;
8259     }
8260
8261     NumOperands = 2;
8262     break;
8263   case X86ISD::ADD:
8264   case X86ISD::SUB:
8265   case X86ISD::INC:
8266   case X86ISD::DEC:
8267   case X86ISD::OR:
8268   case X86ISD::XOR:
8269   case X86ISD::AND:
8270     return SDValue(Op.getNode(), 1);
8271   default:
8272   default_case:
8273     break;
8274   }
8275
8276   if (Opcode == 0)
8277     // Emit a CMP with 0, which is the TEST pattern.
8278     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8279                        DAG.getConstant(0, Op.getValueType()));
8280
8281   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8282   SmallVector<SDValue, 4> Ops;
8283   for (unsigned i = 0; i != NumOperands; ++i)
8284     Ops.push_back(Op.getOperand(i));
8285
8286   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8287   DAG.ReplaceAllUsesWith(Op, New);
8288   return SDValue(New.getNode(), 1);
8289 }
8290
8291 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8292 /// equivalent.
8293 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8294                                    SelectionDAG &DAG) const {
8295   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8296     if (C->getAPIntValue() == 0)
8297       return EmitTest(Op0, X86CC, DAG);
8298
8299   DebugLoc dl = Op0.getDebugLoc();
8300   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8301 }
8302
8303 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8304 /// if it's possible.
8305 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8306                                      DebugLoc dl, SelectionDAG &DAG) const {
8307   SDValue Op0 = And.getOperand(0);
8308   SDValue Op1 = And.getOperand(1);
8309   if (Op0.getOpcode() == ISD::TRUNCATE)
8310     Op0 = Op0.getOperand(0);
8311   if (Op1.getOpcode() == ISD::TRUNCATE)
8312     Op1 = Op1.getOperand(0);
8313
8314   SDValue LHS, RHS;
8315   if (Op1.getOpcode() == ISD::SHL)
8316     std::swap(Op0, Op1);
8317   if (Op0.getOpcode() == ISD::SHL) {
8318     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8319       if (And00C->getZExtValue() == 1) {
8320         // If we looked past a truncate, check that it's only truncating away
8321         // known zeros.
8322         unsigned BitWidth = Op0.getValueSizeInBits();
8323         unsigned AndBitWidth = And.getValueSizeInBits();
8324         if (BitWidth > AndBitWidth) {
8325           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8326           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8327           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8328             return SDValue();
8329         }
8330         LHS = Op1;
8331         RHS = Op0.getOperand(1);
8332       }
8333   } else if (Op1.getOpcode() == ISD::Constant) {
8334     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8335     SDValue AndLHS = Op0;
8336     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8337       LHS = AndLHS.getOperand(0);
8338       RHS = AndLHS.getOperand(1);
8339     }
8340   }
8341
8342   if (LHS.getNode()) {
8343     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8344     // instruction.  Since the shift amount is in-range-or-undefined, we know
8345     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8346     // the encoding for the i16 version is larger than the i32 version.
8347     // Also promote i16 to i32 for performance / code size reason.
8348     if (LHS.getValueType() == MVT::i8 ||
8349         LHS.getValueType() == MVT::i16)
8350       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8351
8352     // If the operand types disagree, extend the shift amount to match.  Since
8353     // BT ignores high bits (like shifts) we can use anyextend.
8354     if (LHS.getValueType() != RHS.getValueType())
8355       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8356
8357     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8358     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8359     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8360                        DAG.getConstant(Cond, MVT::i8), BT);
8361   }
8362
8363   return SDValue();
8364 }
8365
8366 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8367
8368   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8369
8370   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8371   SDValue Op0 = Op.getOperand(0);
8372   SDValue Op1 = Op.getOperand(1);
8373   DebugLoc dl = Op.getDebugLoc();
8374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8375
8376   // Optimize to BT if possible.
8377   // Lower (X & (1 << N)) == 0 to BT(X, N).
8378   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8379   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8380   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8381       Op1.getOpcode() == ISD::Constant &&
8382       cast<ConstantSDNode>(Op1)->isNullValue() &&
8383       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8384     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8385     if (NewSetCC.getNode())
8386       return NewSetCC;
8387   }
8388
8389   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8390   // these.
8391   if (Op1.getOpcode() == ISD::Constant &&
8392       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8393        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8394       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8395
8396     // If the input is a setcc, then reuse the input setcc or use a new one with
8397     // the inverted condition.
8398     if (Op0.getOpcode() == X86ISD::SETCC) {
8399       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8400       bool Invert = (CC == ISD::SETNE) ^
8401         cast<ConstantSDNode>(Op1)->isNullValue();
8402       if (!Invert) return Op0;
8403
8404       CCode = X86::GetOppositeBranchCondition(CCode);
8405       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8406                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8407     }
8408   }
8409
8410   bool isFP = Op1.getValueType().isFloatingPoint();
8411   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8412   if (X86CC == X86::COND_INVALID)
8413     return SDValue();
8414
8415   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8416   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8417                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8418 }
8419
8420 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8421 // ones, and then concatenate the result back.
8422 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8423   EVT VT = Op.getValueType();
8424
8425   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8426          "Unsupported value type for operation");
8427
8428   int NumElems = VT.getVectorNumElements();
8429   DebugLoc dl = Op.getDebugLoc();
8430   SDValue CC = Op.getOperand(2);
8431   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8432   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8433
8434   // Extract the LHS vectors
8435   SDValue LHS = Op.getOperand(0);
8436   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8437   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8438
8439   // Extract the RHS vectors
8440   SDValue RHS = Op.getOperand(1);
8441   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8442   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8443
8444   // Issue the operation on the smaller types and concatenate the result back
8445   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8446   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8447   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8448                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8449                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8450 }
8451
8452
8453 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8454   SDValue Cond;
8455   SDValue Op0 = Op.getOperand(0);
8456   SDValue Op1 = Op.getOperand(1);
8457   SDValue CC = Op.getOperand(2);
8458   EVT VT = Op.getValueType();
8459   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8460   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8461   DebugLoc dl = Op.getDebugLoc();
8462
8463   if (isFP) {
8464     unsigned SSECC = 8;
8465     EVT EltVT = Op0.getValueType().getVectorElementType();
8466     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8467
8468     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8469     bool Swap = false;
8470
8471     // SSE Condition code mapping:
8472     //  0 - EQ
8473     //  1 - LT
8474     //  2 - LE
8475     //  3 - UNORD
8476     //  4 - NEQ
8477     //  5 - NLT
8478     //  6 - NLE
8479     //  7 - ORD
8480     switch (SetCCOpcode) {
8481     default: break;
8482     case ISD::SETOEQ:
8483     case ISD::SETEQ:  SSECC = 0; break;
8484     case ISD::SETOGT:
8485     case ISD::SETGT: Swap = true; // Fallthrough
8486     case ISD::SETLT:
8487     case ISD::SETOLT: SSECC = 1; break;
8488     case ISD::SETOGE:
8489     case ISD::SETGE: Swap = true; // Fallthrough
8490     case ISD::SETLE:
8491     case ISD::SETOLE: SSECC = 2; break;
8492     case ISD::SETUO:  SSECC = 3; break;
8493     case ISD::SETUNE:
8494     case ISD::SETNE:  SSECC = 4; break;
8495     case ISD::SETULE: Swap = true;
8496     case ISD::SETUGE: SSECC = 5; break;
8497     case ISD::SETULT: Swap = true;
8498     case ISD::SETUGT: SSECC = 6; break;
8499     case ISD::SETO:   SSECC = 7; break;
8500     }
8501     if (Swap)
8502       std::swap(Op0, Op1);
8503
8504     // In the two special cases we can't handle, emit two comparisons.
8505     if (SSECC == 8) {
8506       if (SetCCOpcode == ISD::SETUEQ) {
8507         SDValue UNORD, EQ;
8508         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8509         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8510         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8511       }
8512       else if (SetCCOpcode == ISD::SETONE) {
8513         SDValue ORD, NEQ;
8514         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8515         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8516         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8517       }
8518       llvm_unreachable("Illegal FP comparison");
8519     }
8520     // Handle all other FP comparisons here.
8521     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8522   }
8523
8524   // Break 256-bit integer vector compare into smaller ones.
8525   if (!isFP && VT.getSizeInBits() == 256)
8526     return Lower256IntVSETCC(Op, DAG);
8527
8528   // We are handling one of the integer comparisons here.  Since SSE only has
8529   // GT and EQ comparisons for integer, swapping operands and multiple
8530   // operations may be required for some comparisons.
8531   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8532   bool Swap = false, Invert = false, FlipSigns = false;
8533
8534   switch (VT.getSimpleVT().SimpleTy) {
8535   default: break;
8536   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8537   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8538   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8539   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8540   }
8541
8542   switch (SetCCOpcode) {
8543   default: break;
8544   case ISD::SETNE:  Invert = true;
8545   case ISD::SETEQ:  Opc = EQOpc; break;
8546   case ISD::SETLT:  Swap = true;
8547   case ISD::SETGT:  Opc = GTOpc; break;
8548   case ISD::SETGE:  Swap = true;
8549   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8550   case ISD::SETULT: Swap = true;
8551   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8552   case ISD::SETUGE: Swap = true;
8553   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8554   }
8555   if (Swap)
8556     std::swap(Op0, Op1);
8557
8558   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8559   // bits of the inputs before performing those operations.
8560   if (FlipSigns) {
8561     EVT EltVT = VT.getVectorElementType();
8562     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8563                                       EltVT);
8564     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8565     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8566                                     SignBits.size());
8567     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8568     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8569   }
8570
8571   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8572
8573   // If the logical-not of the result is required, perform that now.
8574   if (Invert)
8575     Result = DAG.getNOT(dl, Result, VT);
8576
8577   return Result;
8578 }
8579
8580 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8581 static bool isX86LogicalCmp(SDValue Op) {
8582   unsigned Opc = Op.getNode()->getOpcode();
8583   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8584     return true;
8585   if (Op.getResNo() == 1 &&
8586       (Opc == X86ISD::ADD ||
8587        Opc == X86ISD::SUB ||
8588        Opc == X86ISD::ADC ||
8589        Opc == X86ISD::SBB ||
8590        Opc == X86ISD::SMUL ||
8591        Opc == X86ISD::UMUL ||
8592        Opc == X86ISD::INC ||
8593        Opc == X86ISD::DEC ||
8594        Opc == X86ISD::OR ||
8595        Opc == X86ISD::XOR ||
8596        Opc == X86ISD::AND))
8597     return true;
8598
8599   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8600     return true;
8601
8602   return false;
8603 }
8604
8605 static bool isZero(SDValue V) {
8606   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8607   return C && C->isNullValue();
8608 }
8609
8610 static bool isAllOnes(SDValue V) {
8611   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8612   return C && C->isAllOnesValue();
8613 }
8614
8615 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8616   bool addTest = true;
8617   SDValue Cond  = Op.getOperand(0);
8618   SDValue Op1 = Op.getOperand(1);
8619   SDValue Op2 = Op.getOperand(2);
8620   DebugLoc DL = Op.getDebugLoc();
8621   SDValue CC;
8622
8623   if (Cond.getOpcode() == ISD::SETCC) {
8624     SDValue NewCond = LowerSETCC(Cond, DAG);
8625     if (NewCond.getNode())
8626       Cond = NewCond;
8627   }
8628
8629   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8630   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8631   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8632   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8633   if (Cond.getOpcode() == X86ISD::SETCC &&
8634       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8635       isZero(Cond.getOperand(1).getOperand(1))) {
8636     SDValue Cmp = Cond.getOperand(1);
8637
8638     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8639
8640     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8641         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8642       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8643
8644       SDValue CmpOp0 = Cmp.getOperand(0);
8645       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8646                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8647
8648       SDValue Res =   // Res = 0 or -1.
8649         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8650                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8651
8652       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8653         Res = DAG.getNOT(DL, Res, Res.getValueType());
8654
8655       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8656       if (N2C == 0 || !N2C->isNullValue())
8657         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8658       return Res;
8659     }
8660   }
8661
8662   // Look past (and (setcc_carry (cmp ...)), 1).
8663   if (Cond.getOpcode() == ISD::AND &&
8664       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8665     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8666     if (C && C->getAPIntValue() == 1)
8667       Cond = Cond.getOperand(0);
8668   }
8669
8670   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8671   // setting operand in place of the X86ISD::SETCC.
8672   if (Cond.getOpcode() == X86ISD::SETCC ||
8673       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8674     CC = Cond.getOperand(0);
8675
8676     SDValue Cmp = Cond.getOperand(1);
8677     unsigned Opc = Cmp.getOpcode();
8678     EVT VT = Op.getValueType();
8679
8680     bool IllegalFPCMov = false;
8681     if (VT.isFloatingPoint() && !VT.isVector() &&
8682         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8683       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8684
8685     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8686         Opc == X86ISD::BT) { // FIXME
8687       Cond = Cmp;
8688       addTest = false;
8689     }
8690   }
8691
8692   if (addTest) {
8693     // Look pass the truncate.
8694     if (Cond.getOpcode() == ISD::TRUNCATE)
8695       Cond = Cond.getOperand(0);
8696
8697     // We know the result of AND is compared against zero. Try to match
8698     // it to BT.
8699     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8700       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8701       if (NewSetCC.getNode()) {
8702         CC = NewSetCC.getOperand(0);
8703         Cond = NewSetCC.getOperand(1);
8704         addTest = false;
8705       }
8706     }
8707   }
8708
8709   if (addTest) {
8710     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8711     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8712   }
8713
8714   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8715   // a <  b ?  0 : -1 -> RES = setcc_carry
8716   // a >= b ? -1 :  0 -> RES = setcc_carry
8717   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8718   if (Cond.getOpcode() == X86ISD::CMP) {
8719     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8720
8721     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8722         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8723       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8724                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8725       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8726         return DAG.getNOT(DL, Res, Res.getValueType());
8727       return Res;
8728     }
8729   }
8730
8731   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8732   // condition is true.
8733   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8734   SDValue Ops[] = { Op2, Op1, CC, Cond };
8735   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8736 }
8737
8738 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8739 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8740 // from the AND / OR.
8741 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8742   Opc = Op.getOpcode();
8743   if (Opc != ISD::OR && Opc != ISD::AND)
8744     return false;
8745   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8746           Op.getOperand(0).hasOneUse() &&
8747           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8748           Op.getOperand(1).hasOneUse());
8749 }
8750
8751 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8752 // 1 and that the SETCC node has a single use.
8753 static bool isXor1OfSetCC(SDValue Op) {
8754   if (Op.getOpcode() != ISD::XOR)
8755     return false;
8756   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8757   if (N1C && N1C->getAPIntValue() == 1) {
8758     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8759       Op.getOperand(0).hasOneUse();
8760   }
8761   return false;
8762 }
8763
8764 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8765   bool addTest = true;
8766   SDValue Chain = Op.getOperand(0);
8767   SDValue Cond  = Op.getOperand(1);
8768   SDValue Dest  = Op.getOperand(2);
8769   DebugLoc dl = Op.getDebugLoc();
8770   SDValue CC;
8771
8772   if (Cond.getOpcode() == ISD::SETCC) {
8773     SDValue NewCond = LowerSETCC(Cond, DAG);
8774     if (NewCond.getNode())
8775       Cond = NewCond;
8776   }
8777 #if 0
8778   // FIXME: LowerXALUO doesn't handle these!!
8779   else if (Cond.getOpcode() == X86ISD::ADD  ||
8780            Cond.getOpcode() == X86ISD::SUB  ||
8781            Cond.getOpcode() == X86ISD::SMUL ||
8782            Cond.getOpcode() == X86ISD::UMUL)
8783     Cond = LowerXALUO(Cond, DAG);
8784 #endif
8785
8786   // Look pass (and (setcc_carry (cmp ...)), 1).
8787   if (Cond.getOpcode() == ISD::AND &&
8788       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8789     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8790     if (C && C->getAPIntValue() == 1)
8791       Cond = Cond.getOperand(0);
8792   }
8793
8794   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8795   // setting operand in place of the X86ISD::SETCC.
8796   if (Cond.getOpcode() == X86ISD::SETCC ||
8797       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8798     CC = Cond.getOperand(0);
8799
8800     SDValue Cmp = Cond.getOperand(1);
8801     unsigned Opc = Cmp.getOpcode();
8802     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8803     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8804       Cond = Cmp;
8805       addTest = false;
8806     } else {
8807       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8808       default: break;
8809       case X86::COND_O:
8810       case X86::COND_B:
8811         // These can only come from an arithmetic instruction with overflow,
8812         // e.g. SADDO, UADDO.
8813         Cond = Cond.getNode()->getOperand(1);
8814         addTest = false;
8815         break;
8816       }
8817     }
8818   } else {
8819     unsigned CondOpc;
8820     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8821       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8822       if (CondOpc == ISD::OR) {
8823         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8824         // two branches instead of an explicit OR instruction with a
8825         // separate test.
8826         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8827             isX86LogicalCmp(Cmp)) {
8828           CC = Cond.getOperand(0).getOperand(0);
8829           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8830                               Chain, Dest, CC, Cmp);
8831           CC = Cond.getOperand(1).getOperand(0);
8832           Cond = Cmp;
8833           addTest = false;
8834         }
8835       } else { // ISD::AND
8836         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8837         // two branches instead of an explicit AND instruction with a
8838         // separate test. However, we only do this if this block doesn't
8839         // have a fall-through edge, because this requires an explicit
8840         // jmp when the condition is false.
8841         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8842             isX86LogicalCmp(Cmp) &&
8843             Op.getNode()->hasOneUse()) {
8844           X86::CondCode CCode =
8845             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8846           CCode = X86::GetOppositeBranchCondition(CCode);
8847           CC = DAG.getConstant(CCode, MVT::i8);
8848           SDNode *User = *Op.getNode()->use_begin();
8849           // Look for an unconditional branch following this conditional branch.
8850           // We need this because we need to reverse the successors in order
8851           // to implement FCMP_OEQ.
8852           if (User->getOpcode() == ISD::BR) {
8853             SDValue FalseBB = User->getOperand(1);
8854             SDNode *NewBR =
8855               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8856             assert(NewBR == User);
8857             (void)NewBR;
8858             Dest = FalseBB;
8859
8860             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8861                                 Chain, Dest, CC, Cmp);
8862             X86::CondCode CCode =
8863               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8864             CCode = X86::GetOppositeBranchCondition(CCode);
8865             CC = DAG.getConstant(CCode, MVT::i8);
8866             Cond = Cmp;
8867             addTest = false;
8868           }
8869         }
8870       }
8871     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8872       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8873       // It should be transformed during dag combiner except when the condition
8874       // is set by a arithmetics with overflow node.
8875       X86::CondCode CCode =
8876         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8877       CCode = X86::GetOppositeBranchCondition(CCode);
8878       CC = DAG.getConstant(CCode, MVT::i8);
8879       Cond = Cond.getOperand(0).getOperand(1);
8880       addTest = false;
8881     }
8882   }
8883
8884   if (addTest) {
8885     // Look pass the truncate.
8886     if (Cond.getOpcode() == ISD::TRUNCATE)
8887       Cond = Cond.getOperand(0);
8888
8889     // We know the result of AND is compared against zero. Try to match
8890     // it to BT.
8891     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8892       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8893       if (NewSetCC.getNode()) {
8894         CC = NewSetCC.getOperand(0);
8895         Cond = NewSetCC.getOperand(1);
8896         addTest = false;
8897       }
8898     }
8899   }
8900
8901   if (addTest) {
8902     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8903     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8904   }
8905   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8906                      Chain, Dest, CC, Cond);
8907 }
8908
8909
8910 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8911 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8912 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8913 // that the guard pages used by the OS virtual memory manager are allocated in
8914 // correct sequence.
8915 SDValue
8916 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8917                                            SelectionDAG &DAG) const {
8918   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8919           EnableSegmentedStacks) &&
8920          "This should be used only on Windows targets or when segmented stacks "
8921          "are being used");
8922   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8923   DebugLoc dl = Op.getDebugLoc();
8924
8925   // Get the inputs.
8926   SDValue Chain = Op.getOperand(0);
8927   SDValue Size  = Op.getOperand(1);
8928   // FIXME: Ensure alignment here
8929
8930   bool Is64Bit = Subtarget->is64Bit();
8931   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8932
8933   if (EnableSegmentedStacks) {
8934     MachineFunction &MF = DAG.getMachineFunction();
8935     MachineRegisterInfo &MRI = MF.getRegInfo();
8936
8937     if (Is64Bit) {
8938       // The 64 bit implementation of segmented stacks needs to clobber both r10
8939       // r11. This makes it impossible to use it along with nested parameters.
8940       const Function *F = MF.getFunction();
8941
8942       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8943            I != E; I++)
8944         if (I->hasNestAttr())
8945           report_fatal_error("Cannot use segmented stacks with functions that "
8946                              "have nested arguments.");
8947     }
8948
8949     const TargetRegisterClass *AddrRegClass =
8950       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8951     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8952     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8953     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8954                                 DAG.getRegister(Vreg, SPTy));
8955     SDValue Ops1[2] = { Value, Chain };
8956     return DAG.getMergeValues(Ops1, 2, dl);
8957   } else {
8958     SDValue Flag;
8959     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8960
8961     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8962     Flag = Chain.getValue(1);
8963     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8964
8965     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8966     Flag = Chain.getValue(1);
8967
8968     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8969
8970     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8971     return DAG.getMergeValues(Ops1, 2, dl);
8972   }
8973 }
8974
8975 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8976   MachineFunction &MF = DAG.getMachineFunction();
8977   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8978
8979   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8980   DebugLoc DL = Op.getDebugLoc();
8981
8982   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8983     // vastart just stores the address of the VarArgsFrameIndex slot into the
8984     // memory location argument.
8985     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8986                                    getPointerTy());
8987     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8988                         MachinePointerInfo(SV), false, false, 0);
8989   }
8990
8991   // __va_list_tag:
8992   //   gp_offset         (0 - 6 * 8)
8993   //   fp_offset         (48 - 48 + 8 * 16)
8994   //   overflow_arg_area (point to parameters coming in memory).
8995   //   reg_save_area
8996   SmallVector<SDValue, 8> MemOps;
8997   SDValue FIN = Op.getOperand(1);
8998   // Store gp_offset
8999   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9000                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9001                                                MVT::i32),
9002                                FIN, MachinePointerInfo(SV), false, false, 0);
9003   MemOps.push_back(Store);
9004
9005   // Store fp_offset
9006   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9007                     FIN, DAG.getIntPtrConstant(4));
9008   Store = DAG.getStore(Op.getOperand(0), DL,
9009                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9010                                        MVT::i32),
9011                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9012   MemOps.push_back(Store);
9013
9014   // Store ptr to overflow_arg_area
9015   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9016                     FIN, DAG.getIntPtrConstant(4));
9017   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9018                                     getPointerTy());
9019   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9020                        MachinePointerInfo(SV, 8),
9021                        false, false, 0);
9022   MemOps.push_back(Store);
9023
9024   // Store ptr to reg_save_area.
9025   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9026                     FIN, DAG.getIntPtrConstant(8));
9027   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9028                                     getPointerTy());
9029   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9030                        MachinePointerInfo(SV, 16), false, false, 0);
9031   MemOps.push_back(Store);
9032   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9033                      &MemOps[0], MemOps.size());
9034 }
9035
9036 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9037   assert(Subtarget->is64Bit() &&
9038          "LowerVAARG only handles 64-bit va_arg!");
9039   assert((Subtarget->isTargetLinux() ||
9040           Subtarget->isTargetDarwin()) &&
9041           "Unhandled target in LowerVAARG");
9042   assert(Op.getNode()->getNumOperands() == 4);
9043   SDValue Chain = Op.getOperand(0);
9044   SDValue SrcPtr = Op.getOperand(1);
9045   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9046   unsigned Align = Op.getConstantOperandVal(3);
9047   DebugLoc dl = Op.getDebugLoc();
9048
9049   EVT ArgVT = Op.getNode()->getValueType(0);
9050   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9051   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9052   uint8_t ArgMode;
9053
9054   // Decide which area this value should be read from.
9055   // TODO: Implement the AMD64 ABI in its entirety. This simple
9056   // selection mechanism works only for the basic types.
9057   if (ArgVT == MVT::f80) {
9058     llvm_unreachable("va_arg for f80 not yet implemented");
9059   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9060     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9061   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9062     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9063   } else {
9064     llvm_unreachable("Unhandled argument type in LowerVAARG");
9065   }
9066
9067   if (ArgMode == 2) {
9068     // Sanity Check: Make sure using fp_offset makes sense.
9069     assert(!UseSoftFloat &&
9070            !(DAG.getMachineFunction()
9071                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9072            Subtarget->hasXMM());
9073   }
9074
9075   // Insert VAARG_64 node into the DAG
9076   // VAARG_64 returns two values: Variable Argument Address, Chain
9077   SmallVector<SDValue, 11> InstOps;
9078   InstOps.push_back(Chain);
9079   InstOps.push_back(SrcPtr);
9080   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9081   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9082   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9083   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9084   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9085                                           VTs, &InstOps[0], InstOps.size(),
9086                                           MVT::i64,
9087                                           MachinePointerInfo(SV),
9088                                           /*Align=*/0,
9089                                           /*Volatile=*/false,
9090                                           /*ReadMem=*/true,
9091                                           /*WriteMem=*/true);
9092   Chain = VAARG.getValue(1);
9093
9094   // Load the next argument and return it
9095   return DAG.getLoad(ArgVT, dl,
9096                      Chain,
9097                      VAARG,
9098                      MachinePointerInfo(),
9099                      false, false, 0);
9100 }
9101
9102 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9103   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9104   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9105   SDValue Chain = Op.getOperand(0);
9106   SDValue DstPtr = Op.getOperand(1);
9107   SDValue SrcPtr = Op.getOperand(2);
9108   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9109   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9110   DebugLoc DL = Op.getDebugLoc();
9111
9112   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9113                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9114                        false,
9115                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9116 }
9117
9118 SDValue
9119 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9120   DebugLoc dl = Op.getDebugLoc();
9121   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9122   switch (IntNo) {
9123   default: return SDValue();    // Don't custom lower most intrinsics.
9124   // Comparison intrinsics.
9125   case Intrinsic::x86_sse_comieq_ss:
9126   case Intrinsic::x86_sse_comilt_ss:
9127   case Intrinsic::x86_sse_comile_ss:
9128   case Intrinsic::x86_sse_comigt_ss:
9129   case Intrinsic::x86_sse_comige_ss:
9130   case Intrinsic::x86_sse_comineq_ss:
9131   case Intrinsic::x86_sse_ucomieq_ss:
9132   case Intrinsic::x86_sse_ucomilt_ss:
9133   case Intrinsic::x86_sse_ucomile_ss:
9134   case Intrinsic::x86_sse_ucomigt_ss:
9135   case Intrinsic::x86_sse_ucomige_ss:
9136   case Intrinsic::x86_sse_ucomineq_ss:
9137   case Intrinsic::x86_sse2_comieq_sd:
9138   case Intrinsic::x86_sse2_comilt_sd:
9139   case Intrinsic::x86_sse2_comile_sd:
9140   case Intrinsic::x86_sse2_comigt_sd:
9141   case Intrinsic::x86_sse2_comige_sd:
9142   case Intrinsic::x86_sse2_comineq_sd:
9143   case Intrinsic::x86_sse2_ucomieq_sd:
9144   case Intrinsic::x86_sse2_ucomilt_sd:
9145   case Intrinsic::x86_sse2_ucomile_sd:
9146   case Intrinsic::x86_sse2_ucomigt_sd:
9147   case Intrinsic::x86_sse2_ucomige_sd:
9148   case Intrinsic::x86_sse2_ucomineq_sd: {
9149     unsigned Opc = 0;
9150     ISD::CondCode CC = ISD::SETCC_INVALID;
9151     switch (IntNo) {
9152     default: break;
9153     case Intrinsic::x86_sse_comieq_ss:
9154     case Intrinsic::x86_sse2_comieq_sd:
9155       Opc = X86ISD::COMI;
9156       CC = ISD::SETEQ;
9157       break;
9158     case Intrinsic::x86_sse_comilt_ss:
9159     case Intrinsic::x86_sse2_comilt_sd:
9160       Opc = X86ISD::COMI;
9161       CC = ISD::SETLT;
9162       break;
9163     case Intrinsic::x86_sse_comile_ss:
9164     case Intrinsic::x86_sse2_comile_sd:
9165       Opc = X86ISD::COMI;
9166       CC = ISD::SETLE;
9167       break;
9168     case Intrinsic::x86_sse_comigt_ss:
9169     case Intrinsic::x86_sse2_comigt_sd:
9170       Opc = X86ISD::COMI;
9171       CC = ISD::SETGT;
9172       break;
9173     case Intrinsic::x86_sse_comige_ss:
9174     case Intrinsic::x86_sse2_comige_sd:
9175       Opc = X86ISD::COMI;
9176       CC = ISD::SETGE;
9177       break;
9178     case Intrinsic::x86_sse_comineq_ss:
9179     case Intrinsic::x86_sse2_comineq_sd:
9180       Opc = X86ISD::COMI;
9181       CC = ISD::SETNE;
9182       break;
9183     case Intrinsic::x86_sse_ucomieq_ss:
9184     case Intrinsic::x86_sse2_ucomieq_sd:
9185       Opc = X86ISD::UCOMI;
9186       CC = ISD::SETEQ;
9187       break;
9188     case Intrinsic::x86_sse_ucomilt_ss:
9189     case Intrinsic::x86_sse2_ucomilt_sd:
9190       Opc = X86ISD::UCOMI;
9191       CC = ISD::SETLT;
9192       break;
9193     case Intrinsic::x86_sse_ucomile_ss:
9194     case Intrinsic::x86_sse2_ucomile_sd:
9195       Opc = X86ISD::UCOMI;
9196       CC = ISD::SETLE;
9197       break;
9198     case Intrinsic::x86_sse_ucomigt_ss:
9199     case Intrinsic::x86_sse2_ucomigt_sd:
9200       Opc = X86ISD::UCOMI;
9201       CC = ISD::SETGT;
9202       break;
9203     case Intrinsic::x86_sse_ucomige_ss:
9204     case Intrinsic::x86_sse2_ucomige_sd:
9205       Opc = X86ISD::UCOMI;
9206       CC = ISD::SETGE;
9207       break;
9208     case Intrinsic::x86_sse_ucomineq_ss:
9209     case Intrinsic::x86_sse2_ucomineq_sd:
9210       Opc = X86ISD::UCOMI;
9211       CC = ISD::SETNE;
9212       break;
9213     }
9214
9215     SDValue LHS = Op.getOperand(1);
9216     SDValue RHS = Op.getOperand(2);
9217     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9218     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9219     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9220     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9221                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9222     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9223   }
9224   // ptest and testp intrinsics. The intrinsic these come from are designed to
9225   // return an integer value, not just an instruction so lower it to the ptest
9226   // or testp pattern and a setcc for the result.
9227   case Intrinsic::x86_sse41_ptestz:
9228   case Intrinsic::x86_sse41_ptestc:
9229   case Intrinsic::x86_sse41_ptestnzc:
9230   case Intrinsic::x86_avx_ptestz_256:
9231   case Intrinsic::x86_avx_ptestc_256:
9232   case Intrinsic::x86_avx_ptestnzc_256:
9233   case Intrinsic::x86_avx_vtestz_ps:
9234   case Intrinsic::x86_avx_vtestc_ps:
9235   case Intrinsic::x86_avx_vtestnzc_ps:
9236   case Intrinsic::x86_avx_vtestz_pd:
9237   case Intrinsic::x86_avx_vtestc_pd:
9238   case Intrinsic::x86_avx_vtestnzc_pd:
9239   case Intrinsic::x86_avx_vtestz_ps_256:
9240   case Intrinsic::x86_avx_vtestc_ps_256:
9241   case Intrinsic::x86_avx_vtestnzc_ps_256:
9242   case Intrinsic::x86_avx_vtestz_pd_256:
9243   case Intrinsic::x86_avx_vtestc_pd_256:
9244   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9245     bool IsTestPacked = false;
9246     unsigned X86CC = 0;
9247     switch (IntNo) {
9248     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9249     case Intrinsic::x86_avx_vtestz_ps:
9250     case Intrinsic::x86_avx_vtestz_pd:
9251     case Intrinsic::x86_avx_vtestz_ps_256:
9252     case Intrinsic::x86_avx_vtestz_pd_256:
9253       IsTestPacked = true; // Fallthrough
9254     case Intrinsic::x86_sse41_ptestz:
9255     case Intrinsic::x86_avx_ptestz_256:
9256       // ZF = 1
9257       X86CC = X86::COND_E;
9258       break;
9259     case Intrinsic::x86_avx_vtestc_ps:
9260     case Intrinsic::x86_avx_vtestc_pd:
9261     case Intrinsic::x86_avx_vtestc_ps_256:
9262     case Intrinsic::x86_avx_vtestc_pd_256:
9263       IsTestPacked = true; // Fallthrough
9264     case Intrinsic::x86_sse41_ptestc:
9265     case Intrinsic::x86_avx_ptestc_256:
9266       // CF = 1
9267       X86CC = X86::COND_B;
9268       break;
9269     case Intrinsic::x86_avx_vtestnzc_ps:
9270     case Intrinsic::x86_avx_vtestnzc_pd:
9271     case Intrinsic::x86_avx_vtestnzc_ps_256:
9272     case Intrinsic::x86_avx_vtestnzc_pd_256:
9273       IsTestPacked = true; // Fallthrough
9274     case Intrinsic::x86_sse41_ptestnzc:
9275     case Intrinsic::x86_avx_ptestnzc_256:
9276       // ZF and CF = 0
9277       X86CC = X86::COND_A;
9278       break;
9279     }
9280
9281     SDValue LHS = Op.getOperand(1);
9282     SDValue RHS = Op.getOperand(2);
9283     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9284     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9285     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9286     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9287     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9288   }
9289
9290   // Fix vector shift instructions where the last operand is a non-immediate
9291   // i32 value.
9292   case Intrinsic::x86_sse2_pslli_w:
9293   case Intrinsic::x86_sse2_pslli_d:
9294   case Intrinsic::x86_sse2_pslli_q:
9295   case Intrinsic::x86_sse2_psrli_w:
9296   case Intrinsic::x86_sse2_psrli_d:
9297   case Intrinsic::x86_sse2_psrli_q:
9298   case Intrinsic::x86_sse2_psrai_w:
9299   case Intrinsic::x86_sse2_psrai_d:
9300   case Intrinsic::x86_mmx_pslli_w:
9301   case Intrinsic::x86_mmx_pslli_d:
9302   case Intrinsic::x86_mmx_pslli_q:
9303   case Intrinsic::x86_mmx_psrli_w:
9304   case Intrinsic::x86_mmx_psrli_d:
9305   case Intrinsic::x86_mmx_psrli_q:
9306   case Intrinsic::x86_mmx_psrai_w:
9307   case Intrinsic::x86_mmx_psrai_d: {
9308     SDValue ShAmt = Op.getOperand(2);
9309     if (isa<ConstantSDNode>(ShAmt))
9310       return SDValue();
9311
9312     unsigned NewIntNo = 0;
9313     EVT ShAmtVT = MVT::v4i32;
9314     switch (IntNo) {
9315     case Intrinsic::x86_sse2_pslli_w:
9316       NewIntNo = Intrinsic::x86_sse2_psll_w;
9317       break;
9318     case Intrinsic::x86_sse2_pslli_d:
9319       NewIntNo = Intrinsic::x86_sse2_psll_d;
9320       break;
9321     case Intrinsic::x86_sse2_pslli_q:
9322       NewIntNo = Intrinsic::x86_sse2_psll_q;
9323       break;
9324     case Intrinsic::x86_sse2_psrli_w:
9325       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9326       break;
9327     case Intrinsic::x86_sse2_psrli_d:
9328       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9329       break;
9330     case Intrinsic::x86_sse2_psrli_q:
9331       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9332       break;
9333     case Intrinsic::x86_sse2_psrai_w:
9334       NewIntNo = Intrinsic::x86_sse2_psra_w;
9335       break;
9336     case Intrinsic::x86_sse2_psrai_d:
9337       NewIntNo = Intrinsic::x86_sse2_psra_d;
9338       break;
9339     default: {
9340       ShAmtVT = MVT::v2i32;
9341       switch (IntNo) {
9342       case Intrinsic::x86_mmx_pslli_w:
9343         NewIntNo = Intrinsic::x86_mmx_psll_w;
9344         break;
9345       case Intrinsic::x86_mmx_pslli_d:
9346         NewIntNo = Intrinsic::x86_mmx_psll_d;
9347         break;
9348       case Intrinsic::x86_mmx_pslli_q:
9349         NewIntNo = Intrinsic::x86_mmx_psll_q;
9350         break;
9351       case Intrinsic::x86_mmx_psrli_w:
9352         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9353         break;
9354       case Intrinsic::x86_mmx_psrli_d:
9355         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9356         break;
9357       case Intrinsic::x86_mmx_psrli_q:
9358         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9359         break;
9360       case Intrinsic::x86_mmx_psrai_w:
9361         NewIntNo = Intrinsic::x86_mmx_psra_w;
9362         break;
9363       case Intrinsic::x86_mmx_psrai_d:
9364         NewIntNo = Intrinsic::x86_mmx_psra_d;
9365         break;
9366       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9367       }
9368       break;
9369     }
9370     }
9371
9372     // The vector shift intrinsics with scalars uses 32b shift amounts but
9373     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9374     // to be zero.
9375     SDValue ShOps[4];
9376     ShOps[0] = ShAmt;
9377     ShOps[1] = DAG.getConstant(0, MVT::i32);
9378     if (ShAmtVT == MVT::v4i32) {
9379       ShOps[2] = DAG.getUNDEF(MVT::i32);
9380       ShOps[3] = DAG.getUNDEF(MVT::i32);
9381       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9382     } else {
9383       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9384 // FIXME this must be lowered to get rid of the invalid type.
9385     }
9386
9387     EVT VT = Op.getValueType();
9388     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9389     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9390                        DAG.getConstant(NewIntNo, MVT::i32),
9391                        Op.getOperand(1), ShAmt);
9392   }
9393   }
9394 }
9395
9396 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9397                                            SelectionDAG &DAG) const {
9398   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9399   MFI->setReturnAddressIsTaken(true);
9400
9401   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9402   DebugLoc dl = Op.getDebugLoc();
9403
9404   if (Depth > 0) {
9405     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9406     SDValue Offset =
9407       DAG.getConstant(TD->getPointerSize(),
9408                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9409     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9410                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9411                                    FrameAddr, Offset),
9412                        MachinePointerInfo(), false, false, 0);
9413   }
9414
9415   // Just load the return address.
9416   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9417   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9418                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9419 }
9420
9421 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9422   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9423   MFI->setFrameAddressIsTaken(true);
9424
9425   EVT VT = Op.getValueType();
9426   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9427   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9428   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9429   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9430   while (Depth--)
9431     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9432                             MachinePointerInfo(),
9433                             false, false, 0);
9434   return FrameAddr;
9435 }
9436
9437 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9438                                                      SelectionDAG &DAG) const {
9439   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9440 }
9441
9442 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9443   MachineFunction &MF = DAG.getMachineFunction();
9444   SDValue Chain     = Op.getOperand(0);
9445   SDValue Offset    = Op.getOperand(1);
9446   SDValue Handler   = Op.getOperand(2);
9447   DebugLoc dl       = Op.getDebugLoc();
9448
9449   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9450                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9451                                      getPointerTy());
9452   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9453
9454   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9455                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9456   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9457   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9458                        false, false, 0);
9459   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9460   MF.getRegInfo().addLiveOut(StoreAddrReg);
9461
9462   return DAG.getNode(X86ISD::EH_RETURN, dl,
9463                      MVT::Other,
9464                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9465 }
9466
9467 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9468                                                   SelectionDAG &DAG) const {
9469   return Op.getOperand(0);
9470 }
9471
9472 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9473                                                 SelectionDAG &DAG) const {
9474   SDValue Root = Op.getOperand(0);
9475   SDValue Trmp = Op.getOperand(1); // trampoline
9476   SDValue FPtr = Op.getOperand(2); // nested function
9477   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9478   DebugLoc dl  = Op.getDebugLoc();
9479
9480   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9481
9482   if (Subtarget->is64Bit()) {
9483     SDValue OutChains[6];
9484
9485     // Large code-model.
9486     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9487     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9488
9489     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9490     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9491
9492     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9493
9494     // Load the pointer to the nested function into R11.
9495     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9496     SDValue Addr = Trmp;
9497     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9498                                 Addr, MachinePointerInfo(TrmpAddr),
9499                                 false, false, 0);
9500
9501     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9502                        DAG.getConstant(2, MVT::i64));
9503     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9504                                 MachinePointerInfo(TrmpAddr, 2),
9505                                 false, false, 2);
9506
9507     // Load the 'nest' parameter value into R10.
9508     // R10 is specified in X86CallingConv.td
9509     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9510     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9511                        DAG.getConstant(10, MVT::i64));
9512     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9513                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9514                                 false, false, 0);
9515
9516     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9517                        DAG.getConstant(12, MVT::i64));
9518     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9519                                 MachinePointerInfo(TrmpAddr, 12),
9520                                 false, false, 2);
9521
9522     // Jump to the nested function.
9523     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9524     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9525                        DAG.getConstant(20, MVT::i64));
9526     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9527                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9528                                 false, false, 0);
9529
9530     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9531     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9532                        DAG.getConstant(22, MVT::i64));
9533     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9534                                 MachinePointerInfo(TrmpAddr, 22),
9535                                 false, false, 0);
9536
9537     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9538   } else {
9539     const Function *Func =
9540       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9541     CallingConv::ID CC = Func->getCallingConv();
9542     unsigned NestReg;
9543
9544     switch (CC) {
9545     default:
9546       llvm_unreachable("Unsupported calling convention");
9547     case CallingConv::C:
9548     case CallingConv::X86_StdCall: {
9549       // Pass 'nest' parameter in ECX.
9550       // Must be kept in sync with X86CallingConv.td
9551       NestReg = X86::ECX;
9552
9553       // Check that ECX wasn't needed by an 'inreg' parameter.
9554       FunctionType *FTy = Func->getFunctionType();
9555       const AttrListPtr &Attrs = Func->getAttributes();
9556
9557       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9558         unsigned InRegCount = 0;
9559         unsigned Idx = 1;
9560
9561         for (FunctionType::param_iterator I = FTy->param_begin(),
9562              E = FTy->param_end(); I != E; ++I, ++Idx)
9563           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9564             // FIXME: should only count parameters that are lowered to integers.
9565             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9566
9567         if (InRegCount > 2) {
9568           report_fatal_error("Nest register in use - reduce number of inreg"
9569                              " parameters!");
9570         }
9571       }
9572       break;
9573     }
9574     case CallingConv::X86_FastCall:
9575     case CallingConv::X86_ThisCall:
9576     case CallingConv::Fast:
9577       // Pass 'nest' parameter in EAX.
9578       // Must be kept in sync with X86CallingConv.td
9579       NestReg = X86::EAX;
9580       break;
9581     }
9582
9583     SDValue OutChains[4];
9584     SDValue Addr, Disp;
9585
9586     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9587                        DAG.getConstant(10, MVT::i32));
9588     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9589
9590     // This is storing the opcode for MOV32ri.
9591     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9592     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9593     OutChains[0] = DAG.getStore(Root, dl,
9594                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9595                                 Trmp, MachinePointerInfo(TrmpAddr),
9596                                 false, false, 0);
9597
9598     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9599                        DAG.getConstant(1, MVT::i32));
9600     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9601                                 MachinePointerInfo(TrmpAddr, 1),
9602                                 false, false, 1);
9603
9604     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9605     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9606                        DAG.getConstant(5, MVT::i32));
9607     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9608                                 MachinePointerInfo(TrmpAddr, 5),
9609                                 false, false, 1);
9610
9611     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9612                        DAG.getConstant(6, MVT::i32));
9613     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9614                                 MachinePointerInfo(TrmpAddr, 6),
9615                                 false, false, 1);
9616
9617     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9618   }
9619 }
9620
9621 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9622                                             SelectionDAG &DAG) const {
9623   /*
9624    The rounding mode is in bits 11:10 of FPSR, and has the following
9625    settings:
9626      00 Round to nearest
9627      01 Round to -inf
9628      10 Round to +inf
9629      11 Round to 0
9630
9631   FLT_ROUNDS, on the other hand, expects the following:
9632     -1 Undefined
9633      0 Round to 0
9634      1 Round to nearest
9635      2 Round to +inf
9636      3 Round to -inf
9637
9638   To perform the conversion, we do:
9639     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9640   */
9641
9642   MachineFunction &MF = DAG.getMachineFunction();
9643   const TargetMachine &TM = MF.getTarget();
9644   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9645   unsigned StackAlignment = TFI.getStackAlignment();
9646   EVT VT = Op.getValueType();
9647   DebugLoc DL = Op.getDebugLoc();
9648
9649   // Save FP Control Word to stack slot
9650   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9651   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9652
9653
9654   MachineMemOperand *MMO =
9655    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9656                            MachineMemOperand::MOStore, 2, 2);
9657
9658   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9659   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9660                                           DAG.getVTList(MVT::Other),
9661                                           Ops, 2, MVT::i16, MMO);
9662
9663   // Load FP Control Word from stack slot
9664   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9665                             MachinePointerInfo(), false, false, 0);
9666
9667   // Transform as necessary
9668   SDValue CWD1 =
9669     DAG.getNode(ISD::SRL, DL, MVT::i16,
9670                 DAG.getNode(ISD::AND, DL, MVT::i16,
9671                             CWD, DAG.getConstant(0x800, MVT::i16)),
9672                 DAG.getConstant(11, MVT::i8));
9673   SDValue CWD2 =
9674     DAG.getNode(ISD::SRL, DL, MVT::i16,
9675                 DAG.getNode(ISD::AND, DL, MVT::i16,
9676                             CWD, DAG.getConstant(0x400, MVT::i16)),
9677                 DAG.getConstant(9, MVT::i8));
9678
9679   SDValue RetVal =
9680     DAG.getNode(ISD::AND, DL, MVT::i16,
9681                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9682                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9683                             DAG.getConstant(1, MVT::i16)),
9684                 DAG.getConstant(3, MVT::i16));
9685
9686
9687   return DAG.getNode((VT.getSizeInBits() < 16 ?
9688                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9689 }
9690
9691 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9692   EVT VT = Op.getValueType();
9693   EVT OpVT = VT;
9694   unsigned NumBits = VT.getSizeInBits();
9695   DebugLoc dl = Op.getDebugLoc();
9696
9697   Op = Op.getOperand(0);
9698   if (VT == MVT::i8) {
9699     // Zero extend to i32 since there is not an i8 bsr.
9700     OpVT = MVT::i32;
9701     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9702   }
9703
9704   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9705   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9706   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9707
9708   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9709   SDValue Ops[] = {
9710     Op,
9711     DAG.getConstant(NumBits+NumBits-1, OpVT),
9712     DAG.getConstant(X86::COND_E, MVT::i8),
9713     Op.getValue(1)
9714   };
9715   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9716
9717   // Finally xor with NumBits-1.
9718   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9719
9720   if (VT == MVT::i8)
9721     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9722   return Op;
9723 }
9724
9725 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9726   EVT VT = Op.getValueType();
9727   EVT OpVT = VT;
9728   unsigned NumBits = VT.getSizeInBits();
9729   DebugLoc dl = Op.getDebugLoc();
9730
9731   Op = Op.getOperand(0);
9732   if (VT == MVT::i8) {
9733     OpVT = MVT::i32;
9734     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9735   }
9736
9737   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9738   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9739   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9740
9741   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9742   SDValue Ops[] = {
9743     Op,
9744     DAG.getConstant(NumBits, OpVT),
9745     DAG.getConstant(X86::COND_E, MVT::i8),
9746     Op.getValue(1)
9747   };
9748   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9749
9750   if (VT == MVT::i8)
9751     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9752   return Op;
9753 }
9754
9755 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9756 // ones, and then concatenate the result back.
9757 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9758   EVT VT = Op.getValueType();
9759
9760   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9761          "Unsupported value type for operation");
9762
9763   int NumElems = VT.getVectorNumElements();
9764   DebugLoc dl = Op.getDebugLoc();
9765   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9766   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9767
9768   // Extract the LHS vectors
9769   SDValue LHS = Op.getOperand(0);
9770   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9771   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9772
9773   // Extract the RHS vectors
9774   SDValue RHS = Op.getOperand(1);
9775   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9776   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9777
9778   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9779   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9780
9781   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9782                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9783                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9784 }
9785
9786 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9787   assert(Op.getValueType().getSizeInBits() == 256 &&
9788          Op.getValueType().isInteger() &&
9789          "Only handle AVX 256-bit vector integer operation");
9790   return Lower256IntArith(Op, DAG);
9791 }
9792
9793 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9794   assert(Op.getValueType().getSizeInBits() == 256 &&
9795          Op.getValueType().isInteger() &&
9796          "Only handle AVX 256-bit vector integer operation");
9797   return Lower256IntArith(Op, DAG);
9798 }
9799
9800 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9801   EVT VT = Op.getValueType();
9802
9803   // Decompose 256-bit ops into smaller 128-bit ops.
9804   if (VT.getSizeInBits() == 256)
9805     return Lower256IntArith(Op, DAG);
9806
9807   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9808   DebugLoc dl = Op.getDebugLoc();
9809
9810   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9811   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9812   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9813   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9814   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9815   //
9816   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9817   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9818   //  return AloBlo + AloBhi + AhiBlo;
9819
9820   SDValue A = Op.getOperand(0);
9821   SDValue B = Op.getOperand(1);
9822
9823   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9824                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9825                        A, DAG.getConstant(32, MVT::i32));
9826   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9827                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9828                        B, DAG.getConstant(32, MVT::i32));
9829   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9830                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9831                        A, B);
9832   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9833                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9834                        A, Bhi);
9835   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9836                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9837                        Ahi, B);
9838   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9839                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9840                        AloBhi, DAG.getConstant(32, MVT::i32));
9841   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9842                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9843                        AhiBlo, DAG.getConstant(32, MVT::i32));
9844   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9845   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9846   return Res;
9847 }
9848
9849 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9850
9851   EVT VT = Op.getValueType();
9852   DebugLoc dl = Op.getDebugLoc();
9853   SDValue R = Op.getOperand(0);
9854   SDValue Amt = Op.getOperand(1);
9855   LLVMContext *Context = DAG.getContext();
9856
9857   if (!Subtarget->hasXMMInt())
9858     return SDValue();
9859
9860   // Decompose 256-bit shifts into smaller 128-bit shifts.
9861   if (VT.getSizeInBits() == 256) {
9862     int NumElems = VT.getVectorNumElements();
9863     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9864     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9865
9866     // Extract the two vectors
9867     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9868     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9869                                      DAG, dl);
9870
9871     // Recreate the shift amount vectors
9872     SDValue Amt1, Amt2;
9873     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9874       // Constant shift amount
9875       SmallVector<SDValue, 4> Amt1Csts;
9876       SmallVector<SDValue, 4> Amt2Csts;
9877       for (int i = 0; i < NumElems/2; ++i)
9878         Amt1Csts.push_back(Amt->getOperand(i));
9879       for (int i = NumElems/2; i < NumElems; ++i)
9880         Amt2Csts.push_back(Amt->getOperand(i));
9881
9882       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9883                                  &Amt1Csts[0], NumElems/2);
9884       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9885                                  &Amt2Csts[0], NumElems/2);
9886     } else {
9887       // Variable shift amount
9888       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9889       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9890                                  DAG, dl);
9891     }
9892
9893     // Issue new vector shifts for the smaller types
9894     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9895     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9896
9897     // Concatenate the result back
9898     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9899   }
9900
9901   // Optimize shl/srl/sra with constant shift amount.
9902   if (isSplatVector(Amt.getNode())) {
9903     SDValue SclrAmt = Amt->getOperand(0);
9904     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9905       uint64_t ShiftAmt = C->getZExtValue();
9906
9907       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9908        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9909                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9910                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9911
9912       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9913        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9914                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9915                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9916
9917       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9918        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9919                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9920                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9921
9922       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9923        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9924                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9925                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9926
9927       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9928        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9929                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9930                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9931
9932       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9933        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9934                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9935                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9936
9937       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9938        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9939                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9940                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9941
9942       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9943        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9944                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9945                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9946     }
9947   }
9948
9949   // Lower SHL with variable shift amount.
9950   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9951     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9952                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9953                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9954
9955     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9956
9957     std::vector<Constant*> CV(4, CI);
9958     Constant *C = ConstantVector::get(CV);
9959     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9960     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9961                                  MachinePointerInfo::getConstantPool(),
9962                                  false, false, 16);
9963
9964     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9965     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9966     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9967     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9968   }
9969   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9970     // a = a << 5;
9971     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9972                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9973                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9974
9975     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9976     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9977
9978     std::vector<Constant*> CVM1(16, CM1);
9979     std::vector<Constant*> CVM2(16, CM2);
9980     Constant *C = ConstantVector::get(CVM1);
9981     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9982     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9983                             MachinePointerInfo::getConstantPool(),
9984                             false, false, 16);
9985
9986     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9987     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9988     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9989                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9990                     DAG.getConstant(4, MVT::i32));
9991     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9992     // a += a
9993     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9994
9995     C = ConstantVector::get(CVM2);
9996     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9997     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9998                     MachinePointerInfo::getConstantPool(),
9999                     false, false, 16);
10000
10001     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10002     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10003     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10004                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10005                     DAG.getConstant(2, MVT::i32));
10006     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10007     // a += a
10008     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10009
10010     // return pblendv(r, r+r, a);
10011     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10012                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10013     return R;
10014   }
10015   return SDValue();
10016 }
10017
10018 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10019   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10020   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10021   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10022   // has only one use.
10023   SDNode *N = Op.getNode();
10024   SDValue LHS = N->getOperand(0);
10025   SDValue RHS = N->getOperand(1);
10026   unsigned BaseOp = 0;
10027   unsigned Cond = 0;
10028   DebugLoc DL = Op.getDebugLoc();
10029   switch (Op.getOpcode()) {
10030   default: llvm_unreachable("Unknown ovf instruction!");
10031   case ISD::SADDO:
10032     // A subtract of one will be selected as a INC. Note that INC doesn't
10033     // set CF, so we can't do this for UADDO.
10034     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10035       if (C->isOne()) {
10036         BaseOp = X86ISD::INC;
10037         Cond = X86::COND_O;
10038         break;
10039       }
10040     BaseOp = X86ISD::ADD;
10041     Cond = X86::COND_O;
10042     break;
10043   case ISD::UADDO:
10044     BaseOp = X86ISD::ADD;
10045     Cond = X86::COND_B;
10046     break;
10047   case ISD::SSUBO:
10048     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10049     // set CF, so we can't do this for USUBO.
10050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10051       if (C->isOne()) {
10052         BaseOp = X86ISD::DEC;
10053         Cond = X86::COND_O;
10054         break;
10055       }
10056     BaseOp = X86ISD::SUB;
10057     Cond = X86::COND_O;
10058     break;
10059   case ISD::USUBO:
10060     BaseOp = X86ISD::SUB;
10061     Cond = X86::COND_B;
10062     break;
10063   case ISD::SMULO:
10064     BaseOp = X86ISD::SMUL;
10065     Cond = X86::COND_O;
10066     break;
10067   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10068     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10069                                  MVT::i32);
10070     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10071
10072     SDValue SetCC =
10073       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10074                   DAG.getConstant(X86::COND_O, MVT::i32),
10075                   SDValue(Sum.getNode(), 2));
10076
10077     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10078   }
10079   }
10080
10081   // Also sets EFLAGS.
10082   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10083   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10084
10085   SDValue SetCC =
10086     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10087                 DAG.getConstant(Cond, MVT::i32),
10088                 SDValue(Sum.getNode(), 1));
10089
10090   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10091 }
10092
10093 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10094   DebugLoc dl = Op.getDebugLoc();
10095   SDNode* Node = Op.getNode();
10096   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10097   EVT VT = Node->getValueType(0);
10098   if (Subtarget->hasXMMInt() && VT.isVector()) {
10099     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10100                         ExtraVT.getScalarType().getSizeInBits();
10101     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10102
10103     unsigned SHLIntrinsicsID = 0;
10104     unsigned SRAIntrinsicsID = 0;
10105     switch (VT.getSimpleVT().SimpleTy) {
10106       default:
10107         return SDValue();
10108       case MVT::v2i64: {
10109         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10110         SRAIntrinsicsID = 0;
10111         break;
10112       }
10113       case MVT::v4i32: {
10114         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10115         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10116         break;
10117       }
10118       case MVT::v8i16: {
10119         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10120         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10121         break;
10122       }
10123     }
10124
10125     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10126                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10127                          Node->getOperand(0), ShAmt);
10128
10129     // In case of 1 bit sext, no need to shr
10130     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10131
10132     if (SRAIntrinsicsID) {
10133       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10134                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10135                          Tmp1, ShAmt);
10136     }
10137     return Tmp1;
10138   }
10139
10140   return SDValue();
10141 }
10142
10143
10144 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10145   DebugLoc dl = Op.getDebugLoc();
10146
10147   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10148   // There isn't any reason to disable it if the target processor supports it.
10149   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10150     SDValue Chain = Op.getOperand(0);
10151     SDValue Zero = DAG.getConstant(0, MVT::i32);
10152     SDValue Ops[] = {
10153       DAG.getRegister(X86::ESP, MVT::i32), // Base
10154       DAG.getTargetConstant(1, MVT::i8),   // Scale
10155       DAG.getRegister(0, MVT::i32),        // Index
10156       DAG.getTargetConstant(0, MVT::i32),  // Disp
10157       DAG.getRegister(0, MVT::i32),        // Segment.
10158       Zero,
10159       Chain
10160     };
10161     SDNode *Res =
10162       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10163                           array_lengthof(Ops));
10164     return SDValue(Res, 0);
10165   }
10166
10167   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10168   if (!isDev)
10169     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10170
10171   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10172   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10173   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10174   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10175
10176   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10177   if (!Op1 && !Op2 && !Op3 && Op4)
10178     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10179
10180   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10181   if (Op1 && !Op2 && !Op3 && !Op4)
10182     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10183
10184   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10185   //           (MFENCE)>;
10186   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10187 }
10188
10189 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10190                                              SelectionDAG &DAG) const {
10191   DebugLoc dl = Op.getDebugLoc();
10192   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10193     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10194   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10195     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10196
10197   // The only fence that needs an instruction is a sequentially-consistent
10198   // cross-thread fence.
10199   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10200     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10201     // no-sse2). There isn't any reason to disable it if the target processor
10202     // supports it.
10203     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10204       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10205
10206     SDValue Chain = Op.getOperand(0);
10207     SDValue Zero = DAG.getConstant(0, MVT::i32);
10208     SDValue Ops[] = {
10209       DAG.getRegister(X86::ESP, MVT::i32), // Base
10210       DAG.getTargetConstant(1, MVT::i8),   // Scale
10211       DAG.getRegister(0, MVT::i32),        // Index
10212       DAG.getTargetConstant(0, MVT::i32),  // Disp
10213       DAG.getRegister(0, MVT::i32),        // Segment.
10214       Zero,
10215       Chain
10216     };
10217     SDNode *Res =
10218       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10219                          array_lengthof(Ops));
10220     return SDValue(Res, 0);
10221   }
10222
10223   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10224   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10225 }
10226
10227
10228 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10229   EVT T = Op.getValueType();
10230   DebugLoc DL = Op.getDebugLoc();
10231   unsigned Reg = 0;
10232   unsigned size = 0;
10233   switch(T.getSimpleVT().SimpleTy) {
10234   default:
10235     assert(false && "Invalid value type!");
10236   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10237   case MVT::i16: Reg = X86::AX;  size = 2; break;
10238   case MVT::i32: Reg = X86::EAX; size = 4; break;
10239   case MVT::i64:
10240     assert(Subtarget->is64Bit() && "Node not type legal!");
10241     Reg = X86::RAX; size = 8;
10242     break;
10243   }
10244   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10245                                     Op.getOperand(2), SDValue());
10246   SDValue Ops[] = { cpIn.getValue(0),
10247                     Op.getOperand(1),
10248                     Op.getOperand(3),
10249                     DAG.getTargetConstant(size, MVT::i8),
10250                     cpIn.getValue(1) };
10251   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10252   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10253   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10254                                            Ops, 5, T, MMO);
10255   SDValue cpOut =
10256     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10257   return cpOut;
10258 }
10259
10260 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10261                                                  SelectionDAG &DAG) const {
10262   assert(Subtarget->is64Bit() && "Result not type legalized?");
10263   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10264   SDValue TheChain = Op.getOperand(0);
10265   DebugLoc dl = Op.getDebugLoc();
10266   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10267   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10268   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10269                                    rax.getValue(2));
10270   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10271                             DAG.getConstant(32, MVT::i8));
10272   SDValue Ops[] = {
10273     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10274     rdx.getValue(1)
10275   };
10276   return DAG.getMergeValues(Ops, 2, dl);
10277 }
10278
10279 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10280                                             SelectionDAG &DAG) const {
10281   EVT SrcVT = Op.getOperand(0).getValueType();
10282   EVT DstVT = Op.getValueType();
10283   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10284          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10285   assert((DstVT == MVT::i64 ||
10286           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10287          "Unexpected custom BITCAST");
10288   // i64 <=> MMX conversions are Legal.
10289   if (SrcVT==MVT::i64 && DstVT.isVector())
10290     return Op;
10291   if (DstVT==MVT::i64 && SrcVT.isVector())
10292     return Op;
10293   // MMX <=> MMX conversions are Legal.
10294   if (SrcVT.isVector() && DstVT.isVector())
10295     return Op;
10296   // All other conversions need to be expanded.
10297   return SDValue();
10298 }
10299
10300 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10301   SDNode *Node = Op.getNode();
10302   DebugLoc dl = Node->getDebugLoc();
10303   EVT T = Node->getValueType(0);
10304   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10305                               DAG.getConstant(0, T), Node->getOperand(2));
10306   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10307                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10308                        Node->getOperand(0),
10309                        Node->getOperand(1), negOp,
10310                        cast<AtomicSDNode>(Node)->getSrcValue(),
10311                        cast<AtomicSDNode>(Node)->getAlignment(),
10312                        cast<AtomicSDNode>(Node)->getOrdering(),
10313                        cast<AtomicSDNode>(Node)->getSynchScope());
10314 }
10315
10316 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10317   SDNode *Node = Op.getNode();
10318   DebugLoc dl = Node->getDebugLoc();
10319   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10320
10321   // Convert seq_cst store -> xchg
10322   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10323   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10324   //        (The only way to get a 16-byte store is cmpxchg16b)
10325   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10326   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10327       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10328     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10329                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10330                                  Node->getOperand(0),
10331                                  Node->getOperand(1), Node->getOperand(2),
10332                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10333                                  cast<AtomicSDNode>(Node)->getOrdering(),
10334                                  cast<AtomicSDNode>(Node)->getSynchScope());
10335     return Swap.getValue(1);
10336   }
10337   // Other atomic stores have a simple pattern.
10338   return Op;
10339 }
10340
10341 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10342   EVT VT = Op.getNode()->getValueType(0);
10343
10344   // Let legalize expand this if it isn't a legal type yet.
10345   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10346     return SDValue();
10347
10348   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10349
10350   unsigned Opc;
10351   bool ExtraOp = false;
10352   switch (Op.getOpcode()) {
10353   default: assert(0 && "Invalid code");
10354   case ISD::ADDC: Opc = X86ISD::ADD; break;
10355   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10356   case ISD::SUBC: Opc = X86ISD::SUB; break;
10357   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10358   }
10359
10360   if (!ExtraOp)
10361     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10362                        Op.getOperand(1));
10363   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10364                      Op.getOperand(1), Op.getOperand(2));
10365 }
10366
10367 /// LowerOperation - Provide custom lowering hooks for some operations.
10368 ///
10369 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10370   switch (Op.getOpcode()) {
10371   default: llvm_unreachable("Should not custom lower this!");
10372   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10373   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10374   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10375   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10376   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10377   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10378   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10379   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10380   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10381   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10382   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10383   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10384   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10385   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10386   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10387   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10388   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10389   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10390   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10391   case ISD::SHL_PARTS:
10392   case ISD::SRA_PARTS:
10393   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10394   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10395   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10396   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10397   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10398   case ISD::FABS:               return LowerFABS(Op, DAG);
10399   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10400   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10401   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10402   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10403   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10404   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10405   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10406   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10407   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10408   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10409   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10410   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10411   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10412   case ISD::FRAME_TO_ARGS_OFFSET:
10413                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10414   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10415   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10416   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10417   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10418   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10419   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10420   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10421   case ISD::MUL:                return LowerMUL(Op, DAG);
10422   case ISD::SRA:
10423   case ISD::SRL:
10424   case ISD::SHL:                return LowerShift(Op, DAG);
10425   case ISD::SADDO:
10426   case ISD::UADDO:
10427   case ISD::SSUBO:
10428   case ISD::USUBO:
10429   case ISD::SMULO:
10430   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10431   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10432   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10433   case ISD::ADDC:
10434   case ISD::ADDE:
10435   case ISD::SUBC:
10436   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10437   case ISD::ADD:                return LowerADD(Op, DAG);
10438   case ISD::SUB:                return LowerSUB(Op, DAG);
10439   }
10440 }
10441
10442 static void ReplaceATOMIC_LOAD(SDNode *Node,
10443                                   SmallVectorImpl<SDValue> &Results,
10444                                   SelectionDAG &DAG) {
10445   DebugLoc dl = Node->getDebugLoc();
10446   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10447
10448   // Convert wide load -> cmpxchg8b/cmpxchg16b
10449   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10450   //        (The only way to get a 16-byte load is cmpxchg16b)
10451   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10452   SDValue Zero = DAG.getConstant(0, VT);
10453   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10454                                Node->getOperand(0),
10455                                Node->getOperand(1), Zero, Zero,
10456                                cast<AtomicSDNode>(Node)->getMemOperand(),
10457                                cast<AtomicSDNode>(Node)->getOrdering(),
10458                                cast<AtomicSDNode>(Node)->getSynchScope());
10459   Results.push_back(Swap.getValue(0));
10460   Results.push_back(Swap.getValue(1));
10461 }
10462
10463 void X86TargetLowering::
10464 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10465                         SelectionDAG &DAG, unsigned NewOp) const {
10466   EVT T = Node->getValueType(0);
10467   DebugLoc dl = Node->getDebugLoc();
10468   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10469
10470   SDValue Chain = Node->getOperand(0);
10471   SDValue In1 = Node->getOperand(1);
10472   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10473                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10474   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10475                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10476   SDValue Ops[] = { Chain, In1, In2L, In2H };
10477   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10478   SDValue Result =
10479     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10480                             cast<MemSDNode>(Node)->getMemOperand());
10481   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10482   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10483   Results.push_back(Result.getValue(2));
10484 }
10485
10486 /// ReplaceNodeResults - Replace a node with an illegal result type
10487 /// with a new node built out of custom code.
10488 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10489                                            SmallVectorImpl<SDValue>&Results,
10490                                            SelectionDAG &DAG) const {
10491   DebugLoc dl = N->getDebugLoc();
10492   switch (N->getOpcode()) {
10493   default:
10494     assert(false && "Do not know how to custom type legalize this operation!");
10495     return;
10496   case ISD::SIGN_EXTEND_INREG:
10497   case ISD::ADDC:
10498   case ISD::ADDE:
10499   case ISD::SUBC:
10500   case ISD::SUBE:
10501     // We don't want to expand or promote these.
10502     return;
10503   case ISD::FP_TO_SINT: {
10504     std::pair<SDValue,SDValue> Vals =
10505         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10506     SDValue FIST = Vals.first, StackSlot = Vals.second;
10507     if (FIST.getNode() != 0) {
10508       EVT VT = N->getValueType(0);
10509       // Return a load from the stack slot.
10510       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10511                                     MachinePointerInfo(), false, false, 0));
10512     }
10513     return;
10514   }
10515   case ISD::READCYCLECOUNTER: {
10516     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10517     SDValue TheChain = N->getOperand(0);
10518     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10519     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10520                                      rd.getValue(1));
10521     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10522                                      eax.getValue(2));
10523     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10524     SDValue Ops[] = { eax, edx };
10525     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10526     Results.push_back(edx.getValue(1));
10527     return;
10528   }
10529   case ISD::ATOMIC_CMP_SWAP: {
10530     EVT T = N->getValueType(0);
10531     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10532     bool Regs64bit = T == MVT::i128;
10533     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10534     SDValue cpInL, cpInH;
10535     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10536                         DAG.getConstant(0, HalfT));
10537     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10538                         DAG.getConstant(1, HalfT));
10539     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10540                              Regs64bit ? X86::RAX : X86::EAX,
10541                              cpInL, SDValue());
10542     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10543                              Regs64bit ? X86::RDX : X86::EDX,
10544                              cpInH, cpInL.getValue(1));
10545     SDValue swapInL, swapInH;
10546     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10547                           DAG.getConstant(0, HalfT));
10548     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10549                           DAG.getConstant(1, HalfT));
10550     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10551                                Regs64bit ? X86::RBX : X86::EBX,
10552                                swapInL, cpInH.getValue(1));
10553     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10554                                Regs64bit ? X86::RCX : X86::ECX, 
10555                                swapInH, swapInL.getValue(1));
10556     SDValue Ops[] = { swapInH.getValue(0),
10557                       N->getOperand(1),
10558                       swapInH.getValue(1) };
10559     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10560     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10561     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10562                                   X86ISD::LCMPXCHG8_DAG;
10563     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10564                                              Ops, 3, T, MMO);
10565     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10566                                         Regs64bit ? X86::RAX : X86::EAX,
10567                                         HalfT, Result.getValue(1));
10568     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10569                                         Regs64bit ? X86::RDX : X86::EDX,
10570                                         HalfT, cpOutL.getValue(2));
10571     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10572     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10573     Results.push_back(cpOutH.getValue(1));
10574     return;
10575   }
10576   case ISD::ATOMIC_LOAD_ADD:
10577     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10578     return;
10579   case ISD::ATOMIC_LOAD_AND:
10580     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10581     return;
10582   case ISD::ATOMIC_LOAD_NAND:
10583     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10584     return;
10585   case ISD::ATOMIC_LOAD_OR:
10586     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10587     return;
10588   case ISD::ATOMIC_LOAD_SUB:
10589     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10590     return;
10591   case ISD::ATOMIC_LOAD_XOR:
10592     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10593     return;
10594   case ISD::ATOMIC_SWAP:
10595     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10596     return;
10597   case ISD::ATOMIC_LOAD:
10598     ReplaceATOMIC_LOAD(N, Results, DAG);
10599   }
10600 }
10601
10602 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10603   switch (Opcode) {
10604   default: return NULL;
10605   case X86ISD::BSF:                return "X86ISD::BSF";
10606   case X86ISD::BSR:                return "X86ISD::BSR";
10607   case X86ISD::SHLD:               return "X86ISD::SHLD";
10608   case X86ISD::SHRD:               return "X86ISD::SHRD";
10609   case X86ISD::FAND:               return "X86ISD::FAND";
10610   case X86ISD::FOR:                return "X86ISD::FOR";
10611   case X86ISD::FXOR:               return "X86ISD::FXOR";
10612   case X86ISD::FSRL:               return "X86ISD::FSRL";
10613   case X86ISD::FILD:               return "X86ISD::FILD";
10614   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10615   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10616   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10617   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10618   case X86ISD::FLD:                return "X86ISD::FLD";
10619   case X86ISD::FST:                return "X86ISD::FST";
10620   case X86ISD::CALL:               return "X86ISD::CALL";
10621   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10622   case X86ISD::BT:                 return "X86ISD::BT";
10623   case X86ISD::CMP:                return "X86ISD::CMP";
10624   case X86ISD::COMI:               return "X86ISD::COMI";
10625   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10626   case X86ISD::SETCC:              return "X86ISD::SETCC";
10627   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10628   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10629   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10630   case X86ISD::CMOV:               return "X86ISD::CMOV";
10631   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10632   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10633   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10634   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10635   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10636   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10637   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10638   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10639   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10640   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10641   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10642   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10643   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10644   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10645   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10646   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10647   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10648   case X86ISD::FMAX:               return "X86ISD::FMAX";
10649   case X86ISD::FMIN:               return "X86ISD::FMIN";
10650   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10651   case X86ISD::FRCP:               return "X86ISD::FRCP";
10652   case X86ISD::FHADD:              return "X86ISD::FHADD";
10653   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10654   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10655   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10656   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10657   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10658   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10659   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10660   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10661   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10662   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10663   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10664   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10665   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10666   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10667   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10668   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10669   case X86ISD::VSHL:               return "X86ISD::VSHL";
10670   case X86ISD::VSRL:               return "X86ISD::VSRL";
10671   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10672   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10673   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10674   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10675   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10676   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10677   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10678   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10679   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10680   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10681   case X86ISD::ADD:                return "X86ISD::ADD";
10682   case X86ISD::SUB:                return "X86ISD::SUB";
10683   case X86ISD::ADC:                return "X86ISD::ADC";
10684   case X86ISD::SBB:                return "X86ISD::SBB";
10685   case X86ISD::SMUL:               return "X86ISD::SMUL";
10686   case X86ISD::UMUL:               return "X86ISD::UMUL";
10687   case X86ISD::INC:                return "X86ISD::INC";
10688   case X86ISD::DEC:                return "X86ISD::DEC";
10689   case X86ISD::OR:                 return "X86ISD::OR";
10690   case X86ISD::XOR:                return "X86ISD::XOR";
10691   case X86ISD::AND:                return "X86ISD::AND";
10692   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10693   case X86ISD::PTEST:              return "X86ISD::PTEST";
10694   case X86ISD::TESTP:              return "X86ISD::TESTP";
10695   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10696   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10697   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10698   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10699   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10700   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10701   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10702   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10703   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10704   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10705   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10706   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10707   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10708   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10709   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10710   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10711   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10712   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10713   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10714   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10715   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10716   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10717   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10718   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10719   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10720   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10721   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10722   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10723   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10724   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10725   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10726   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10727   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10728   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10729   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10730   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10731   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10732   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10733   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10734   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10735   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10736   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10737   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10738   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10739   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10740   }
10741 }
10742
10743 // isLegalAddressingMode - Return true if the addressing mode represented
10744 // by AM is legal for this target, for a load/store of the specified type.
10745 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10746                                               Type *Ty) const {
10747   // X86 supports extremely general addressing modes.
10748   CodeModel::Model M = getTargetMachine().getCodeModel();
10749   Reloc::Model R = getTargetMachine().getRelocationModel();
10750
10751   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10752   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10753     return false;
10754
10755   if (AM.BaseGV) {
10756     unsigned GVFlags =
10757       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10758
10759     // If a reference to this global requires an extra load, we can't fold it.
10760     if (isGlobalStubReference(GVFlags))
10761       return false;
10762
10763     // If BaseGV requires a register for the PIC base, we cannot also have a
10764     // BaseReg specified.
10765     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10766       return false;
10767
10768     // If lower 4G is not available, then we must use rip-relative addressing.
10769     if ((M != CodeModel::Small || R != Reloc::Static) &&
10770         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10771       return false;
10772   }
10773
10774   switch (AM.Scale) {
10775   case 0:
10776   case 1:
10777   case 2:
10778   case 4:
10779   case 8:
10780     // These scales always work.
10781     break;
10782   case 3:
10783   case 5:
10784   case 9:
10785     // These scales are formed with basereg+scalereg.  Only accept if there is
10786     // no basereg yet.
10787     if (AM.HasBaseReg)
10788       return false;
10789     break;
10790   default:  // Other stuff never works.
10791     return false;
10792   }
10793
10794   return true;
10795 }
10796
10797
10798 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10799   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10800     return false;
10801   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10802   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10803   if (NumBits1 <= NumBits2)
10804     return false;
10805   return true;
10806 }
10807
10808 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10809   if (!VT1.isInteger() || !VT2.isInteger())
10810     return false;
10811   unsigned NumBits1 = VT1.getSizeInBits();
10812   unsigned NumBits2 = VT2.getSizeInBits();
10813   if (NumBits1 <= NumBits2)
10814     return false;
10815   return true;
10816 }
10817
10818 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10819   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10820   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10821 }
10822
10823 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10824   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10825   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10826 }
10827
10828 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10829   // i16 instructions are longer (0x66 prefix) and potentially slower.
10830   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10831 }
10832
10833 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10834 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10835 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10836 /// are assumed to be legal.
10837 bool
10838 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10839                                       EVT VT) const {
10840   // Very little shuffling can be done for 64-bit vectors right now.
10841   if (VT.getSizeInBits() == 64)
10842     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
10843
10844   // FIXME: pshufb, blends, shifts.
10845   return (VT.getVectorNumElements() == 2 ||
10846           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10847           isMOVLMask(M, VT) ||
10848           isSHUFPMask(M, VT) ||
10849           isPSHUFDMask(M, VT) ||
10850           isPSHUFHWMask(M, VT) ||
10851           isPSHUFLWMask(M, VT) ||
10852           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
10853           isUNPCKLMask(M, VT) ||
10854           isUNPCKHMask(M, VT) ||
10855           isUNPCKL_v_undef_Mask(M, VT) ||
10856           isUNPCKH_v_undef_Mask(M, VT));
10857 }
10858
10859 bool
10860 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10861                                           EVT VT) const {
10862   unsigned NumElts = VT.getVectorNumElements();
10863   // FIXME: This collection of masks seems suspect.
10864   if (NumElts == 2)
10865     return true;
10866   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10867     return (isMOVLMask(Mask, VT)  ||
10868             isCommutedMOVLMask(Mask, VT, true) ||
10869             isSHUFPMask(Mask, VT) ||
10870             isCommutedSHUFPMask(Mask, VT));
10871   }
10872   return false;
10873 }
10874
10875 //===----------------------------------------------------------------------===//
10876 //                           X86 Scheduler Hooks
10877 //===----------------------------------------------------------------------===//
10878
10879 // private utility function
10880 MachineBasicBlock *
10881 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10882                                                        MachineBasicBlock *MBB,
10883                                                        unsigned regOpc,
10884                                                        unsigned immOpc,
10885                                                        unsigned LoadOpc,
10886                                                        unsigned CXchgOpc,
10887                                                        unsigned notOpc,
10888                                                        unsigned EAXreg,
10889                                                        TargetRegisterClass *RC,
10890                                                        bool invSrc) const {
10891   // For the atomic bitwise operator, we generate
10892   //   thisMBB:
10893   //   newMBB:
10894   //     ld  t1 = [bitinstr.addr]
10895   //     op  t2 = t1, [bitinstr.val]
10896   //     mov EAX = t1
10897   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10898   //     bz  newMBB
10899   //     fallthrough -->nextMBB
10900   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10901   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10902   MachineFunction::iterator MBBIter = MBB;
10903   ++MBBIter;
10904
10905   /// First build the CFG
10906   MachineFunction *F = MBB->getParent();
10907   MachineBasicBlock *thisMBB = MBB;
10908   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10909   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10910   F->insert(MBBIter, newMBB);
10911   F->insert(MBBIter, nextMBB);
10912
10913   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10914   nextMBB->splice(nextMBB->begin(), thisMBB,
10915                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10916                   thisMBB->end());
10917   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10918
10919   // Update thisMBB to fall through to newMBB
10920   thisMBB->addSuccessor(newMBB);
10921
10922   // newMBB jumps to itself and fall through to nextMBB
10923   newMBB->addSuccessor(nextMBB);
10924   newMBB->addSuccessor(newMBB);
10925
10926   // Insert instructions into newMBB based on incoming instruction
10927   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10928          "unexpected number of operands");
10929   DebugLoc dl = bInstr->getDebugLoc();
10930   MachineOperand& destOper = bInstr->getOperand(0);
10931   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10932   int numArgs = bInstr->getNumOperands() - 1;
10933   for (int i=0; i < numArgs; ++i)
10934     argOpers[i] = &bInstr->getOperand(i+1);
10935
10936   // x86 address has 4 operands: base, index, scale, and displacement
10937   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10938   int valArgIndx = lastAddrIndx + 1;
10939
10940   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10941   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10942   for (int i=0; i <= lastAddrIndx; ++i)
10943     (*MIB).addOperand(*argOpers[i]);
10944
10945   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10946   if (invSrc) {
10947     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10948   }
10949   else
10950     tt = t1;
10951
10952   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10953   assert((argOpers[valArgIndx]->isReg() ||
10954           argOpers[valArgIndx]->isImm()) &&
10955          "invalid operand");
10956   if (argOpers[valArgIndx]->isReg())
10957     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10958   else
10959     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10960   MIB.addReg(tt);
10961   (*MIB).addOperand(*argOpers[valArgIndx]);
10962
10963   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10964   MIB.addReg(t1);
10965
10966   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10967   for (int i=0; i <= lastAddrIndx; ++i)
10968     (*MIB).addOperand(*argOpers[i]);
10969   MIB.addReg(t2);
10970   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10971   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10972                     bInstr->memoperands_end());
10973
10974   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10975   MIB.addReg(EAXreg);
10976
10977   // insert branch
10978   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10979
10980   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10981   return nextMBB;
10982 }
10983
10984 // private utility function:  64 bit atomics on 32 bit host.
10985 MachineBasicBlock *
10986 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10987                                                        MachineBasicBlock *MBB,
10988                                                        unsigned regOpcL,
10989                                                        unsigned regOpcH,
10990                                                        unsigned immOpcL,
10991                                                        unsigned immOpcH,
10992                                                        bool invSrc) const {
10993   // For the atomic bitwise operator, we generate
10994   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10995   //     ld t1,t2 = [bitinstr.addr]
10996   //   newMBB:
10997   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10998   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10999   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11000   //     mov ECX, EBX <- t5, t6
11001   //     mov EAX, EDX <- t1, t2
11002   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11003   //     mov t3, t4 <- EAX, EDX
11004   //     bz  newMBB
11005   //     result in out1, out2
11006   //     fallthrough -->nextMBB
11007
11008   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11009   const unsigned LoadOpc = X86::MOV32rm;
11010   const unsigned NotOpc = X86::NOT32r;
11011   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11012   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11013   MachineFunction::iterator MBBIter = MBB;
11014   ++MBBIter;
11015
11016   /// First build the CFG
11017   MachineFunction *F = MBB->getParent();
11018   MachineBasicBlock *thisMBB = MBB;
11019   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11020   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11021   F->insert(MBBIter, newMBB);
11022   F->insert(MBBIter, nextMBB);
11023
11024   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11025   nextMBB->splice(nextMBB->begin(), thisMBB,
11026                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11027                   thisMBB->end());
11028   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11029
11030   // Update thisMBB to fall through to newMBB
11031   thisMBB->addSuccessor(newMBB);
11032
11033   // newMBB jumps to itself and fall through to nextMBB
11034   newMBB->addSuccessor(nextMBB);
11035   newMBB->addSuccessor(newMBB);
11036
11037   DebugLoc dl = bInstr->getDebugLoc();
11038   // Insert instructions into newMBB based on incoming instruction
11039   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11040   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11041          "unexpected number of operands");
11042   MachineOperand& dest1Oper = bInstr->getOperand(0);
11043   MachineOperand& dest2Oper = bInstr->getOperand(1);
11044   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11045   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11046     argOpers[i] = &bInstr->getOperand(i+2);
11047
11048     // We use some of the operands multiple times, so conservatively just
11049     // clear any kill flags that might be present.
11050     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11051       argOpers[i]->setIsKill(false);
11052   }
11053
11054   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11055   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11056
11057   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11058   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11059   for (int i=0; i <= lastAddrIndx; ++i)
11060     (*MIB).addOperand(*argOpers[i]);
11061   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11062   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11063   // add 4 to displacement.
11064   for (int i=0; i <= lastAddrIndx-2; ++i)
11065     (*MIB).addOperand(*argOpers[i]);
11066   MachineOperand newOp3 = *(argOpers[3]);
11067   if (newOp3.isImm())
11068     newOp3.setImm(newOp3.getImm()+4);
11069   else
11070     newOp3.setOffset(newOp3.getOffset()+4);
11071   (*MIB).addOperand(newOp3);
11072   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11073
11074   // t3/4 are defined later, at the bottom of the loop
11075   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11076   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11077   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11078     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11079   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11080     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11081
11082   // The subsequent operations should be using the destination registers of
11083   //the PHI instructions.
11084   if (invSrc) {
11085     t1 = F->getRegInfo().createVirtualRegister(RC);
11086     t2 = F->getRegInfo().createVirtualRegister(RC);
11087     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11088     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11089   } else {
11090     t1 = dest1Oper.getReg();
11091     t2 = dest2Oper.getReg();
11092   }
11093
11094   int valArgIndx = lastAddrIndx + 1;
11095   assert((argOpers[valArgIndx]->isReg() ||
11096           argOpers[valArgIndx]->isImm()) &&
11097          "invalid operand");
11098   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11099   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11100   if (argOpers[valArgIndx]->isReg())
11101     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11102   else
11103     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11104   if (regOpcL != X86::MOV32rr)
11105     MIB.addReg(t1);
11106   (*MIB).addOperand(*argOpers[valArgIndx]);
11107   assert(argOpers[valArgIndx + 1]->isReg() ==
11108          argOpers[valArgIndx]->isReg());
11109   assert(argOpers[valArgIndx + 1]->isImm() ==
11110          argOpers[valArgIndx]->isImm());
11111   if (argOpers[valArgIndx + 1]->isReg())
11112     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11113   else
11114     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11115   if (regOpcH != X86::MOV32rr)
11116     MIB.addReg(t2);
11117   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11118
11119   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11120   MIB.addReg(t1);
11121   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11122   MIB.addReg(t2);
11123
11124   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11125   MIB.addReg(t5);
11126   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11127   MIB.addReg(t6);
11128
11129   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11130   for (int i=0; i <= lastAddrIndx; ++i)
11131     (*MIB).addOperand(*argOpers[i]);
11132
11133   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11134   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11135                     bInstr->memoperands_end());
11136
11137   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11138   MIB.addReg(X86::EAX);
11139   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11140   MIB.addReg(X86::EDX);
11141
11142   // insert branch
11143   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11144
11145   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11146   return nextMBB;
11147 }
11148
11149 // private utility function
11150 MachineBasicBlock *
11151 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11152                                                       MachineBasicBlock *MBB,
11153                                                       unsigned cmovOpc) const {
11154   // For the atomic min/max operator, we generate
11155   //   thisMBB:
11156   //   newMBB:
11157   //     ld t1 = [min/max.addr]
11158   //     mov t2 = [min/max.val]
11159   //     cmp  t1, t2
11160   //     cmov[cond] t2 = t1
11161   //     mov EAX = t1
11162   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11163   //     bz   newMBB
11164   //     fallthrough -->nextMBB
11165   //
11166   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11167   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11168   MachineFunction::iterator MBBIter = MBB;
11169   ++MBBIter;
11170
11171   /// First build the CFG
11172   MachineFunction *F = MBB->getParent();
11173   MachineBasicBlock *thisMBB = MBB;
11174   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11175   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11176   F->insert(MBBIter, newMBB);
11177   F->insert(MBBIter, nextMBB);
11178
11179   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11180   nextMBB->splice(nextMBB->begin(), thisMBB,
11181                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11182                   thisMBB->end());
11183   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11184
11185   // Update thisMBB to fall through to newMBB
11186   thisMBB->addSuccessor(newMBB);
11187
11188   // newMBB jumps to newMBB and fall through to nextMBB
11189   newMBB->addSuccessor(nextMBB);
11190   newMBB->addSuccessor(newMBB);
11191
11192   DebugLoc dl = mInstr->getDebugLoc();
11193   // Insert instructions into newMBB based on incoming instruction
11194   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11195          "unexpected number of operands");
11196   MachineOperand& destOper = mInstr->getOperand(0);
11197   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11198   int numArgs = mInstr->getNumOperands() - 1;
11199   for (int i=0; i < numArgs; ++i)
11200     argOpers[i] = &mInstr->getOperand(i+1);
11201
11202   // x86 address has 4 operands: base, index, scale, and displacement
11203   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11204   int valArgIndx = lastAddrIndx + 1;
11205
11206   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11207   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11208   for (int i=0; i <= lastAddrIndx; ++i)
11209     (*MIB).addOperand(*argOpers[i]);
11210
11211   // We only support register and immediate values
11212   assert((argOpers[valArgIndx]->isReg() ||
11213           argOpers[valArgIndx]->isImm()) &&
11214          "invalid operand");
11215
11216   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11217   if (argOpers[valArgIndx]->isReg())
11218     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11219   else
11220     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11221   (*MIB).addOperand(*argOpers[valArgIndx]);
11222
11223   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11224   MIB.addReg(t1);
11225
11226   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11227   MIB.addReg(t1);
11228   MIB.addReg(t2);
11229
11230   // Generate movc
11231   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11232   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11233   MIB.addReg(t2);
11234   MIB.addReg(t1);
11235
11236   // Cmp and exchange if none has modified the memory location
11237   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11238   for (int i=0; i <= lastAddrIndx; ++i)
11239     (*MIB).addOperand(*argOpers[i]);
11240   MIB.addReg(t3);
11241   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11242   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11243                     mInstr->memoperands_end());
11244
11245   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11246   MIB.addReg(X86::EAX);
11247
11248   // insert branch
11249   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11250
11251   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11252   return nextMBB;
11253 }
11254
11255 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11256 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11257 // in the .td file.
11258 MachineBasicBlock *
11259 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11260                             unsigned numArgs, bool memArg) const {
11261   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11262          "Target must have SSE4.2 or AVX features enabled");
11263
11264   DebugLoc dl = MI->getDebugLoc();
11265   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11266   unsigned Opc;
11267   if (!Subtarget->hasAVX()) {
11268     if (memArg)
11269       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11270     else
11271       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11272   } else {
11273     if (memArg)
11274       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11275     else
11276       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11277   }
11278
11279   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11280   for (unsigned i = 0; i < numArgs; ++i) {
11281     MachineOperand &Op = MI->getOperand(i+1);
11282     if (!(Op.isReg() && Op.isImplicit()))
11283       MIB.addOperand(Op);
11284   }
11285   BuildMI(*BB, MI, dl,
11286     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11287              MI->getOperand(0).getReg())
11288     .addReg(X86::XMM0);
11289
11290   MI->eraseFromParent();
11291   return BB;
11292 }
11293
11294 MachineBasicBlock *
11295 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11296   DebugLoc dl = MI->getDebugLoc();
11297   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11298
11299   // Address into RAX/EAX, other two args into ECX, EDX.
11300   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11301   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11302   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11303   for (int i = 0; i < X86::AddrNumOperands; ++i)
11304     MIB.addOperand(MI->getOperand(i));
11305
11306   unsigned ValOps = X86::AddrNumOperands;
11307   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11308     .addReg(MI->getOperand(ValOps).getReg());
11309   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11310     .addReg(MI->getOperand(ValOps+1).getReg());
11311
11312   // The instruction doesn't actually take any operands though.
11313   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11314
11315   MI->eraseFromParent(); // The pseudo is gone now.
11316   return BB;
11317 }
11318
11319 MachineBasicBlock *
11320 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11321   DebugLoc dl = MI->getDebugLoc();
11322   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11323
11324   // First arg in ECX, the second in EAX.
11325   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11326     .addReg(MI->getOperand(0).getReg());
11327   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11328     .addReg(MI->getOperand(1).getReg());
11329
11330   // The instruction doesn't actually take any operands though.
11331   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11332
11333   MI->eraseFromParent(); // The pseudo is gone now.
11334   return BB;
11335 }
11336
11337 MachineBasicBlock *
11338 X86TargetLowering::EmitVAARG64WithCustomInserter(
11339                    MachineInstr *MI,
11340                    MachineBasicBlock *MBB) const {
11341   // Emit va_arg instruction on X86-64.
11342
11343   // Operands to this pseudo-instruction:
11344   // 0  ) Output        : destination address (reg)
11345   // 1-5) Input         : va_list address (addr, i64mem)
11346   // 6  ) ArgSize       : Size (in bytes) of vararg type
11347   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11348   // 8  ) Align         : Alignment of type
11349   // 9  ) EFLAGS (implicit-def)
11350
11351   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11352   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11353
11354   unsigned DestReg = MI->getOperand(0).getReg();
11355   MachineOperand &Base = MI->getOperand(1);
11356   MachineOperand &Scale = MI->getOperand(2);
11357   MachineOperand &Index = MI->getOperand(3);
11358   MachineOperand &Disp = MI->getOperand(4);
11359   MachineOperand &Segment = MI->getOperand(5);
11360   unsigned ArgSize = MI->getOperand(6).getImm();
11361   unsigned ArgMode = MI->getOperand(7).getImm();
11362   unsigned Align = MI->getOperand(8).getImm();
11363
11364   // Memory Reference
11365   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11366   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11367   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11368
11369   // Machine Information
11370   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11371   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11372   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11373   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11374   DebugLoc DL = MI->getDebugLoc();
11375
11376   // struct va_list {
11377   //   i32   gp_offset
11378   //   i32   fp_offset
11379   //   i64   overflow_area (address)
11380   //   i64   reg_save_area (address)
11381   // }
11382   // sizeof(va_list) = 24
11383   // alignment(va_list) = 8
11384
11385   unsigned TotalNumIntRegs = 6;
11386   unsigned TotalNumXMMRegs = 8;
11387   bool UseGPOffset = (ArgMode == 1);
11388   bool UseFPOffset = (ArgMode == 2);
11389   unsigned MaxOffset = TotalNumIntRegs * 8 +
11390                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11391
11392   /* Align ArgSize to a multiple of 8 */
11393   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11394   bool NeedsAlign = (Align > 8);
11395
11396   MachineBasicBlock *thisMBB = MBB;
11397   MachineBasicBlock *overflowMBB;
11398   MachineBasicBlock *offsetMBB;
11399   MachineBasicBlock *endMBB;
11400
11401   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11402   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11403   unsigned OffsetReg = 0;
11404
11405   if (!UseGPOffset && !UseFPOffset) {
11406     // If we only pull from the overflow region, we don't create a branch.
11407     // We don't need to alter control flow.
11408     OffsetDestReg = 0; // unused
11409     OverflowDestReg = DestReg;
11410
11411     offsetMBB = NULL;
11412     overflowMBB = thisMBB;
11413     endMBB = thisMBB;
11414   } else {
11415     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11416     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11417     // If not, pull from overflow_area. (branch to overflowMBB)
11418     //
11419     //       thisMBB
11420     //         |     .
11421     //         |        .
11422     //     offsetMBB   overflowMBB
11423     //         |        .
11424     //         |     .
11425     //        endMBB
11426
11427     // Registers for the PHI in endMBB
11428     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11429     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11430
11431     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11432     MachineFunction *MF = MBB->getParent();
11433     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11434     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11435     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11436
11437     MachineFunction::iterator MBBIter = MBB;
11438     ++MBBIter;
11439
11440     // Insert the new basic blocks
11441     MF->insert(MBBIter, offsetMBB);
11442     MF->insert(MBBIter, overflowMBB);
11443     MF->insert(MBBIter, endMBB);
11444
11445     // Transfer the remainder of MBB and its successor edges to endMBB.
11446     endMBB->splice(endMBB->begin(), thisMBB,
11447                     llvm::next(MachineBasicBlock::iterator(MI)),
11448                     thisMBB->end());
11449     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11450
11451     // Make offsetMBB and overflowMBB successors of thisMBB
11452     thisMBB->addSuccessor(offsetMBB);
11453     thisMBB->addSuccessor(overflowMBB);
11454
11455     // endMBB is a successor of both offsetMBB and overflowMBB
11456     offsetMBB->addSuccessor(endMBB);
11457     overflowMBB->addSuccessor(endMBB);
11458
11459     // Load the offset value into a register
11460     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11461     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11462       .addOperand(Base)
11463       .addOperand(Scale)
11464       .addOperand(Index)
11465       .addDisp(Disp, UseFPOffset ? 4 : 0)
11466       .addOperand(Segment)
11467       .setMemRefs(MMOBegin, MMOEnd);
11468
11469     // Check if there is enough room left to pull this argument.
11470     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11471       .addReg(OffsetReg)
11472       .addImm(MaxOffset + 8 - ArgSizeA8);
11473
11474     // Branch to "overflowMBB" if offset >= max
11475     // Fall through to "offsetMBB" otherwise
11476     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11477       .addMBB(overflowMBB);
11478   }
11479
11480   // In offsetMBB, emit code to use the reg_save_area.
11481   if (offsetMBB) {
11482     assert(OffsetReg != 0);
11483
11484     // Read the reg_save_area address.
11485     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11486     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11487       .addOperand(Base)
11488       .addOperand(Scale)
11489       .addOperand(Index)
11490       .addDisp(Disp, 16)
11491       .addOperand(Segment)
11492       .setMemRefs(MMOBegin, MMOEnd);
11493
11494     // Zero-extend the offset
11495     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11496       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11497         .addImm(0)
11498         .addReg(OffsetReg)
11499         .addImm(X86::sub_32bit);
11500
11501     // Add the offset to the reg_save_area to get the final address.
11502     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11503       .addReg(OffsetReg64)
11504       .addReg(RegSaveReg);
11505
11506     // Compute the offset for the next argument
11507     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11508     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11509       .addReg(OffsetReg)
11510       .addImm(UseFPOffset ? 16 : 8);
11511
11512     // Store it back into the va_list.
11513     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11514       .addOperand(Base)
11515       .addOperand(Scale)
11516       .addOperand(Index)
11517       .addDisp(Disp, UseFPOffset ? 4 : 0)
11518       .addOperand(Segment)
11519       .addReg(NextOffsetReg)
11520       .setMemRefs(MMOBegin, MMOEnd);
11521
11522     // Jump to endMBB
11523     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11524       .addMBB(endMBB);
11525   }
11526
11527   //
11528   // Emit code to use overflow area
11529   //
11530
11531   // Load the overflow_area address into a register.
11532   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11533   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11534     .addOperand(Base)
11535     .addOperand(Scale)
11536     .addOperand(Index)
11537     .addDisp(Disp, 8)
11538     .addOperand(Segment)
11539     .setMemRefs(MMOBegin, MMOEnd);
11540
11541   // If we need to align it, do so. Otherwise, just copy the address
11542   // to OverflowDestReg.
11543   if (NeedsAlign) {
11544     // Align the overflow address
11545     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11546     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11547
11548     // aligned_addr = (addr + (align-1)) & ~(align-1)
11549     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11550       .addReg(OverflowAddrReg)
11551       .addImm(Align-1);
11552
11553     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11554       .addReg(TmpReg)
11555       .addImm(~(uint64_t)(Align-1));
11556   } else {
11557     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11558       .addReg(OverflowAddrReg);
11559   }
11560
11561   // Compute the next overflow address after this argument.
11562   // (the overflow address should be kept 8-byte aligned)
11563   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11564   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11565     .addReg(OverflowDestReg)
11566     .addImm(ArgSizeA8);
11567
11568   // Store the new overflow address.
11569   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11570     .addOperand(Base)
11571     .addOperand(Scale)
11572     .addOperand(Index)
11573     .addDisp(Disp, 8)
11574     .addOperand(Segment)
11575     .addReg(NextAddrReg)
11576     .setMemRefs(MMOBegin, MMOEnd);
11577
11578   // If we branched, emit the PHI to the front of endMBB.
11579   if (offsetMBB) {
11580     BuildMI(*endMBB, endMBB->begin(), DL,
11581             TII->get(X86::PHI), DestReg)
11582       .addReg(OffsetDestReg).addMBB(offsetMBB)
11583       .addReg(OverflowDestReg).addMBB(overflowMBB);
11584   }
11585
11586   // Erase the pseudo instruction
11587   MI->eraseFromParent();
11588
11589   return endMBB;
11590 }
11591
11592 MachineBasicBlock *
11593 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11594                                                  MachineInstr *MI,
11595                                                  MachineBasicBlock *MBB) const {
11596   // Emit code to save XMM registers to the stack. The ABI says that the
11597   // number of registers to save is given in %al, so it's theoretically
11598   // possible to do an indirect jump trick to avoid saving all of them,
11599   // however this code takes a simpler approach and just executes all
11600   // of the stores if %al is non-zero. It's less code, and it's probably
11601   // easier on the hardware branch predictor, and stores aren't all that
11602   // expensive anyway.
11603
11604   // Create the new basic blocks. One block contains all the XMM stores,
11605   // and one block is the final destination regardless of whether any
11606   // stores were performed.
11607   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11608   MachineFunction *F = MBB->getParent();
11609   MachineFunction::iterator MBBIter = MBB;
11610   ++MBBIter;
11611   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11612   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11613   F->insert(MBBIter, XMMSaveMBB);
11614   F->insert(MBBIter, EndMBB);
11615
11616   // Transfer the remainder of MBB and its successor edges to EndMBB.
11617   EndMBB->splice(EndMBB->begin(), MBB,
11618                  llvm::next(MachineBasicBlock::iterator(MI)),
11619                  MBB->end());
11620   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11621
11622   // The original block will now fall through to the XMM save block.
11623   MBB->addSuccessor(XMMSaveMBB);
11624   // The XMMSaveMBB will fall through to the end block.
11625   XMMSaveMBB->addSuccessor(EndMBB);
11626
11627   // Now add the instructions.
11628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11629   DebugLoc DL = MI->getDebugLoc();
11630
11631   unsigned CountReg = MI->getOperand(0).getReg();
11632   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11633   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11634
11635   if (!Subtarget->isTargetWin64()) {
11636     // If %al is 0, branch around the XMM save block.
11637     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11638     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11639     MBB->addSuccessor(EndMBB);
11640   }
11641
11642   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11643   // In the XMM save block, save all the XMM argument registers.
11644   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11645     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11646     MachineMemOperand *MMO =
11647       F->getMachineMemOperand(
11648           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11649         MachineMemOperand::MOStore,
11650         /*Size=*/16, /*Align=*/16);
11651     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11652       .addFrameIndex(RegSaveFrameIndex)
11653       .addImm(/*Scale=*/1)
11654       .addReg(/*IndexReg=*/0)
11655       .addImm(/*Disp=*/Offset)
11656       .addReg(/*Segment=*/0)
11657       .addReg(MI->getOperand(i).getReg())
11658       .addMemOperand(MMO);
11659   }
11660
11661   MI->eraseFromParent();   // The pseudo instruction is gone now.
11662
11663   return EndMBB;
11664 }
11665
11666 MachineBasicBlock *
11667 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11668                                      MachineBasicBlock *BB) const {
11669   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11670   DebugLoc DL = MI->getDebugLoc();
11671
11672   // To "insert" a SELECT_CC instruction, we actually have to insert the
11673   // diamond control-flow pattern.  The incoming instruction knows the
11674   // destination vreg to set, the condition code register to branch on, the
11675   // true/false values to select between, and a branch opcode to use.
11676   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11677   MachineFunction::iterator It = BB;
11678   ++It;
11679
11680   //  thisMBB:
11681   //  ...
11682   //   TrueVal = ...
11683   //   cmpTY ccX, r1, r2
11684   //   bCC copy1MBB
11685   //   fallthrough --> copy0MBB
11686   MachineBasicBlock *thisMBB = BB;
11687   MachineFunction *F = BB->getParent();
11688   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11689   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11690   F->insert(It, copy0MBB);
11691   F->insert(It, sinkMBB);
11692
11693   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11694   // live into the sink and copy blocks.
11695   if (!MI->killsRegister(X86::EFLAGS)) {
11696     copy0MBB->addLiveIn(X86::EFLAGS);
11697     sinkMBB->addLiveIn(X86::EFLAGS);
11698   }
11699
11700   // Transfer the remainder of BB and its successor edges to sinkMBB.
11701   sinkMBB->splice(sinkMBB->begin(), BB,
11702                   llvm::next(MachineBasicBlock::iterator(MI)),
11703                   BB->end());
11704   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11705
11706   // Add the true and fallthrough blocks as its successors.
11707   BB->addSuccessor(copy0MBB);
11708   BB->addSuccessor(sinkMBB);
11709
11710   // Create the conditional branch instruction.
11711   unsigned Opc =
11712     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11713   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11714
11715   //  copy0MBB:
11716   //   %FalseValue = ...
11717   //   # fallthrough to sinkMBB
11718   copy0MBB->addSuccessor(sinkMBB);
11719
11720   //  sinkMBB:
11721   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11722   //  ...
11723   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11724           TII->get(X86::PHI), MI->getOperand(0).getReg())
11725     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11726     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11727
11728   MI->eraseFromParent();   // The pseudo instruction is gone now.
11729   return sinkMBB;
11730 }
11731
11732 MachineBasicBlock *
11733 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11734                                         bool Is64Bit) const {
11735   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11736   DebugLoc DL = MI->getDebugLoc();
11737   MachineFunction *MF = BB->getParent();
11738   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11739
11740   assert(EnableSegmentedStacks);
11741
11742   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11743   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11744
11745   // BB:
11746   //  ... [Till the alloca]
11747   // If stacklet is not large enough, jump to mallocMBB
11748   //
11749   // bumpMBB:
11750   //  Allocate by subtracting from RSP
11751   //  Jump to continueMBB
11752   //
11753   // mallocMBB:
11754   //  Allocate by call to runtime
11755   //
11756   // continueMBB:
11757   //  ...
11758   //  [rest of original BB]
11759   //
11760
11761   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11762   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11763   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11764
11765   MachineRegisterInfo &MRI = MF->getRegInfo();
11766   const TargetRegisterClass *AddrRegClass =
11767     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11768
11769   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11770     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11771     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11772     sizeVReg = MI->getOperand(1).getReg(),
11773     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11774
11775   MachineFunction::iterator MBBIter = BB;
11776   ++MBBIter;
11777
11778   MF->insert(MBBIter, bumpMBB);
11779   MF->insert(MBBIter, mallocMBB);
11780   MF->insert(MBBIter, continueMBB);
11781
11782   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11783                       (MachineBasicBlock::iterator(MI)), BB->end());
11784   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11785
11786   // Add code to the main basic block to check if the stack limit has been hit,
11787   // and if so, jump to mallocMBB otherwise to bumpMBB.
11788   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11789   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11790     .addReg(tmpSPVReg).addReg(sizeVReg);
11791   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11792     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11793     .addReg(tmpSPVReg);
11794   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11795
11796   // bumpMBB simply decreases the stack pointer, since we know the current
11797   // stacklet has enough space.
11798   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11799     .addReg(tmpSPVReg);
11800   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11801     .addReg(tmpSPVReg);
11802   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11803
11804   // Calls into a routine in libgcc to allocate more space from the heap.
11805   if (Is64Bit) {
11806     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11807       .addReg(sizeVReg);
11808     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11809     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11810   } else {
11811     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11812       .addImm(12);
11813     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11814     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11815       .addExternalSymbol("__morestack_allocate_stack_space");
11816   }
11817
11818   if (!Is64Bit)
11819     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11820       .addImm(16);
11821
11822   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11823     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11824   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11825
11826   // Set up the CFG correctly.
11827   BB->addSuccessor(bumpMBB);
11828   BB->addSuccessor(mallocMBB);
11829   mallocMBB->addSuccessor(continueMBB);
11830   bumpMBB->addSuccessor(continueMBB);
11831
11832   // Take care of the PHI nodes.
11833   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11834           MI->getOperand(0).getReg())
11835     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11836     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11837
11838   // Delete the original pseudo instruction.
11839   MI->eraseFromParent();
11840
11841   // And we're done.
11842   return continueMBB;
11843 }
11844
11845 MachineBasicBlock *
11846 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11847                                           MachineBasicBlock *BB) const {
11848   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11849   DebugLoc DL = MI->getDebugLoc();
11850
11851   assert(!Subtarget->isTargetEnvMacho());
11852
11853   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11854   // non-trivial part is impdef of ESP.
11855
11856   if (Subtarget->isTargetWin64()) {
11857     if (Subtarget->isTargetCygMing()) {
11858       // ___chkstk(Mingw64):
11859       // Clobbers R10, R11, RAX and EFLAGS.
11860       // Updates RSP.
11861       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11862         .addExternalSymbol("___chkstk")
11863         .addReg(X86::RAX, RegState::Implicit)
11864         .addReg(X86::RSP, RegState::Implicit)
11865         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11866         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11867         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11868     } else {
11869       // __chkstk(MSVCRT): does not update stack pointer.
11870       // Clobbers R10, R11 and EFLAGS.
11871       // FIXME: RAX(allocated size) might be reused and not killed.
11872       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11873         .addExternalSymbol("__chkstk")
11874         .addReg(X86::RAX, RegState::Implicit)
11875         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11876       // RAX has the offset to subtracted from RSP.
11877       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11878         .addReg(X86::RSP)
11879         .addReg(X86::RAX);
11880     }
11881   } else {
11882     const char *StackProbeSymbol =
11883       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11884
11885     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11886       .addExternalSymbol(StackProbeSymbol)
11887       .addReg(X86::EAX, RegState::Implicit)
11888       .addReg(X86::ESP, RegState::Implicit)
11889       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11890       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11891       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11892   }
11893
11894   MI->eraseFromParent();   // The pseudo instruction is gone now.
11895   return BB;
11896 }
11897
11898 MachineBasicBlock *
11899 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11900                                       MachineBasicBlock *BB) const {
11901   // This is pretty easy.  We're taking the value that we received from
11902   // our load from the relocation, sticking it in either RDI (x86-64)
11903   // or EAX and doing an indirect call.  The return value will then
11904   // be in the normal return register.
11905   const X86InstrInfo *TII
11906     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11907   DebugLoc DL = MI->getDebugLoc();
11908   MachineFunction *F = BB->getParent();
11909
11910   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11911   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11912
11913   if (Subtarget->is64Bit()) {
11914     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11915                                       TII->get(X86::MOV64rm), X86::RDI)
11916     .addReg(X86::RIP)
11917     .addImm(0).addReg(0)
11918     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11919                       MI->getOperand(3).getTargetFlags())
11920     .addReg(0);
11921     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11922     addDirectMem(MIB, X86::RDI);
11923   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11924     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11925                                       TII->get(X86::MOV32rm), X86::EAX)
11926     .addReg(0)
11927     .addImm(0).addReg(0)
11928     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11929                       MI->getOperand(3).getTargetFlags())
11930     .addReg(0);
11931     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11932     addDirectMem(MIB, X86::EAX);
11933   } else {
11934     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11935                                       TII->get(X86::MOV32rm), X86::EAX)
11936     .addReg(TII->getGlobalBaseReg(F))
11937     .addImm(0).addReg(0)
11938     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11939                       MI->getOperand(3).getTargetFlags())
11940     .addReg(0);
11941     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11942     addDirectMem(MIB, X86::EAX);
11943   }
11944
11945   MI->eraseFromParent(); // The pseudo instruction is gone now.
11946   return BB;
11947 }
11948
11949 MachineBasicBlock *
11950 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11951                                                MachineBasicBlock *BB) const {
11952   switch (MI->getOpcode()) {
11953   default: assert(0 && "Unexpected instr type to insert");
11954   case X86::TAILJMPd64:
11955   case X86::TAILJMPr64:
11956   case X86::TAILJMPm64:
11957     assert(0 && "TAILJMP64 would not be touched here.");
11958   case X86::TCRETURNdi64:
11959   case X86::TCRETURNri64:
11960   case X86::TCRETURNmi64:
11961     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11962     // On AMD64, additional defs should be added before register allocation.
11963     if (!Subtarget->isTargetWin64()) {
11964       MI->addRegisterDefined(X86::RSI);
11965       MI->addRegisterDefined(X86::RDI);
11966       MI->addRegisterDefined(X86::XMM6);
11967       MI->addRegisterDefined(X86::XMM7);
11968       MI->addRegisterDefined(X86::XMM8);
11969       MI->addRegisterDefined(X86::XMM9);
11970       MI->addRegisterDefined(X86::XMM10);
11971       MI->addRegisterDefined(X86::XMM11);
11972       MI->addRegisterDefined(X86::XMM12);
11973       MI->addRegisterDefined(X86::XMM13);
11974       MI->addRegisterDefined(X86::XMM14);
11975       MI->addRegisterDefined(X86::XMM15);
11976     }
11977     return BB;
11978   case X86::WIN_ALLOCA:
11979     return EmitLoweredWinAlloca(MI, BB);
11980   case X86::SEG_ALLOCA_32:
11981     return EmitLoweredSegAlloca(MI, BB, false);
11982   case X86::SEG_ALLOCA_64:
11983     return EmitLoweredSegAlloca(MI, BB, true);
11984   case X86::TLSCall_32:
11985   case X86::TLSCall_64:
11986     return EmitLoweredTLSCall(MI, BB);
11987   case X86::CMOV_GR8:
11988   case X86::CMOV_FR32:
11989   case X86::CMOV_FR64:
11990   case X86::CMOV_V4F32:
11991   case X86::CMOV_V2F64:
11992   case X86::CMOV_V2I64:
11993   case X86::CMOV_V8F32:
11994   case X86::CMOV_V4F64:
11995   case X86::CMOV_V4I64:
11996   case X86::CMOV_GR16:
11997   case X86::CMOV_GR32:
11998   case X86::CMOV_RFP32:
11999   case X86::CMOV_RFP64:
12000   case X86::CMOV_RFP80:
12001     return EmitLoweredSelect(MI, BB);
12002
12003   case X86::FP32_TO_INT16_IN_MEM:
12004   case X86::FP32_TO_INT32_IN_MEM:
12005   case X86::FP32_TO_INT64_IN_MEM:
12006   case X86::FP64_TO_INT16_IN_MEM:
12007   case X86::FP64_TO_INT32_IN_MEM:
12008   case X86::FP64_TO_INT64_IN_MEM:
12009   case X86::FP80_TO_INT16_IN_MEM:
12010   case X86::FP80_TO_INT32_IN_MEM:
12011   case X86::FP80_TO_INT64_IN_MEM: {
12012     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12013     DebugLoc DL = MI->getDebugLoc();
12014
12015     // Change the floating point control register to use "round towards zero"
12016     // mode when truncating to an integer value.
12017     MachineFunction *F = BB->getParent();
12018     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12019     addFrameReference(BuildMI(*BB, MI, DL,
12020                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12021
12022     // Load the old value of the high byte of the control word...
12023     unsigned OldCW =
12024       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12025     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12026                       CWFrameIdx);
12027
12028     // Set the high part to be round to zero...
12029     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12030       .addImm(0xC7F);
12031
12032     // Reload the modified control word now...
12033     addFrameReference(BuildMI(*BB, MI, DL,
12034                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12035
12036     // Restore the memory image of control word to original value
12037     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12038       .addReg(OldCW);
12039
12040     // Get the X86 opcode to use.
12041     unsigned Opc;
12042     switch (MI->getOpcode()) {
12043     default: llvm_unreachable("illegal opcode!");
12044     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12045     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12046     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12047     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12048     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12049     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12050     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12051     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12052     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12053     }
12054
12055     X86AddressMode AM;
12056     MachineOperand &Op = MI->getOperand(0);
12057     if (Op.isReg()) {
12058       AM.BaseType = X86AddressMode::RegBase;
12059       AM.Base.Reg = Op.getReg();
12060     } else {
12061       AM.BaseType = X86AddressMode::FrameIndexBase;
12062       AM.Base.FrameIndex = Op.getIndex();
12063     }
12064     Op = MI->getOperand(1);
12065     if (Op.isImm())
12066       AM.Scale = Op.getImm();
12067     Op = MI->getOperand(2);
12068     if (Op.isImm())
12069       AM.IndexReg = Op.getImm();
12070     Op = MI->getOperand(3);
12071     if (Op.isGlobal()) {
12072       AM.GV = Op.getGlobal();
12073     } else {
12074       AM.Disp = Op.getImm();
12075     }
12076     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12077                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12078
12079     // Reload the original control word now.
12080     addFrameReference(BuildMI(*BB, MI, DL,
12081                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12082
12083     MI->eraseFromParent();   // The pseudo instruction is gone now.
12084     return BB;
12085   }
12086     // String/text processing lowering.
12087   case X86::PCMPISTRM128REG:
12088   case X86::VPCMPISTRM128REG:
12089     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12090   case X86::PCMPISTRM128MEM:
12091   case X86::VPCMPISTRM128MEM:
12092     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12093   case X86::PCMPESTRM128REG:
12094   case X86::VPCMPESTRM128REG:
12095     return EmitPCMP(MI, BB, 5, false /* in mem */);
12096   case X86::PCMPESTRM128MEM:
12097   case X86::VPCMPESTRM128MEM:
12098     return EmitPCMP(MI, BB, 5, true /* in mem */);
12099
12100     // Thread synchronization.
12101   case X86::MONITOR:
12102     return EmitMonitor(MI, BB);
12103   case X86::MWAIT:
12104     return EmitMwait(MI, BB);
12105
12106     // Atomic Lowering.
12107   case X86::ATOMAND32:
12108     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12109                                                X86::AND32ri, X86::MOV32rm,
12110                                                X86::LCMPXCHG32,
12111                                                X86::NOT32r, X86::EAX,
12112                                                X86::GR32RegisterClass);
12113   case X86::ATOMOR32:
12114     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12115                                                X86::OR32ri, X86::MOV32rm,
12116                                                X86::LCMPXCHG32,
12117                                                X86::NOT32r, X86::EAX,
12118                                                X86::GR32RegisterClass);
12119   case X86::ATOMXOR32:
12120     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12121                                                X86::XOR32ri, X86::MOV32rm,
12122                                                X86::LCMPXCHG32,
12123                                                X86::NOT32r, X86::EAX,
12124                                                X86::GR32RegisterClass);
12125   case X86::ATOMNAND32:
12126     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12127                                                X86::AND32ri, X86::MOV32rm,
12128                                                X86::LCMPXCHG32,
12129                                                X86::NOT32r, X86::EAX,
12130                                                X86::GR32RegisterClass, true);
12131   case X86::ATOMMIN32:
12132     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12133   case X86::ATOMMAX32:
12134     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12135   case X86::ATOMUMIN32:
12136     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12137   case X86::ATOMUMAX32:
12138     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12139
12140   case X86::ATOMAND16:
12141     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12142                                                X86::AND16ri, X86::MOV16rm,
12143                                                X86::LCMPXCHG16,
12144                                                X86::NOT16r, X86::AX,
12145                                                X86::GR16RegisterClass);
12146   case X86::ATOMOR16:
12147     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12148                                                X86::OR16ri, X86::MOV16rm,
12149                                                X86::LCMPXCHG16,
12150                                                X86::NOT16r, X86::AX,
12151                                                X86::GR16RegisterClass);
12152   case X86::ATOMXOR16:
12153     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12154                                                X86::XOR16ri, X86::MOV16rm,
12155                                                X86::LCMPXCHG16,
12156                                                X86::NOT16r, X86::AX,
12157                                                X86::GR16RegisterClass);
12158   case X86::ATOMNAND16:
12159     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12160                                                X86::AND16ri, X86::MOV16rm,
12161                                                X86::LCMPXCHG16,
12162                                                X86::NOT16r, X86::AX,
12163                                                X86::GR16RegisterClass, true);
12164   case X86::ATOMMIN16:
12165     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12166   case X86::ATOMMAX16:
12167     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12168   case X86::ATOMUMIN16:
12169     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12170   case X86::ATOMUMAX16:
12171     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12172
12173   case X86::ATOMAND8:
12174     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12175                                                X86::AND8ri, X86::MOV8rm,
12176                                                X86::LCMPXCHG8,
12177                                                X86::NOT8r, X86::AL,
12178                                                X86::GR8RegisterClass);
12179   case X86::ATOMOR8:
12180     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12181                                                X86::OR8ri, X86::MOV8rm,
12182                                                X86::LCMPXCHG8,
12183                                                X86::NOT8r, X86::AL,
12184                                                X86::GR8RegisterClass);
12185   case X86::ATOMXOR8:
12186     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12187                                                X86::XOR8ri, X86::MOV8rm,
12188                                                X86::LCMPXCHG8,
12189                                                X86::NOT8r, X86::AL,
12190                                                X86::GR8RegisterClass);
12191   case X86::ATOMNAND8:
12192     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12193                                                X86::AND8ri, X86::MOV8rm,
12194                                                X86::LCMPXCHG8,
12195                                                X86::NOT8r, X86::AL,
12196                                                X86::GR8RegisterClass, true);
12197   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12198   // This group is for 64-bit host.
12199   case X86::ATOMAND64:
12200     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12201                                                X86::AND64ri32, X86::MOV64rm,
12202                                                X86::LCMPXCHG64,
12203                                                X86::NOT64r, X86::RAX,
12204                                                X86::GR64RegisterClass);
12205   case X86::ATOMOR64:
12206     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12207                                                X86::OR64ri32, X86::MOV64rm,
12208                                                X86::LCMPXCHG64,
12209                                                X86::NOT64r, X86::RAX,
12210                                                X86::GR64RegisterClass);
12211   case X86::ATOMXOR64:
12212     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12213                                                X86::XOR64ri32, X86::MOV64rm,
12214                                                X86::LCMPXCHG64,
12215                                                X86::NOT64r, X86::RAX,
12216                                                X86::GR64RegisterClass);
12217   case X86::ATOMNAND64:
12218     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12219                                                X86::AND64ri32, X86::MOV64rm,
12220                                                X86::LCMPXCHG64,
12221                                                X86::NOT64r, X86::RAX,
12222                                                X86::GR64RegisterClass, true);
12223   case X86::ATOMMIN64:
12224     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12225   case X86::ATOMMAX64:
12226     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12227   case X86::ATOMUMIN64:
12228     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12229   case X86::ATOMUMAX64:
12230     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12231
12232   // This group does 64-bit operations on a 32-bit host.
12233   case X86::ATOMAND6432:
12234     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12235                                                X86::AND32rr, X86::AND32rr,
12236                                                X86::AND32ri, X86::AND32ri,
12237                                                false);
12238   case X86::ATOMOR6432:
12239     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12240                                                X86::OR32rr, X86::OR32rr,
12241                                                X86::OR32ri, X86::OR32ri,
12242                                                false);
12243   case X86::ATOMXOR6432:
12244     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12245                                                X86::XOR32rr, X86::XOR32rr,
12246                                                X86::XOR32ri, X86::XOR32ri,
12247                                                false);
12248   case X86::ATOMNAND6432:
12249     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12250                                                X86::AND32rr, X86::AND32rr,
12251                                                X86::AND32ri, X86::AND32ri,
12252                                                true);
12253   case X86::ATOMADD6432:
12254     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12255                                                X86::ADD32rr, X86::ADC32rr,
12256                                                X86::ADD32ri, X86::ADC32ri,
12257                                                false);
12258   case X86::ATOMSUB6432:
12259     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12260                                                X86::SUB32rr, X86::SBB32rr,
12261                                                X86::SUB32ri, X86::SBB32ri,
12262                                                false);
12263   case X86::ATOMSWAP6432:
12264     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12265                                                X86::MOV32rr, X86::MOV32rr,
12266                                                X86::MOV32ri, X86::MOV32ri,
12267                                                false);
12268   case X86::VASTART_SAVE_XMM_REGS:
12269     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12270
12271   case X86::VAARG_64:
12272     return EmitVAARG64WithCustomInserter(MI, BB);
12273   }
12274 }
12275
12276 //===----------------------------------------------------------------------===//
12277 //                           X86 Optimization Hooks
12278 //===----------------------------------------------------------------------===//
12279
12280 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12281                                                        const APInt &Mask,
12282                                                        APInt &KnownZero,
12283                                                        APInt &KnownOne,
12284                                                        const SelectionDAG &DAG,
12285                                                        unsigned Depth) const {
12286   unsigned Opc = Op.getOpcode();
12287   assert((Opc >= ISD::BUILTIN_OP_END ||
12288           Opc == ISD::INTRINSIC_WO_CHAIN ||
12289           Opc == ISD::INTRINSIC_W_CHAIN ||
12290           Opc == ISD::INTRINSIC_VOID) &&
12291          "Should use MaskedValueIsZero if you don't know whether Op"
12292          " is a target node!");
12293
12294   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12295   switch (Opc) {
12296   default: break;
12297   case X86ISD::ADD:
12298   case X86ISD::SUB:
12299   case X86ISD::ADC:
12300   case X86ISD::SBB:
12301   case X86ISD::SMUL:
12302   case X86ISD::UMUL:
12303   case X86ISD::INC:
12304   case X86ISD::DEC:
12305   case X86ISD::OR:
12306   case X86ISD::XOR:
12307   case X86ISD::AND:
12308     // These nodes' second result is a boolean.
12309     if (Op.getResNo() == 0)
12310       break;
12311     // Fallthrough
12312   case X86ISD::SETCC:
12313     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12314                                        Mask.getBitWidth() - 1);
12315     break;
12316   }
12317 }
12318
12319 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12320                                                          unsigned Depth) const {
12321   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12322   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12323     return Op.getValueType().getScalarType().getSizeInBits();
12324
12325   // Fallback case.
12326   return 1;
12327 }
12328
12329 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12330 /// node is a GlobalAddress + offset.
12331 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12332                                        const GlobalValue* &GA,
12333                                        int64_t &Offset) const {
12334   if (N->getOpcode() == X86ISD::Wrapper) {
12335     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12336       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12337       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12338       return true;
12339     }
12340   }
12341   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12342 }
12343
12344 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12345 /// same as extracting the high 128-bit part of 256-bit vector and then
12346 /// inserting the result into the low part of a new 256-bit vector
12347 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12348   EVT VT = SVOp->getValueType(0);
12349   int NumElems = VT.getVectorNumElements();
12350
12351   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12352   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12353     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12354         SVOp->getMaskElt(j) >= 0)
12355       return false;
12356
12357   return true;
12358 }
12359
12360 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12361 /// same as extracting the low 128-bit part of 256-bit vector and then
12362 /// inserting the result into the high part of a new 256-bit vector
12363 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12364   EVT VT = SVOp->getValueType(0);
12365   int NumElems = VT.getVectorNumElements();
12366
12367   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12368   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12369     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12370         SVOp->getMaskElt(j) >= 0)
12371       return false;
12372
12373   return true;
12374 }
12375
12376 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12377 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12378                                         TargetLowering::DAGCombinerInfo &DCI) {
12379   DebugLoc dl = N->getDebugLoc();
12380   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12381   SDValue V1 = SVOp->getOperand(0);
12382   SDValue V2 = SVOp->getOperand(1);
12383   EVT VT = SVOp->getValueType(0);
12384   int NumElems = VT.getVectorNumElements();
12385
12386   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12387       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12388     //
12389     //                   0,0,0,...
12390     //                      |
12391     //    V      UNDEF    BUILD_VECTOR    UNDEF
12392     //     \      /           \           /
12393     //  CONCAT_VECTOR         CONCAT_VECTOR
12394     //         \                  /
12395     //          \                /
12396     //          RESULT: V + zero extended
12397     //
12398     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12399         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12400         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12401       return SDValue();
12402
12403     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12404       return SDValue();
12405
12406     // To match the shuffle mask, the first half of the mask should
12407     // be exactly the first vector, and all the rest a splat with the
12408     // first element of the second one.
12409     for (int i = 0; i < NumElems/2; ++i)
12410       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12411           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12412         return SDValue();
12413
12414     // Emit a zeroed vector and insert the desired subvector on its
12415     // first half.
12416     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12417     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12418                          DAG.getConstant(0, MVT::i32), DAG, dl);
12419     return DCI.CombineTo(N, InsV);
12420   }
12421
12422   //===--------------------------------------------------------------------===//
12423   // Combine some shuffles into subvector extracts and inserts:
12424   //
12425
12426   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12427   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12428     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12429                                     DAG, dl);
12430     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12431                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12432     return DCI.CombineTo(N, InsV);
12433   }
12434
12435   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12436   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12437     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12438     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12439                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12440     return DCI.CombineTo(N, InsV);
12441   }
12442
12443   return SDValue();
12444 }
12445
12446 /// PerformShuffleCombine - Performs several different shuffle combines.
12447 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12448                                      TargetLowering::DAGCombinerInfo &DCI,
12449                                      const X86Subtarget *Subtarget) {
12450   DebugLoc dl = N->getDebugLoc();
12451   EVT VT = N->getValueType(0);
12452
12453   // Don't create instructions with illegal types after legalize types has run.
12454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12455   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12456     return SDValue();
12457
12458   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12459   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12460       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12461     return PerformShuffleCombine256(N, DAG, DCI);
12462
12463   // Only handle 128 wide vector from here on.
12464   if (VT.getSizeInBits() != 128)
12465     return SDValue();
12466
12467   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12468   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12469   // consecutive, non-overlapping, and in the right order.
12470   SmallVector<SDValue, 16> Elts;
12471   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12472     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12473
12474   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12475 }
12476
12477 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12478 /// generation and convert it from being a bunch of shuffles and extracts
12479 /// to a simple store and scalar loads to extract the elements.
12480 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12481                                                 const TargetLowering &TLI) {
12482   SDValue InputVector = N->getOperand(0);
12483
12484   // Only operate on vectors of 4 elements, where the alternative shuffling
12485   // gets to be more expensive.
12486   if (InputVector.getValueType() != MVT::v4i32)
12487     return SDValue();
12488
12489   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12490   // single use which is a sign-extend or zero-extend, and all elements are
12491   // used.
12492   SmallVector<SDNode *, 4> Uses;
12493   unsigned ExtractedElements = 0;
12494   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12495        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12496     if (UI.getUse().getResNo() != InputVector.getResNo())
12497       return SDValue();
12498
12499     SDNode *Extract = *UI;
12500     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12501       return SDValue();
12502
12503     if (Extract->getValueType(0) != MVT::i32)
12504       return SDValue();
12505     if (!Extract->hasOneUse())
12506       return SDValue();
12507     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12508         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12509       return SDValue();
12510     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12511       return SDValue();
12512
12513     // Record which element was extracted.
12514     ExtractedElements |=
12515       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12516
12517     Uses.push_back(Extract);
12518   }
12519
12520   // If not all the elements were used, this may not be worthwhile.
12521   if (ExtractedElements != 15)
12522     return SDValue();
12523
12524   // Ok, we've now decided to do the transformation.
12525   DebugLoc dl = InputVector.getDebugLoc();
12526
12527   // Store the value to a temporary stack slot.
12528   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12529   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12530                             MachinePointerInfo(), false, false, 0);
12531
12532   // Replace each use (extract) with a load of the appropriate element.
12533   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12534        UE = Uses.end(); UI != UE; ++UI) {
12535     SDNode *Extract = *UI;
12536
12537     // cOMpute the element's address.
12538     SDValue Idx = Extract->getOperand(1);
12539     unsigned EltSize =
12540         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12541     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12542     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12543
12544     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12545                                      StackPtr, OffsetVal);
12546
12547     // Load the scalar.
12548     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12549                                      ScalarAddr, MachinePointerInfo(),
12550                                      false, false, 0);
12551
12552     // Replace the exact with the load.
12553     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12554   }
12555
12556   // The replacement was made in place; don't return anything.
12557   return SDValue();
12558 }
12559
12560 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12561 /// nodes.
12562 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12563                                     const X86Subtarget *Subtarget) {
12564   DebugLoc DL = N->getDebugLoc();
12565   SDValue Cond = N->getOperand(0);
12566   // Get the LHS/RHS of the select.
12567   SDValue LHS = N->getOperand(1);
12568   SDValue RHS = N->getOperand(2);
12569   EVT VT = LHS.getValueType();
12570
12571   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12572   // instructions match the semantics of the common C idiom x<y?x:y but not
12573   // x<=y?x:y, because of how they handle negative zero (which can be
12574   // ignored in unsafe-math mode).
12575   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12576       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12577       (Subtarget->hasXMMInt() ||
12578        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12579     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12580
12581     unsigned Opcode = 0;
12582     // Check for x CC y ? x : y.
12583     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12584         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12585       switch (CC) {
12586       default: break;
12587       case ISD::SETULT:
12588         // Converting this to a min would handle NaNs incorrectly, and swapping
12589         // the operands would cause it to handle comparisons between positive
12590         // and negative zero incorrectly.
12591         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12592           if (!UnsafeFPMath &&
12593               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12594             break;
12595           std::swap(LHS, RHS);
12596         }
12597         Opcode = X86ISD::FMIN;
12598         break;
12599       case ISD::SETOLE:
12600         // Converting this to a min would handle comparisons between positive
12601         // and negative zero incorrectly.
12602         if (!UnsafeFPMath &&
12603             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12604           break;
12605         Opcode = X86ISD::FMIN;
12606         break;
12607       case ISD::SETULE:
12608         // Converting this to a min would handle both negative zeros and NaNs
12609         // incorrectly, but we can swap the operands to fix both.
12610         std::swap(LHS, RHS);
12611       case ISD::SETOLT:
12612       case ISD::SETLT:
12613       case ISD::SETLE:
12614         Opcode = X86ISD::FMIN;
12615         break;
12616
12617       case ISD::SETOGE:
12618         // Converting this to a max would handle comparisons between positive
12619         // and negative zero incorrectly.
12620         if (!UnsafeFPMath &&
12621             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12622           break;
12623         Opcode = X86ISD::FMAX;
12624         break;
12625       case ISD::SETUGT:
12626         // Converting this to a max would handle NaNs incorrectly, and swapping
12627         // the operands would cause it to handle comparisons between positive
12628         // and negative zero incorrectly.
12629         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12630           if (!UnsafeFPMath &&
12631               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12632             break;
12633           std::swap(LHS, RHS);
12634         }
12635         Opcode = X86ISD::FMAX;
12636         break;
12637       case ISD::SETUGE:
12638         // Converting this to a max would handle both negative zeros and NaNs
12639         // incorrectly, but we can swap the operands to fix both.
12640         std::swap(LHS, RHS);
12641       case ISD::SETOGT:
12642       case ISD::SETGT:
12643       case ISD::SETGE:
12644         Opcode = X86ISD::FMAX;
12645         break;
12646       }
12647     // Check for x CC y ? y : x -- a min/max with reversed arms.
12648     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12649                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12650       switch (CC) {
12651       default: break;
12652       case ISD::SETOGE:
12653         // Converting this to a min would handle comparisons between positive
12654         // and negative zero incorrectly, and swapping the operands would
12655         // cause it to handle NaNs incorrectly.
12656         if (!UnsafeFPMath &&
12657             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12658           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12659             break;
12660           std::swap(LHS, RHS);
12661         }
12662         Opcode = X86ISD::FMIN;
12663         break;
12664       case ISD::SETUGT:
12665         // Converting this to a min would handle NaNs incorrectly.
12666         if (!UnsafeFPMath &&
12667             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12668           break;
12669         Opcode = X86ISD::FMIN;
12670         break;
12671       case ISD::SETUGE:
12672         // Converting this to a min would handle both negative zeros and NaNs
12673         // incorrectly, but we can swap the operands to fix both.
12674         std::swap(LHS, RHS);
12675       case ISD::SETOGT:
12676       case ISD::SETGT:
12677       case ISD::SETGE:
12678         Opcode = X86ISD::FMIN;
12679         break;
12680
12681       case ISD::SETULT:
12682         // Converting this to a max would handle NaNs incorrectly.
12683         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12684           break;
12685         Opcode = X86ISD::FMAX;
12686         break;
12687       case ISD::SETOLE:
12688         // Converting this to a max would handle comparisons between positive
12689         // and negative zero incorrectly, and swapping the operands would
12690         // cause it to handle NaNs incorrectly.
12691         if (!UnsafeFPMath &&
12692             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12693           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12694             break;
12695           std::swap(LHS, RHS);
12696         }
12697         Opcode = X86ISD::FMAX;
12698         break;
12699       case ISD::SETULE:
12700         // Converting this to a max would handle both negative zeros and NaNs
12701         // incorrectly, but we can swap the operands to fix both.
12702         std::swap(LHS, RHS);
12703       case ISD::SETOLT:
12704       case ISD::SETLT:
12705       case ISD::SETLE:
12706         Opcode = X86ISD::FMAX;
12707         break;
12708       }
12709     }
12710
12711     if (Opcode)
12712       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12713   }
12714
12715   // If this is a select between two integer constants, try to do some
12716   // optimizations.
12717   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12718     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12719       // Don't do this for crazy integer types.
12720       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12721         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12722         // so that TrueC (the true value) is larger than FalseC.
12723         bool NeedsCondInvert = false;
12724
12725         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12726             // Efficiently invertible.
12727             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12728              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12729               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12730           NeedsCondInvert = true;
12731           std::swap(TrueC, FalseC);
12732         }
12733
12734         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12735         if (FalseC->getAPIntValue() == 0 &&
12736             TrueC->getAPIntValue().isPowerOf2()) {
12737           if (NeedsCondInvert) // Invert the condition if needed.
12738             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12739                                DAG.getConstant(1, Cond.getValueType()));
12740
12741           // Zero extend the condition if needed.
12742           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12743
12744           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12745           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12746                              DAG.getConstant(ShAmt, MVT::i8));
12747         }
12748
12749         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12750         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12751           if (NeedsCondInvert) // Invert the condition if needed.
12752             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12753                                DAG.getConstant(1, Cond.getValueType()));
12754
12755           // Zero extend the condition if needed.
12756           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12757                              FalseC->getValueType(0), Cond);
12758           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12759                              SDValue(FalseC, 0));
12760         }
12761
12762         // Optimize cases that will turn into an LEA instruction.  This requires
12763         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12764         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12765           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12766           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12767
12768           bool isFastMultiplier = false;
12769           if (Diff < 10) {
12770             switch ((unsigned char)Diff) {
12771               default: break;
12772               case 1:  // result = add base, cond
12773               case 2:  // result = lea base(    , cond*2)
12774               case 3:  // result = lea base(cond, cond*2)
12775               case 4:  // result = lea base(    , cond*4)
12776               case 5:  // result = lea base(cond, cond*4)
12777               case 8:  // result = lea base(    , cond*8)
12778               case 9:  // result = lea base(cond, cond*8)
12779                 isFastMultiplier = true;
12780                 break;
12781             }
12782           }
12783
12784           if (isFastMultiplier) {
12785             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12786             if (NeedsCondInvert) // Invert the condition if needed.
12787               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12788                                  DAG.getConstant(1, Cond.getValueType()));
12789
12790             // Zero extend the condition if needed.
12791             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12792                                Cond);
12793             // Scale the condition by the difference.
12794             if (Diff != 1)
12795               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12796                                  DAG.getConstant(Diff, Cond.getValueType()));
12797
12798             // Add the base if non-zero.
12799             if (FalseC->getAPIntValue() != 0)
12800               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12801                                  SDValue(FalseC, 0));
12802             return Cond;
12803           }
12804         }
12805       }
12806   }
12807
12808   return SDValue();
12809 }
12810
12811 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12812 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12813                                   TargetLowering::DAGCombinerInfo &DCI) {
12814   DebugLoc DL = N->getDebugLoc();
12815
12816   // If the flag operand isn't dead, don't touch this CMOV.
12817   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12818     return SDValue();
12819
12820   SDValue FalseOp = N->getOperand(0);
12821   SDValue TrueOp = N->getOperand(1);
12822   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12823   SDValue Cond = N->getOperand(3);
12824   if (CC == X86::COND_E || CC == X86::COND_NE) {
12825     switch (Cond.getOpcode()) {
12826     default: break;
12827     case X86ISD::BSR:
12828     case X86ISD::BSF:
12829       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12830       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12831         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12832     }
12833   }
12834
12835   // If this is a select between two integer constants, try to do some
12836   // optimizations.  Note that the operands are ordered the opposite of SELECT
12837   // operands.
12838   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12839     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12840       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12841       // larger than FalseC (the false value).
12842       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12843         CC = X86::GetOppositeBranchCondition(CC);
12844         std::swap(TrueC, FalseC);
12845       }
12846
12847       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12848       // This is efficient for any integer data type (including i8/i16) and
12849       // shift amount.
12850       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12851         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12852                            DAG.getConstant(CC, MVT::i8), Cond);
12853
12854         // Zero extend the condition if needed.
12855         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12856
12857         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12858         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12859                            DAG.getConstant(ShAmt, MVT::i8));
12860         if (N->getNumValues() == 2)  // Dead flag value?
12861           return DCI.CombineTo(N, Cond, SDValue());
12862         return Cond;
12863       }
12864
12865       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12866       // for any integer data type, including i8/i16.
12867       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12868         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12869                            DAG.getConstant(CC, MVT::i8), Cond);
12870
12871         // Zero extend the condition if needed.
12872         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12873                            FalseC->getValueType(0), Cond);
12874         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12875                            SDValue(FalseC, 0));
12876
12877         if (N->getNumValues() == 2)  // Dead flag value?
12878           return DCI.CombineTo(N, Cond, SDValue());
12879         return Cond;
12880       }
12881
12882       // Optimize cases that will turn into an LEA instruction.  This requires
12883       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12884       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12885         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12886         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12887
12888         bool isFastMultiplier = false;
12889         if (Diff < 10) {
12890           switch ((unsigned char)Diff) {
12891           default: break;
12892           case 1:  // result = add base, cond
12893           case 2:  // result = lea base(    , cond*2)
12894           case 3:  // result = lea base(cond, cond*2)
12895           case 4:  // result = lea base(    , cond*4)
12896           case 5:  // result = lea base(cond, cond*4)
12897           case 8:  // result = lea base(    , cond*8)
12898           case 9:  // result = lea base(cond, cond*8)
12899             isFastMultiplier = true;
12900             break;
12901           }
12902         }
12903
12904         if (isFastMultiplier) {
12905           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12906           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12907                              DAG.getConstant(CC, MVT::i8), Cond);
12908           // Zero extend the condition if needed.
12909           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12910                              Cond);
12911           // Scale the condition by the difference.
12912           if (Diff != 1)
12913             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12914                                DAG.getConstant(Diff, Cond.getValueType()));
12915
12916           // Add the base if non-zero.
12917           if (FalseC->getAPIntValue() != 0)
12918             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12919                                SDValue(FalseC, 0));
12920           if (N->getNumValues() == 2)  // Dead flag value?
12921             return DCI.CombineTo(N, Cond, SDValue());
12922           return Cond;
12923         }
12924       }
12925     }
12926   }
12927   return SDValue();
12928 }
12929
12930
12931 /// PerformMulCombine - Optimize a single multiply with constant into two
12932 /// in order to implement it with two cheaper instructions, e.g.
12933 /// LEA + SHL, LEA + LEA.
12934 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12935                                  TargetLowering::DAGCombinerInfo &DCI) {
12936   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12937     return SDValue();
12938
12939   EVT VT = N->getValueType(0);
12940   if (VT != MVT::i64)
12941     return SDValue();
12942
12943   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12944   if (!C)
12945     return SDValue();
12946   uint64_t MulAmt = C->getZExtValue();
12947   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12948     return SDValue();
12949
12950   uint64_t MulAmt1 = 0;
12951   uint64_t MulAmt2 = 0;
12952   if ((MulAmt % 9) == 0) {
12953     MulAmt1 = 9;
12954     MulAmt2 = MulAmt / 9;
12955   } else if ((MulAmt % 5) == 0) {
12956     MulAmt1 = 5;
12957     MulAmt2 = MulAmt / 5;
12958   } else if ((MulAmt % 3) == 0) {
12959     MulAmt1 = 3;
12960     MulAmt2 = MulAmt / 3;
12961   }
12962   if (MulAmt2 &&
12963       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12964     DebugLoc DL = N->getDebugLoc();
12965
12966     if (isPowerOf2_64(MulAmt2) &&
12967         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12968       // If second multiplifer is pow2, issue it first. We want the multiply by
12969       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12970       // is an add.
12971       std::swap(MulAmt1, MulAmt2);
12972
12973     SDValue NewMul;
12974     if (isPowerOf2_64(MulAmt1))
12975       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12976                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12977     else
12978       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12979                            DAG.getConstant(MulAmt1, VT));
12980
12981     if (isPowerOf2_64(MulAmt2))
12982       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12983                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12984     else
12985       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12986                            DAG.getConstant(MulAmt2, VT));
12987
12988     // Do not add new nodes to DAG combiner worklist.
12989     DCI.CombineTo(N, NewMul, false);
12990   }
12991   return SDValue();
12992 }
12993
12994 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12995   SDValue N0 = N->getOperand(0);
12996   SDValue N1 = N->getOperand(1);
12997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12998   EVT VT = N0.getValueType();
12999
13000   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13001   // since the result of setcc_c is all zero's or all ones.
13002   if (N1C && N0.getOpcode() == ISD::AND &&
13003       N0.getOperand(1).getOpcode() == ISD::Constant) {
13004     SDValue N00 = N0.getOperand(0);
13005     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13006         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13007           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13008          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13009       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13010       APInt ShAmt = N1C->getAPIntValue();
13011       Mask = Mask.shl(ShAmt);
13012       if (Mask != 0)
13013         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13014                            N00, DAG.getConstant(Mask, VT));
13015     }
13016   }
13017
13018   return SDValue();
13019 }
13020
13021 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13022 ///                       when possible.
13023 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13024                                    const X86Subtarget *Subtarget) {
13025   EVT VT = N->getValueType(0);
13026   if (!VT.isVector() && VT.isInteger() &&
13027       N->getOpcode() == ISD::SHL)
13028     return PerformSHLCombine(N, DAG);
13029
13030   // On X86 with SSE2 support, we can transform this to a vector shift if
13031   // all elements are shifted by the same amount.  We can't do this in legalize
13032   // because the a constant vector is typically transformed to a constant pool
13033   // so we have no knowledge of the shift amount.
13034   if (!Subtarget->hasXMMInt())
13035     return SDValue();
13036
13037   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13038     return SDValue();
13039
13040   SDValue ShAmtOp = N->getOperand(1);
13041   EVT EltVT = VT.getVectorElementType();
13042   DebugLoc DL = N->getDebugLoc();
13043   SDValue BaseShAmt = SDValue();
13044   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13045     unsigned NumElts = VT.getVectorNumElements();
13046     unsigned i = 0;
13047     for (; i != NumElts; ++i) {
13048       SDValue Arg = ShAmtOp.getOperand(i);
13049       if (Arg.getOpcode() == ISD::UNDEF) continue;
13050       BaseShAmt = Arg;
13051       break;
13052     }
13053     for (; i != NumElts; ++i) {
13054       SDValue Arg = ShAmtOp.getOperand(i);
13055       if (Arg.getOpcode() == ISD::UNDEF) continue;
13056       if (Arg != BaseShAmt) {
13057         return SDValue();
13058       }
13059     }
13060   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13061              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13062     SDValue InVec = ShAmtOp.getOperand(0);
13063     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13064       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13065       unsigned i = 0;
13066       for (; i != NumElts; ++i) {
13067         SDValue Arg = InVec.getOperand(i);
13068         if (Arg.getOpcode() == ISD::UNDEF) continue;
13069         BaseShAmt = Arg;
13070         break;
13071       }
13072     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13073        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13074          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13075          if (C->getZExtValue() == SplatIdx)
13076            BaseShAmt = InVec.getOperand(1);
13077        }
13078     }
13079     if (BaseShAmt.getNode() == 0)
13080       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13081                               DAG.getIntPtrConstant(0));
13082   } else
13083     return SDValue();
13084
13085   // The shift amount is an i32.
13086   if (EltVT.bitsGT(MVT::i32))
13087     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13088   else if (EltVT.bitsLT(MVT::i32))
13089     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13090
13091   // The shift amount is identical so we can do a vector shift.
13092   SDValue  ValOp = N->getOperand(0);
13093   switch (N->getOpcode()) {
13094   default:
13095     llvm_unreachable("Unknown shift opcode!");
13096     break;
13097   case ISD::SHL:
13098     if (VT == MVT::v2i64)
13099       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13100                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13101                          ValOp, BaseShAmt);
13102     if (VT == MVT::v4i32)
13103       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13104                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13105                          ValOp, BaseShAmt);
13106     if (VT == MVT::v8i16)
13107       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13108                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13109                          ValOp, BaseShAmt);
13110     break;
13111   case ISD::SRA:
13112     if (VT == MVT::v4i32)
13113       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13114                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13115                          ValOp, BaseShAmt);
13116     if (VT == MVT::v8i16)
13117       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13118                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13119                          ValOp, BaseShAmt);
13120     break;
13121   case ISD::SRL:
13122     if (VT == MVT::v2i64)
13123       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13124                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13125                          ValOp, BaseShAmt);
13126     if (VT == MVT::v4i32)
13127       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13128                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13129                          ValOp, BaseShAmt);
13130     if (VT ==  MVT::v8i16)
13131       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13132                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13133                          ValOp, BaseShAmt);
13134     break;
13135   }
13136   return SDValue();
13137 }
13138
13139
13140 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13141 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13142 // and friends.  Likewise for OR -> CMPNEQSS.
13143 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13144                             TargetLowering::DAGCombinerInfo &DCI,
13145                             const X86Subtarget *Subtarget) {
13146   unsigned opcode;
13147
13148   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13149   // we're requiring SSE2 for both.
13150   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13151     SDValue N0 = N->getOperand(0);
13152     SDValue N1 = N->getOperand(1);
13153     SDValue CMP0 = N0->getOperand(1);
13154     SDValue CMP1 = N1->getOperand(1);
13155     DebugLoc DL = N->getDebugLoc();
13156
13157     // The SETCCs should both refer to the same CMP.
13158     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13159       return SDValue();
13160
13161     SDValue CMP00 = CMP0->getOperand(0);
13162     SDValue CMP01 = CMP0->getOperand(1);
13163     EVT     VT    = CMP00.getValueType();
13164
13165     if (VT == MVT::f32 || VT == MVT::f64) {
13166       bool ExpectingFlags = false;
13167       // Check for any users that want flags:
13168       for (SDNode::use_iterator UI = N->use_begin(),
13169              UE = N->use_end();
13170            !ExpectingFlags && UI != UE; ++UI)
13171         switch (UI->getOpcode()) {
13172         default:
13173         case ISD::BR_CC:
13174         case ISD::BRCOND:
13175         case ISD::SELECT:
13176           ExpectingFlags = true;
13177           break;
13178         case ISD::CopyToReg:
13179         case ISD::SIGN_EXTEND:
13180         case ISD::ZERO_EXTEND:
13181         case ISD::ANY_EXTEND:
13182           break;
13183         }
13184
13185       if (!ExpectingFlags) {
13186         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13187         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13188
13189         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13190           X86::CondCode tmp = cc0;
13191           cc0 = cc1;
13192           cc1 = tmp;
13193         }
13194
13195         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13196             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13197           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13198           X86ISD::NodeType NTOperator = is64BitFP ?
13199             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13200           // FIXME: need symbolic constants for these magic numbers.
13201           // See X86ATTInstPrinter.cpp:printSSECC().
13202           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13203           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13204                                               DAG.getConstant(x86cc, MVT::i8));
13205           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13206                                               OnesOrZeroesF);
13207           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13208                                       DAG.getConstant(1, MVT::i32));
13209           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13210           return OneBitOfTruth;
13211         }
13212       }
13213     }
13214   }
13215   return SDValue();
13216 }
13217
13218 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13219 /// so it can be folded inside ANDNP.
13220 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13221   EVT VT = N->getValueType(0);
13222
13223   // Match direct AllOnes for 128 and 256-bit vectors
13224   if (ISD::isBuildVectorAllOnes(N))
13225     return true;
13226
13227   // Look through a bit convert.
13228   if (N->getOpcode() == ISD::BITCAST)
13229     N = N->getOperand(0).getNode();
13230
13231   // Sometimes the operand may come from a insert_subvector building a 256-bit
13232   // allones vector
13233   if (VT.getSizeInBits() == 256 &&
13234       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13235     SDValue V1 = N->getOperand(0);
13236     SDValue V2 = N->getOperand(1);
13237
13238     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13239         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13240         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13241         ISD::isBuildVectorAllOnes(V2.getNode()))
13242       return true;
13243   }
13244
13245   return false;
13246 }
13247
13248 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13249                                  TargetLowering::DAGCombinerInfo &DCI,
13250                                  const X86Subtarget *Subtarget) {
13251   if (DCI.isBeforeLegalizeOps())
13252     return SDValue();
13253
13254   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13255   if (R.getNode())
13256     return R;
13257
13258   // Want to form ANDNP nodes:
13259   // 1) In the hopes of then easily combining them with OR and AND nodes
13260   //    to form PBLEND/PSIGN.
13261   // 2) To match ANDN packed intrinsics
13262   EVT VT = N->getValueType(0);
13263   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13264     return SDValue();
13265
13266   SDValue N0 = N->getOperand(0);
13267   SDValue N1 = N->getOperand(1);
13268   DebugLoc DL = N->getDebugLoc();
13269
13270   // Check LHS for vnot
13271   if (N0.getOpcode() == ISD::XOR &&
13272       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13273       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13274     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13275
13276   // Check RHS for vnot
13277   if (N1.getOpcode() == ISD::XOR &&
13278       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13279       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13280     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13281
13282   return SDValue();
13283 }
13284
13285 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13286                                 TargetLowering::DAGCombinerInfo &DCI,
13287                                 const X86Subtarget *Subtarget) {
13288   if (DCI.isBeforeLegalizeOps())
13289     return SDValue();
13290
13291   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13292   if (R.getNode())
13293     return R;
13294
13295   EVT VT = N->getValueType(0);
13296   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13297     return SDValue();
13298
13299   SDValue N0 = N->getOperand(0);
13300   SDValue N1 = N->getOperand(1);
13301
13302   // look for psign/blend
13303   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13304     if (VT == MVT::v2i64) {
13305       // Canonicalize pandn to RHS
13306       if (N0.getOpcode() == X86ISD::ANDNP)
13307         std::swap(N0, N1);
13308       // or (and (m, x), (pandn m, y))
13309       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13310         SDValue Mask = N1.getOperand(0);
13311         SDValue X    = N1.getOperand(1);
13312         SDValue Y;
13313         if (N0.getOperand(0) == Mask)
13314           Y = N0.getOperand(1);
13315         if (N0.getOperand(1) == Mask)
13316           Y = N0.getOperand(0);
13317
13318         // Check to see if the mask appeared in both the AND and ANDNP and
13319         if (!Y.getNode())
13320           return SDValue();
13321
13322         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13323         if (Mask.getOpcode() != ISD::BITCAST ||
13324             X.getOpcode() != ISD::BITCAST ||
13325             Y.getOpcode() != ISD::BITCAST)
13326           return SDValue();
13327
13328         // Look through mask bitcast.
13329         Mask = Mask.getOperand(0);
13330         EVT MaskVT = Mask.getValueType();
13331
13332         // Validate that the Mask operand is a vector sra node.  The sra node
13333         // will be an intrinsic.
13334         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13335           return SDValue();
13336
13337         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13338         // there is no psrai.b
13339         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13340         case Intrinsic::x86_sse2_psrai_w:
13341         case Intrinsic::x86_sse2_psrai_d:
13342           break;
13343         default: return SDValue();
13344         }
13345
13346         // Check that the SRA is all signbits.
13347         SDValue SraC = Mask.getOperand(2);
13348         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13349         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13350         if ((SraAmt + 1) != EltBits)
13351           return SDValue();
13352
13353         DebugLoc DL = N->getDebugLoc();
13354
13355         // Now we know we at least have a plendvb with the mask val.  See if
13356         // we can form a psignb/w/d.
13357         // psign = x.type == y.type == mask.type && y = sub(0, x);
13358         X = X.getOperand(0);
13359         Y = Y.getOperand(0);
13360         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13361             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13362             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13363           unsigned Opc = 0;
13364           switch (EltBits) {
13365           case 8: Opc = X86ISD::PSIGNB; break;
13366           case 16: Opc = X86ISD::PSIGNW; break;
13367           case 32: Opc = X86ISD::PSIGND; break;
13368           default: break;
13369           }
13370           if (Opc) {
13371             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13372             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13373           }
13374         }
13375         // PBLENDVB only available on SSE 4.1
13376         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13377           return SDValue();
13378
13379         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13380         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13381         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13382         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13383         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13384       }
13385     }
13386   }
13387
13388   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13389   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13390     std::swap(N0, N1);
13391   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13392     return SDValue();
13393   if (!N0.hasOneUse() || !N1.hasOneUse())
13394     return SDValue();
13395
13396   SDValue ShAmt0 = N0.getOperand(1);
13397   if (ShAmt0.getValueType() != MVT::i8)
13398     return SDValue();
13399   SDValue ShAmt1 = N1.getOperand(1);
13400   if (ShAmt1.getValueType() != MVT::i8)
13401     return SDValue();
13402   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13403     ShAmt0 = ShAmt0.getOperand(0);
13404   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13405     ShAmt1 = ShAmt1.getOperand(0);
13406
13407   DebugLoc DL = N->getDebugLoc();
13408   unsigned Opc = X86ISD::SHLD;
13409   SDValue Op0 = N0.getOperand(0);
13410   SDValue Op1 = N1.getOperand(0);
13411   if (ShAmt0.getOpcode() == ISD::SUB) {
13412     Opc = X86ISD::SHRD;
13413     std::swap(Op0, Op1);
13414     std::swap(ShAmt0, ShAmt1);
13415   }
13416
13417   unsigned Bits = VT.getSizeInBits();
13418   if (ShAmt1.getOpcode() == ISD::SUB) {
13419     SDValue Sum = ShAmt1.getOperand(0);
13420     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13421       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13422       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13423         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13424       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13425         return DAG.getNode(Opc, DL, VT,
13426                            Op0, Op1,
13427                            DAG.getNode(ISD::TRUNCATE, DL,
13428                                        MVT::i8, ShAmt0));
13429     }
13430   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13431     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13432     if (ShAmt0C &&
13433         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13434       return DAG.getNode(Opc, DL, VT,
13435                          N0.getOperand(0), N1.getOperand(0),
13436                          DAG.getNode(ISD::TRUNCATE, DL,
13437                                        MVT::i8, ShAmt0));
13438   }
13439
13440   return SDValue();
13441 }
13442
13443 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13444 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13445                                    const X86Subtarget *Subtarget) {
13446   LoadSDNode *Ld = cast<LoadSDNode>(N);
13447   EVT RegVT = Ld->getValueType(0);
13448   EVT MemVT = Ld->getMemoryVT();
13449   DebugLoc dl = Ld->getDebugLoc();
13450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13451
13452   ISD::LoadExtType Ext = Ld->getExtensionType();
13453
13454   // If this is a vector EXT Load then attempt to optimize it using a
13455   // shuffle. We need SSE4 for the shuffles.
13456   // TODO: It is possible to support ZExt by zeroing the undef values
13457   // during the shuffle phase or after the shuffle.
13458   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13459     assert(MemVT != RegVT && "Cannot extend to the same type");
13460     assert(MemVT.isVector() && "Must load a vector from memory");
13461
13462     unsigned NumElems = RegVT.getVectorNumElements();
13463     unsigned RegSz = RegVT.getSizeInBits();
13464     unsigned MemSz = MemVT.getSizeInBits();
13465     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13466     // All sizes must be a power of two
13467     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13468
13469     // Attempt to load the original value using a single load op.
13470     // Find a scalar type which is equal to the loaded word size.
13471     MVT SclrLoadTy = MVT::i8;
13472     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13473          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13474       MVT Tp = (MVT::SimpleValueType)tp;
13475       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13476         SclrLoadTy = Tp;
13477         break;
13478       }
13479     }
13480
13481     // Proceed if a load word is found.
13482     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13483
13484     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13485       RegSz/SclrLoadTy.getSizeInBits());
13486
13487     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13488                                   RegSz/MemVT.getScalarType().getSizeInBits());
13489     // Can't shuffle using an illegal type.
13490     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13491
13492     // Perform a single load.
13493     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13494                                   Ld->getBasePtr(),
13495                                   Ld->getPointerInfo(), Ld->isVolatile(),
13496                                   Ld->isNonTemporal(), Ld->getAlignment());
13497
13498     // Insert the word loaded into a vector.
13499     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13500       LoadUnitVecVT, ScalarLoad);
13501
13502     // Bitcast the loaded value to a vector of the original element type, in
13503     // the size of the target vector type.
13504     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13505     unsigned SizeRatio = RegSz/MemSz;
13506
13507     // Redistribute the loaded elements into the different locations.
13508     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13509     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13510
13511     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13512                                 DAG.getUNDEF(SlicedVec.getValueType()),
13513                                 ShuffleVec.data());
13514
13515     // Bitcast to the requested type.
13516     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13517     // Replace the original load with the new sequence
13518     // and return the new chain.
13519     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13520     return SDValue(ScalarLoad.getNode(), 1);
13521   }
13522
13523   return SDValue();
13524 }
13525
13526 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13527 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13528                                    const X86Subtarget *Subtarget) {
13529   StoreSDNode *St = cast<StoreSDNode>(N);
13530   EVT VT = St->getValue().getValueType();
13531   EVT StVT = St->getMemoryVT();
13532   DebugLoc dl = St->getDebugLoc();
13533   SDValue StoredVal = St->getOperand(1);
13534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13535
13536   // If we are saving a concatination of two XMM registers, perform two stores.
13537   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13538   // 128-bit ones. If in the future the cost becomes only one memory access the
13539   // first version would be better.
13540   if (VT.getSizeInBits() == 256 &&
13541     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13542     StoredVal.getNumOperands() == 2) {
13543
13544     SDValue Value0 = StoredVal.getOperand(0);
13545     SDValue Value1 = StoredVal.getOperand(1);
13546
13547     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13548     SDValue Ptr0 = St->getBasePtr();
13549     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13550
13551     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13552                                 St->getPointerInfo(), St->isVolatile(),
13553                                 St->isNonTemporal(), St->getAlignment());
13554     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13555                                 St->getPointerInfo(), St->isVolatile(),
13556                                 St->isNonTemporal(), St->getAlignment());
13557     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13558   }
13559
13560   // Optimize trunc store (of multiple scalars) to shuffle and store.
13561   // First, pack all of the elements in one place. Next, store to memory
13562   // in fewer chunks.
13563   if (St->isTruncatingStore() && VT.isVector()) {
13564     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13565     unsigned NumElems = VT.getVectorNumElements();
13566     assert(StVT != VT && "Cannot truncate to the same type");
13567     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13568     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13569
13570     // From, To sizes and ElemCount must be pow of two
13571     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13572     // We are going to use the original vector elt for storing.
13573     // Accumulated smaller vector elements must be a multiple of the store size.
13574     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13575
13576     unsigned SizeRatio  = FromSz / ToSz;
13577
13578     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13579
13580     // Create a type on which we perform the shuffle
13581     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13582             StVT.getScalarType(), NumElems*SizeRatio);
13583
13584     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13585
13586     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13587     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13588     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13589
13590     // Can't shuffle using an illegal type
13591     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13592
13593     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13594                                 DAG.getUNDEF(WideVec.getValueType()),
13595                                 ShuffleVec.data());
13596     // At this point all of the data is stored at the bottom of the
13597     // register. We now need to save it to mem.
13598
13599     // Find the largest store unit
13600     MVT StoreType = MVT::i8;
13601     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13602          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13603       MVT Tp = (MVT::SimpleValueType)tp;
13604       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13605         StoreType = Tp;
13606     }
13607
13608     // Bitcast the original vector into a vector of store-size units
13609     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13610             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13611     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13612     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13613     SmallVector<SDValue, 8> Chains;
13614     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13615                                         TLI.getPointerTy());
13616     SDValue Ptr = St->getBasePtr();
13617
13618     // Perform one or more big stores into memory.
13619     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13620       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13621                                    StoreType, ShuffWide,
13622                                    DAG.getIntPtrConstant(i));
13623       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13624                                 St->getPointerInfo(), St->isVolatile(),
13625                                 St->isNonTemporal(), St->getAlignment());
13626       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13627       Chains.push_back(Ch);
13628     }
13629
13630     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13631                                Chains.size());
13632   }
13633
13634
13635   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13636   // the FP state in cases where an emms may be missing.
13637   // A preferable solution to the general problem is to figure out the right
13638   // places to insert EMMS.  This qualifies as a quick hack.
13639
13640   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13641   if (VT.getSizeInBits() != 64)
13642     return SDValue();
13643
13644   const Function *F = DAG.getMachineFunction().getFunction();
13645   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13646   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13647                      && Subtarget->hasXMMInt();
13648   if ((VT.isVector() ||
13649        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13650       isa<LoadSDNode>(St->getValue()) &&
13651       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13652       St->getChain().hasOneUse() && !St->isVolatile()) {
13653     SDNode* LdVal = St->getValue().getNode();
13654     LoadSDNode *Ld = 0;
13655     int TokenFactorIndex = -1;
13656     SmallVector<SDValue, 8> Ops;
13657     SDNode* ChainVal = St->getChain().getNode();
13658     // Must be a store of a load.  We currently handle two cases:  the load
13659     // is a direct child, and it's under an intervening TokenFactor.  It is
13660     // possible to dig deeper under nested TokenFactors.
13661     if (ChainVal == LdVal)
13662       Ld = cast<LoadSDNode>(St->getChain());
13663     else if (St->getValue().hasOneUse() &&
13664              ChainVal->getOpcode() == ISD::TokenFactor) {
13665       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13666         if (ChainVal->getOperand(i).getNode() == LdVal) {
13667           TokenFactorIndex = i;
13668           Ld = cast<LoadSDNode>(St->getValue());
13669         } else
13670           Ops.push_back(ChainVal->getOperand(i));
13671       }
13672     }
13673
13674     if (!Ld || !ISD::isNormalLoad(Ld))
13675       return SDValue();
13676
13677     // If this is not the MMX case, i.e. we are just turning i64 load/store
13678     // into f64 load/store, avoid the transformation if there are multiple
13679     // uses of the loaded value.
13680     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13681       return SDValue();
13682
13683     DebugLoc LdDL = Ld->getDebugLoc();
13684     DebugLoc StDL = N->getDebugLoc();
13685     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13686     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13687     // pair instead.
13688     if (Subtarget->is64Bit() || F64IsLegal) {
13689       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13690       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13691                                   Ld->getPointerInfo(), Ld->isVolatile(),
13692                                   Ld->isNonTemporal(), Ld->getAlignment());
13693       SDValue NewChain = NewLd.getValue(1);
13694       if (TokenFactorIndex != -1) {
13695         Ops.push_back(NewChain);
13696         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13697                                Ops.size());
13698       }
13699       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13700                           St->getPointerInfo(),
13701                           St->isVolatile(), St->isNonTemporal(),
13702                           St->getAlignment());
13703     }
13704
13705     // Otherwise, lower to two pairs of 32-bit loads / stores.
13706     SDValue LoAddr = Ld->getBasePtr();
13707     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13708                                  DAG.getConstant(4, MVT::i32));
13709
13710     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13711                                Ld->getPointerInfo(),
13712                                Ld->isVolatile(), Ld->isNonTemporal(),
13713                                Ld->getAlignment());
13714     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13715                                Ld->getPointerInfo().getWithOffset(4),
13716                                Ld->isVolatile(), Ld->isNonTemporal(),
13717                                MinAlign(Ld->getAlignment(), 4));
13718
13719     SDValue NewChain = LoLd.getValue(1);
13720     if (TokenFactorIndex != -1) {
13721       Ops.push_back(LoLd);
13722       Ops.push_back(HiLd);
13723       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13724                              Ops.size());
13725     }
13726
13727     LoAddr = St->getBasePtr();
13728     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13729                          DAG.getConstant(4, MVT::i32));
13730
13731     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13732                                 St->getPointerInfo(),
13733                                 St->isVolatile(), St->isNonTemporal(),
13734                                 St->getAlignment());
13735     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13736                                 St->getPointerInfo().getWithOffset(4),
13737                                 St->isVolatile(),
13738                                 St->isNonTemporal(),
13739                                 MinAlign(St->getAlignment(), 4));
13740     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13741   }
13742   return SDValue();
13743 }
13744
13745 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
13746 /// and return the operands for the horizontal operation in LHS and RHS.  A
13747 /// horizontal operation performs the binary operation on successive elements
13748 /// of its first operand, then on successive elements of its second operand,
13749 /// returning the resulting values in a vector.  For example, if
13750 ///   A = < float a0, float a1, float a2, float a3 >
13751 /// and
13752 ///   B = < float b0, float b1, float b2, float b3 >
13753 /// then the result of doing a horizontal operation on A and B is
13754 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
13755 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
13756 /// A horizontal-op B, for some already available A and B, and if so then LHS is
13757 /// set to A, RHS to B, and the routine returns 'true'.
13758 /// Note that the binary operation should have the property that if one of the
13759 /// operands is UNDEF then the result is UNDEF.
13760 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
13761   // Look for the following pattern: if
13762   //   A = < float a0, float a1, float a2, float a3 >
13763   //   B = < float b0, float b1, float b2, float b3 >
13764   // and
13765   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
13766   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
13767   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
13768   // which is A horizontal-op B.
13769
13770   // At least one of the operands should be a vector shuffle.
13771   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13772       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
13773     return false;
13774
13775   EVT VT = LHS.getValueType();
13776   unsigned N = VT.getVectorNumElements();
13777
13778   // View LHS in the form
13779   //   LHS = VECTOR_SHUFFLE A, B, LMask
13780   // If LHS is not a shuffle then pretend it is the shuffle
13781   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
13782   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
13783   // type VT.
13784   SDValue A, B;
13785   SmallVector<int, 8> LMask(N);
13786   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13787     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
13788       A = LHS.getOperand(0);
13789     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
13790       B = LHS.getOperand(1);
13791     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
13792   } else {
13793     if (LHS.getOpcode() != ISD::UNDEF)
13794       A = LHS;
13795     for (unsigned i = 0; i != N; ++i)
13796       LMask[i] = i;
13797   }
13798
13799   // Likewise, view RHS in the form
13800   //   RHS = VECTOR_SHUFFLE C, D, RMask
13801   SDValue C, D;
13802   SmallVector<int, 8> RMask(N);
13803   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13804     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
13805       C = RHS.getOperand(0);
13806     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
13807       D = RHS.getOperand(1);
13808     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
13809   } else {
13810     if (RHS.getOpcode() != ISD::UNDEF)
13811       C = RHS;
13812     for (unsigned i = 0; i != N; ++i)
13813       RMask[i] = i;
13814   }
13815
13816   // Check that the shuffles are both shuffling the same vectors.
13817   if (!(A == C && B == D) && !(A == D && B == C))
13818     return false;
13819
13820   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
13821   if (!A.getNode() && !B.getNode())
13822     return false;
13823
13824   // If A and B occur in reverse order in RHS, then "swap" them (which means
13825   // rewriting the mask).
13826   if (A != C)
13827     for (unsigned i = 0; i != N; ++i) {
13828       unsigned Idx = RMask[i];
13829       if (Idx < N)
13830         RMask[i] += N;
13831       else if (Idx < 2*N)
13832         RMask[i] -= N;
13833     }
13834
13835   // At this point LHS and RHS are equivalent to
13836   //   LHS = VECTOR_SHUFFLE A, B, LMask
13837   //   RHS = VECTOR_SHUFFLE A, B, RMask
13838   // Check that the masks correspond to performing a horizontal operation.
13839   for (unsigned i = 0; i != N; ++i) {
13840     unsigned LIdx = LMask[i], RIdx = RMask[i];
13841
13842     // Ignore any UNDEF components.
13843     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
13844         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
13845       continue;
13846
13847     // Check that successive elements are being operated on.  If not, this is
13848     // not a horizontal operation.
13849     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
13850         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
13851       return false;
13852   }
13853
13854   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
13855   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
13856   return true;
13857 }
13858
13859 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
13860 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
13861                                   const X86Subtarget *Subtarget) {
13862   EVT VT = N->getValueType(0);
13863   SDValue LHS = N->getOperand(0);
13864   SDValue RHS = N->getOperand(1);
13865
13866   // Try to synthesize horizontal adds from adds of shuffles.
13867   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13868       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13869       isHorizontalBinOp(LHS, RHS, true))
13870     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
13871   return SDValue();
13872 }
13873
13874 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
13875 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
13876                                   const X86Subtarget *Subtarget) {
13877   EVT VT = N->getValueType(0);
13878   SDValue LHS = N->getOperand(0);
13879   SDValue RHS = N->getOperand(1);
13880
13881   // Try to synthesize horizontal subs from subs of shuffles.
13882   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13883       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13884       isHorizontalBinOp(LHS, RHS, false))
13885     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
13886   return SDValue();
13887 }
13888
13889 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13890 /// X86ISD::FXOR nodes.
13891 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13892   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13893   // F[X]OR(0.0, x) -> x
13894   // F[X]OR(x, 0.0) -> x
13895   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13896     if (C->getValueAPF().isPosZero())
13897       return N->getOperand(1);
13898   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13899     if (C->getValueAPF().isPosZero())
13900       return N->getOperand(0);
13901   return SDValue();
13902 }
13903
13904 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13905 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13906   // FAND(0.0, x) -> 0.0
13907   // FAND(x, 0.0) -> 0.0
13908   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13909     if (C->getValueAPF().isPosZero())
13910       return N->getOperand(0);
13911   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13912     if (C->getValueAPF().isPosZero())
13913       return N->getOperand(1);
13914   return SDValue();
13915 }
13916
13917 static SDValue PerformBTCombine(SDNode *N,
13918                                 SelectionDAG &DAG,
13919                                 TargetLowering::DAGCombinerInfo &DCI) {
13920   // BT ignores high bits in the bit index operand.
13921   SDValue Op1 = N->getOperand(1);
13922   if (Op1.hasOneUse()) {
13923     unsigned BitWidth = Op1.getValueSizeInBits();
13924     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13925     APInt KnownZero, KnownOne;
13926     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13927                                           !DCI.isBeforeLegalizeOps());
13928     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13929     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13930         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13931       DCI.CommitTargetLoweringOpt(TLO);
13932   }
13933   return SDValue();
13934 }
13935
13936 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13937   SDValue Op = N->getOperand(0);
13938   if (Op.getOpcode() == ISD::BITCAST)
13939     Op = Op.getOperand(0);
13940   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13941   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13942       VT.getVectorElementType().getSizeInBits() ==
13943       OpVT.getVectorElementType().getSizeInBits()) {
13944     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13945   }
13946   return SDValue();
13947 }
13948
13949 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13950   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13951   //           (and (i32 x86isd::setcc_carry), 1)
13952   // This eliminates the zext. This transformation is necessary because
13953   // ISD::SETCC is always legalized to i8.
13954   DebugLoc dl = N->getDebugLoc();
13955   SDValue N0 = N->getOperand(0);
13956   EVT VT = N->getValueType(0);
13957   if (N0.getOpcode() == ISD::AND &&
13958       N0.hasOneUse() &&
13959       N0.getOperand(0).hasOneUse()) {
13960     SDValue N00 = N0.getOperand(0);
13961     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13962       return SDValue();
13963     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13964     if (!C || C->getZExtValue() != 1)
13965       return SDValue();
13966     return DAG.getNode(ISD::AND, dl, VT,
13967                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13968                                    N00.getOperand(0), N00.getOperand(1)),
13969                        DAG.getConstant(1, VT));
13970   }
13971
13972   return SDValue();
13973 }
13974
13975 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13976 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13977   unsigned X86CC = N->getConstantOperandVal(0);
13978   SDValue EFLAG = N->getOperand(1);
13979   DebugLoc DL = N->getDebugLoc();
13980
13981   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13982   // a zext and produces an all-ones bit which is more useful than 0/1 in some
13983   // cases.
13984   if (X86CC == X86::COND_B)
13985     return DAG.getNode(ISD::AND, DL, MVT::i8,
13986                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13987                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
13988                        DAG.getConstant(1, MVT::i8));
13989
13990   return SDValue();
13991 }
13992
13993 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13994                                         const X86TargetLowering *XTLI) {
13995   SDValue Op0 = N->getOperand(0);
13996   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13997   // a 32-bit target where SSE doesn't support i64->FP operations.
13998   if (Op0.getOpcode() == ISD::LOAD) {
13999     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14000     EVT VT = Ld->getValueType(0);
14001     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14002         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14003         !XTLI->getSubtarget()->is64Bit() &&
14004         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14005       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14006                                           Ld->getChain(), Op0, DAG);
14007       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14008       return FILDChain;
14009     }
14010   }
14011   return SDValue();
14012 }
14013
14014 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14015 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14016                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14017   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14018   // the result is either zero or one (depending on the input carry bit).
14019   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14020   if (X86::isZeroNode(N->getOperand(0)) &&
14021       X86::isZeroNode(N->getOperand(1)) &&
14022       // We don't have a good way to replace an EFLAGS use, so only do this when
14023       // dead right now.
14024       SDValue(N, 1).use_empty()) {
14025     DebugLoc DL = N->getDebugLoc();
14026     EVT VT = N->getValueType(0);
14027     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14028     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14029                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14030                                            DAG.getConstant(X86::COND_B,MVT::i8),
14031                                            N->getOperand(2)),
14032                                DAG.getConstant(1, VT));
14033     return DCI.CombineTo(N, Res1, CarryOut);
14034   }
14035
14036   return SDValue();
14037 }
14038
14039 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14040 //      (add Y, (setne X, 0)) -> sbb -1, Y
14041 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14042 //      (sub (setne X, 0), Y) -> adc -1, Y
14043 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14044   DebugLoc DL = N->getDebugLoc();
14045
14046   // Look through ZExts.
14047   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14048   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14049     return SDValue();
14050
14051   SDValue SetCC = Ext.getOperand(0);
14052   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14053     return SDValue();
14054
14055   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14056   if (CC != X86::COND_E && CC != X86::COND_NE)
14057     return SDValue();
14058
14059   SDValue Cmp = SetCC.getOperand(1);
14060   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14061       !X86::isZeroNode(Cmp.getOperand(1)) ||
14062       !Cmp.getOperand(0).getValueType().isInteger())
14063     return SDValue();
14064
14065   SDValue CmpOp0 = Cmp.getOperand(0);
14066   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14067                                DAG.getConstant(1, CmpOp0.getValueType()));
14068
14069   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14070   if (CC == X86::COND_NE)
14071     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14072                        DL, OtherVal.getValueType(), OtherVal,
14073                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14074   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14075                      DL, OtherVal.getValueType(), OtherVal,
14076                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14077 }
14078
14079 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14080   SDValue Op0 = N->getOperand(0);
14081   SDValue Op1 = N->getOperand(1);
14082
14083   // X86 can't encode an immediate LHS of a sub. See if we can push the
14084   // negation into a preceding instruction.
14085   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14086     // If the RHS of the sub is a XOR with one use and a constant, invert the
14087     // immediate. Then add one to the LHS of the sub so we can turn
14088     // X-Y -> X+~Y+1, saving one register.
14089     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14090         isa<ConstantSDNode>(Op1.getOperand(1))) {
14091       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14092       EVT VT = Op0.getValueType();
14093       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14094                                    Op1.getOperand(0),
14095                                    DAG.getConstant(~XorC, VT));
14096       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14097                          DAG.getConstant(C->getAPIntValue()+1, VT));
14098     }
14099   }
14100
14101   return OptimizeConditionalInDecrement(N, DAG);
14102 }
14103
14104 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14105                                              DAGCombinerInfo &DCI) const {
14106   SelectionDAG &DAG = DCI.DAG;
14107   switch (N->getOpcode()) {
14108   default: break;
14109   case ISD::EXTRACT_VECTOR_ELT:
14110     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14111   case ISD::VSELECT:
14112   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14113   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14114   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14115   case ISD::SUB:            return PerformSubCombine(N, DAG);
14116   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14117   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14118   case ISD::SHL:
14119   case ISD::SRA:
14120   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14121   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14122   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14123   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14124   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14125   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14126   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14127   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14128   case X86ISD::FXOR:
14129   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14130   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14131   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14132   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14133   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14134   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14135   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14136   case X86ISD::SHUFPD:
14137   case X86ISD::PALIGN:
14138   case X86ISD::PUNPCKHBW:
14139   case X86ISD::PUNPCKHWD:
14140   case X86ISD::PUNPCKHDQ:
14141   case X86ISD::PUNPCKHQDQ:
14142   case X86ISD::UNPCKHPS:
14143   case X86ISD::UNPCKHPD:
14144   case X86ISD::VUNPCKHPSY:
14145   case X86ISD::VUNPCKHPDY:
14146   case X86ISD::PUNPCKLBW:
14147   case X86ISD::PUNPCKLWD:
14148   case X86ISD::PUNPCKLDQ:
14149   case X86ISD::PUNPCKLQDQ:
14150   case X86ISD::UNPCKLPS:
14151   case X86ISD::UNPCKLPD:
14152   case X86ISD::VUNPCKLPSY:
14153   case X86ISD::VUNPCKLPDY:
14154   case X86ISD::MOVHLPS:
14155   case X86ISD::MOVLHPS:
14156   case X86ISD::PSHUFD:
14157   case X86ISD::PSHUFHW:
14158   case X86ISD::PSHUFLW:
14159   case X86ISD::MOVSS:
14160   case X86ISD::MOVSD:
14161   case X86ISD::VPERMILPS:
14162   case X86ISD::VPERMILPSY:
14163   case X86ISD::VPERMILPD:
14164   case X86ISD::VPERMILPDY:
14165   case X86ISD::VPERM2F128:
14166   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14167   }
14168
14169   return SDValue();
14170 }
14171
14172 /// isTypeDesirableForOp - Return true if the target has native support for
14173 /// the specified value type and it is 'desirable' to use the type for the
14174 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14175 /// instruction encodings are longer and some i16 instructions are slow.
14176 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14177   if (!isTypeLegal(VT))
14178     return false;
14179   if (VT != MVT::i16)
14180     return true;
14181
14182   switch (Opc) {
14183   default:
14184     return true;
14185   case ISD::LOAD:
14186   case ISD::SIGN_EXTEND:
14187   case ISD::ZERO_EXTEND:
14188   case ISD::ANY_EXTEND:
14189   case ISD::SHL:
14190   case ISD::SRL:
14191   case ISD::SUB:
14192   case ISD::ADD:
14193   case ISD::MUL:
14194   case ISD::AND:
14195   case ISD::OR:
14196   case ISD::XOR:
14197     return false;
14198   }
14199 }
14200
14201 /// IsDesirableToPromoteOp - This method query the target whether it is
14202 /// beneficial for dag combiner to promote the specified node. If true, it
14203 /// should return the desired promotion type by reference.
14204 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14205   EVT VT = Op.getValueType();
14206   if (VT != MVT::i16)
14207     return false;
14208
14209   bool Promote = false;
14210   bool Commute = false;
14211   switch (Op.getOpcode()) {
14212   default: break;
14213   case ISD::LOAD: {
14214     LoadSDNode *LD = cast<LoadSDNode>(Op);
14215     // If the non-extending load has a single use and it's not live out, then it
14216     // might be folded.
14217     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14218                                                      Op.hasOneUse()*/) {
14219       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14220              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14221         // The only case where we'd want to promote LOAD (rather then it being
14222         // promoted as an operand is when it's only use is liveout.
14223         if (UI->getOpcode() != ISD::CopyToReg)
14224           return false;
14225       }
14226     }
14227     Promote = true;
14228     break;
14229   }
14230   case ISD::SIGN_EXTEND:
14231   case ISD::ZERO_EXTEND:
14232   case ISD::ANY_EXTEND:
14233     Promote = true;
14234     break;
14235   case ISD::SHL:
14236   case ISD::SRL: {
14237     SDValue N0 = Op.getOperand(0);
14238     // Look out for (store (shl (load), x)).
14239     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14240       return false;
14241     Promote = true;
14242     break;
14243   }
14244   case ISD::ADD:
14245   case ISD::MUL:
14246   case ISD::AND:
14247   case ISD::OR:
14248   case ISD::XOR:
14249     Commute = true;
14250     // fallthrough
14251   case ISD::SUB: {
14252     SDValue N0 = Op.getOperand(0);
14253     SDValue N1 = Op.getOperand(1);
14254     if (!Commute && MayFoldLoad(N1))
14255       return false;
14256     // Avoid disabling potential load folding opportunities.
14257     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14258       return false;
14259     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14260       return false;
14261     Promote = true;
14262   }
14263   }
14264
14265   PVT = MVT::i32;
14266   return Promote;
14267 }
14268
14269 //===----------------------------------------------------------------------===//
14270 //                           X86 Inline Assembly Support
14271 //===----------------------------------------------------------------------===//
14272
14273 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14274   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14275
14276   std::string AsmStr = IA->getAsmString();
14277
14278   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14279   SmallVector<StringRef, 4> AsmPieces;
14280   SplitString(AsmStr, AsmPieces, ";\n");
14281
14282   switch (AsmPieces.size()) {
14283   default: return false;
14284   case 1:
14285     AsmStr = AsmPieces[0];
14286     AsmPieces.clear();
14287     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14288
14289     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14290     // we will turn this bswap into something that will be lowered to logical ops
14291     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14292     // so don't worry about this.
14293     // bswap $0
14294     if (AsmPieces.size() == 2 &&
14295         (AsmPieces[0] == "bswap" ||
14296          AsmPieces[0] == "bswapq" ||
14297          AsmPieces[0] == "bswapl") &&
14298         (AsmPieces[1] == "$0" ||
14299          AsmPieces[1] == "${0:q}")) {
14300       // No need to check constraints, nothing other than the equivalent of
14301       // "=r,0" would be valid here.
14302       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14303       if (!Ty || Ty->getBitWidth() % 16 != 0)
14304         return false;
14305       return IntrinsicLowering::LowerToByteSwap(CI);
14306     }
14307     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14308     if (CI->getType()->isIntegerTy(16) &&
14309         AsmPieces.size() == 3 &&
14310         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14311         AsmPieces[1] == "$$8," &&
14312         AsmPieces[2] == "${0:w}" &&
14313         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14314       AsmPieces.clear();
14315       const std::string &ConstraintsStr = IA->getConstraintString();
14316       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14317       std::sort(AsmPieces.begin(), AsmPieces.end());
14318       if (AsmPieces.size() == 4 &&
14319           AsmPieces[0] == "~{cc}" &&
14320           AsmPieces[1] == "~{dirflag}" &&
14321           AsmPieces[2] == "~{flags}" &&
14322           AsmPieces[3] == "~{fpsr}") {
14323         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14324         if (!Ty || Ty->getBitWidth() % 16 != 0)
14325           return false;
14326         return IntrinsicLowering::LowerToByteSwap(CI);
14327       }
14328     }
14329     break;
14330   case 3:
14331     if (CI->getType()->isIntegerTy(32) &&
14332         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14333       SmallVector<StringRef, 4> Words;
14334       SplitString(AsmPieces[0], Words, " \t,");
14335       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14336           Words[2] == "${0:w}") {
14337         Words.clear();
14338         SplitString(AsmPieces[1], Words, " \t,");
14339         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14340             Words[2] == "$0") {
14341           Words.clear();
14342           SplitString(AsmPieces[2], Words, " \t,");
14343           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14344               Words[2] == "${0:w}") {
14345             AsmPieces.clear();
14346             const std::string &ConstraintsStr = IA->getConstraintString();
14347             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14348             std::sort(AsmPieces.begin(), AsmPieces.end());
14349             if (AsmPieces.size() == 4 &&
14350                 AsmPieces[0] == "~{cc}" &&
14351                 AsmPieces[1] == "~{dirflag}" &&
14352                 AsmPieces[2] == "~{flags}" &&
14353                 AsmPieces[3] == "~{fpsr}") {
14354               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14355               if (!Ty || Ty->getBitWidth() % 16 != 0)
14356                 return false;
14357               return IntrinsicLowering::LowerToByteSwap(CI);
14358             }
14359           }
14360         }
14361       }
14362     }
14363
14364     if (CI->getType()->isIntegerTy(64)) {
14365       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14366       if (Constraints.size() >= 2 &&
14367           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14368           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14369         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14370         SmallVector<StringRef, 4> Words;
14371         SplitString(AsmPieces[0], Words, " \t");
14372         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14373           Words.clear();
14374           SplitString(AsmPieces[1], Words, " \t");
14375           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14376             Words.clear();
14377             SplitString(AsmPieces[2], Words, " \t,");
14378             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14379                 Words[2] == "%edx") {
14380               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14381               if (!Ty || Ty->getBitWidth() % 16 != 0)
14382                 return false;
14383               return IntrinsicLowering::LowerToByteSwap(CI);
14384             }
14385           }
14386         }
14387       }
14388     }
14389     break;
14390   }
14391   return false;
14392 }
14393
14394
14395
14396 /// getConstraintType - Given a constraint letter, return the type of
14397 /// constraint it is for this target.
14398 X86TargetLowering::ConstraintType
14399 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14400   if (Constraint.size() == 1) {
14401     switch (Constraint[0]) {
14402     case 'R':
14403     case 'q':
14404     case 'Q':
14405     case 'f':
14406     case 't':
14407     case 'u':
14408     case 'y':
14409     case 'x':
14410     case 'Y':
14411     case 'l':
14412       return C_RegisterClass;
14413     case 'a':
14414     case 'b':
14415     case 'c':
14416     case 'd':
14417     case 'S':
14418     case 'D':
14419     case 'A':
14420       return C_Register;
14421     case 'I':
14422     case 'J':
14423     case 'K':
14424     case 'L':
14425     case 'M':
14426     case 'N':
14427     case 'G':
14428     case 'C':
14429     case 'e':
14430     case 'Z':
14431       return C_Other;
14432     default:
14433       break;
14434     }
14435   }
14436   return TargetLowering::getConstraintType(Constraint);
14437 }
14438
14439 /// Examine constraint type and operand type and determine a weight value.
14440 /// This object must already have been set up with the operand type
14441 /// and the current alternative constraint selected.
14442 TargetLowering::ConstraintWeight
14443   X86TargetLowering::getSingleConstraintMatchWeight(
14444     AsmOperandInfo &info, const char *constraint) const {
14445   ConstraintWeight weight = CW_Invalid;
14446   Value *CallOperandVal = info.CallOperandVal;
14447     // If we don't have a value, we can't do a match,
14448     // but allow it at the lowest weight.
14449   if (CallOperandVal == NULL)
14450     return CW_Default;
14451   Type *type = CallOperandVal->getType();
14452   // Look at the constraint type.
14453   switch (*constraint) {
14454   default:
14455     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14456   case 'R':
14457   case 'q':
14458   case 'Q':
14459   case 'a':
14460   case 'b':
14461   case 'c':
14462   case 'd':
14463   case 'S':
14464   case 'D':
14465   case 'A':
14466     if (CallOperandVal->getType()->isIntegerTy())
14467       weight = CW_SpecificReg;
14468     break;
14469   case 'f':
14470   case 't':
14471   case 'u':
14472       if (type->isFloatingPointTy())
14473         weight = CW_SpecificReg;
14474       break;
14475   case 'y':
14476       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14477         weight = CW_SpecificReg;
14478       break;
14479   case 'x':
14480   case 'Y':
14481     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14482       weight = CW_Register;
14483     break;
14484   case 'I':
14485     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14486       if (C->getZExtValue() <= 31)
14487         weight = CW_Constant;
14488     }
14489     break;
14490   case 'J':
14491     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14492       if (C->getZExtValue() <= 63)
14493         weight = CW_Constant;
14494     }
14495     break;
14496   case 'K':
14497     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14498       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14499         weight = CW_Constant;
14500     }
14501     break;
14502   case 'L':
14503     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14504       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14505         weight = CW_Constant;
14506     }
14507     break;
14508   case 'M':
14509     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14510       if (C->getZExtValue() <= 3)
14511         weight = CW_Constant;
14512     }
14513     break;
14514   case 'N':
14515     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14516       if (C->getZExtValue() <= 0xff)
14517         weight = CW_Constant;
14518     }
14519     break;
14520   case 'G':
14521   case 'C':
14522     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14523       weight = CW_Constant;
14524     }
14525     break;
14526   case 'e':
14527     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14528       if ((C->getSExtValue() >= -0x80000000LL) &&
14529           (C->getSExtValue() <= 0x7fffffffLL))
14530         weight = CW_Constant;
14531     }
14532     break;
14533   case 'Z':
14534     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14535       if (C->getZExtValue() <= 0xffffffff)
14536         weight = CW_Constant;
14537     }
14538     break;
14539   }
14540   return weight;
14541 }
14542
14543 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14544 /// with another that has more specific requirements based on the type of the
14545 /// corresponding operand.
14546 const char *X86TargetLowering::
14547 LowerXConstraint(EVT ConstraintVT) const {
14548   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14549   // 'f' like normal targets.
14550   if (ConstraintVT.isFloatingPoint()) {
14551     if (Subtarget->hasXMMInt())
14552       return "Y";
14553     if (Subtarget->hasXMM())
14554       return "x";
14555   }
14556
14557   return TargetLowering::LowerXConstraint(ConstraintVT);
14558 }
14559
14560 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14561 /// vector.  If it is invalid, don't add anything to Ops.
14562 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14563                                                      std::string &Constraint,
14564                                                      std::vector<SDValue>&Ops,
14565                                                      SelectionDAG &DAG) const {
14566   SDValue Result(0, 0);
14567
14568   // Only support length 1 constraints for now.
14569   if (Constraint.length() > 1) return;
14570
14571   char ConstraintLetter = Constraint[0];
14572   switch (ConstraintLetter) {
14573   default: break;
14574   case 'I':
14575     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14576       if (C->getZExtValue() <= 31) {
14577         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14578         break;
14579       }
14580     }
14581     return;
14582   case 'J':
14583     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14584       if (C->getZExtValue() <= 63) {
14585         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14586         break;
14587       }
14588     }
14589     return;
14590   case 'K':
14591     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14592       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14593         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14594         break;
14595       }
14596     }
14597     return;
14598   case 'N':
14599     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14600       if (C->getZExtValue() <= 255) {
14601         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14602         break;
14603       }
14604     }
14605     return;
14606   case 'e': {
14607     // 32-bit signed value
14608     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14609       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14610                                            C->getSExtValue())) {
14611         // Widen to 64 bits here to get it sign extended.
14612         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14613         break;
14614       }
14615     // FIXME gcc accepts some relocatable values here too, but only in certain
14616     // memory models; it's complicated.
14617     }
14618     return;
14619   }
14620   case 'Z': {
14621     // 32-bit unsigned value
14622     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14623       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14624                                            C->getZExtValue())) {
14625         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14626         break;
14627       }
14628     }
14629     // FIXME gcc accepts some relocatable values here too, but only in certain
14630     // memory models; it's complicated.
14631     return;
14632   }
14633   case 'i': {
14634     // Literal immediates are always ok.
14635     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14636       // Widen to 64 bits here to get it sign extended.
14637       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14638       break;
14639     }
14640
14641     // In any sort of PIC mode addresses need to be computed at runtime by
14642     // adding in a register or some sort of table lookup.  These can't
14643     // be used as immediates.
14644     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14645       return;
14646
14647     // If we are in non-pic codegen mode, we allow the address of a global (with
14648     // an optional displacement) to be used with 'i'.
14649     GlobalAddressSDNode *GA = 0;
14650     int64_t Offset = 0;
14651
14652     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14653     while (1) {
14654       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14655         Offset += GA->getOffset();
14656         break;
14657       } else if (Op.getOpcode() == ISD::ADD) {
14658         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14659           Offset += C->getZExtValue();
14660           Op = Op.getOperand(0);
14661           continue;
14662         }
14663       } else if (Op.getOpcode() == ISD::SUB) {
14664         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14665           Offset += -C->getZExtValue();
14666           Op = Op.getOperand(0);
14667           continue;
14668         }
14669       }
14670
14671       // Otherwise, this isn't something we can handle, reject it.
14672       return;
14673     }
14674
14675     const GlobalValue *GV = GA->getGlobal();
14676     // If we require an extra load to get this address, as in PIC mode, we
14677     // can't accept it.
14678     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14679                                                         getTargetMachine())))
14680       return;
14681
14682     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14683                                         GA->getValueType(0), Offset);
14684     break;
14685   }
14686   }
14687
14688   if (Result.getNode()) {
14689     Ops.push_back(Result);
14690     return;
14691   }
14692   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14693 }
14694
14695 std::pair<unsigned, const TargetRegisterClass*>
14696 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14697                                                 EVT VT) const {
14698   // First, see if this is a constraint that directly corresponds to an LLVM
14699   // register class.
14700   if (Constraint.size() == 1) {
14701     // GCC Constraint Letters
14702     switch (Constraint[0]) {
14703     default: break;
14704       // TODO: Slight differences here in allocation order and leaving
14705       // RIP in the class. Do they matter any more here than they do
14706       // in the normal allocation?
14707     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14708       if (Subtarget->is64Bit()) {
14709         if (VT == MVT::i32 || VT == MVT::f32)
14710           return std::make_pair(0U, X86::GR32RegisterClass);
14711         else if (VT == MVT::i16)
14712           return std::make_pair(0U, X86::GR16RegisterClass);
14713         else if (VT == MVT::i8 || VT == MVT::i1)
14714           return std::make_pair(0U, X86::GR8RegisterClass);
14715         else if (VT == MVT::i64 || VT == MVT::f64)
14716           return std::make_pair(0U, X86::GR64RegisterClass);
14717         break;
14718       }
14719       // 32-bit fallthrough
14720     case 'Q':   // Q_REGS
14721       if (VT == MVT::i32 || VT == MVT::f32)
14722         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14723       else if (VT == MVT::i16)
14724         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14725       else if (VT == MVT::i8 || VT == MVT::i1)
14726         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14727       else if (VT == MVT::i64)
14728         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14729       break;
14730     case 'r':   // GENERAL_REGS
14731     case 'l':   // INDEX_REGS
14732       if (VT == MVT::i8 || VT == MVT::i1)
14733         return std::make_pair(0U, X86::GR8RegisterClass);
14734       if (VT == MVT::i16)
14735         return std::make_pair(0U, X86::GR16RegisterClass);
14736       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14737         return std::make_pair(0U, X86::GR32RegisterClass);
14738       return std::make_pair(0U, X86::GR64RegisterClass);
14739     case 'R':   // LEGACY_REGS
14740       if (VT == MVT::i8 || VT == MVT::i1)
14741         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14742       if (VT == MVT::i16)
14743         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14744       if (VT == MVT::i32 || !Subtarget->is64Bit())
14745         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14746       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14747     case 'f':  // FP Stack registers.
14748       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14749       // value to the correct fpstack register class.
14750       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14751         return std::make_pair(0U, X86::RFP32RegisterClass);
14752       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14753         return std::make_pair(0U, X86::RFP64RegisterClass);
14754       return std::make_pair(0U, X86::RFP80RegisterClass);
14755     case 'y':   // MMX_REGS if MMX allowed.
14756       if (!Subtarget->hasMMX()) break;
14757       return std::make_pair(0U, X86::VR64RegisterClass);
14758     case 'Y':   // SSE_REGS if SSE2 allowed
14759       if (!Subtarget->hasXMMInt()) break;
14760       // FALL THROUGH.
14761     case 'x':   // SSE_REGS if SSE1 allowed
14762       if (!Subtarget->hasXMM()) break;
14763
14764       switch (VT.getSimpleVT().SimpleTy) {
14765       default: break;
14766       // Scalar SSE types.
14767       case MVT::f32:
14768       case MVT::i32:
14769         return std::make_pair(0U, X86::FR32RegisterClass);
14770       case MVT::f64:
14771       case MVT::i64:
14772         return std::make_pair(0U, X86::FR64RegisterClass);
14773       // Vector types.
14774       case MVT::v16i8:
14775       case MVT::v8i16:
14776       case MVT::v4i32:
14777       case MVT::v2i64:
14778       case MVT::v4f32:
14779       case MVT::v2f64:
14780         return std::make_pair(0U, X86::VR128RegisterClass);
14781       }
14782       break;
14783     }
14784   }
14785
14786   // Use the default implementation in TargetLowering to convert the register
14787   // constraint into a member of a register class.
14788   std::pair<unsigned, const TargetRegisterClass*> Res;
14789   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14790
14791   // Not found as a standard register?
14792   if (Res.second == 0) {
14793     // Map st(0) -> st(7) -> ST0
14794     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14795         tolower(Constraint[1]) == 's' &&
14796         tolower(Constraint[2]) == 't' &&
14797         Constraint[3] == '(' &&
14798         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14799         Constraint[5] == ')' &&
14800         Constraint[6] == '}') {
14801
14802       Res.first = X86::ST0+Constraint[4]-'0';
14803       Res.second = X86::RFP80RegisterClass;
14804       return Res;
14805     }
14806
14807     // GCC allows "st(0)" to be called just plain "st".
14808     if (StringRef("{st}").equals_lower(Constraint)) {
14809       Res.first = X86::ST0;
14810       Res.second = X86::RFP80RegisterClass;
14811       return Res;
14812     }
14813
14814     // flags -> EFLAGS
14815     if (StringRef("{flags}").equals_lower(Constraint)) {
14816       Res.first = X86::EFLAGS;
14817       Res.second = X86::CCRRegisterClass;
14818       return Res;
14819     }
14820
14821     // 'A' means EAX + EDX.
14822     if (Constraint == "A") {
14823       Res.first = X86::EAX;
14824       Res.second = X86::GR32_ADRegisterClass;
14825       return Res;
14826     }
14827     return Res;
14828   }
14829
14830   // Otherwise, check to see if this is a register class of the wrong value
14831   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14832   // turn into {ax},{dx}.
14833   if (Res.second->hasType(VT))
14834     return Res;   // Correct type already, nothing to do.
14835
14836   // All of the single-register GCC register classes map their values onto
14837   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14838   // really want an 8-bit or 32-bit register, map to the appropriate register
14839   // class and return the appropriate register.
14840   if (Res.second == X86::GR16RegisterClass) {
14841     if (VT == MVT::i8) {
14842       unsigned DestReg = 0;
14843       switch (Res.first) {
14844       default: break;
14845       case X86::AX: DestReg = X86::AL; break;
14846       case X86::DX: DestReg = X86::DL; break;
14847       case X86::CX: DestReg = X86::CL; break;
14848       case X86::BX: DestReg = X86::BL; break;
14849       }
14850       if (DestReg) {
14851         Res.first = DestReg;
14852         Res.second = X86::GR8RegisterClass;
14853       }
14854     } else if (VT == MVT::i32) {
14855       unsigned DestReg = 0;
14856       switch (Res.first) {
14857       default: break;
14858       case X86::AX: DestReg = X86::EAX; break;
14859       case X86::DX: DestReg = X86::EDX; break;
14860       case X86::CX: DestReg = X86::ECX; break;
14861       case X86::BX: DestReg = X86::EBX; break;
14862       case X86::SI: DestReg = X86::ESI; break;
14863       case X86::DI: DestReg = X86::EDI; break;
14864       case X86::BP: DestReg = X86::EBP; break;
14865       case X86::SP: DestReg = X86::ESP; break;
14866       }
14867       if (DestReg) {
14868         Res.first = DestReg;
14869         Res.second = X86::GR32RegisterClass;
14870       }
14871     } else if (VT == MVT::i64) {
14872       unsigned DestReg = 0;
14873       switch (Res.first) {
14874       default: break;
14875       case X86::AX: DestReg = X86::RAX; break;
14876       case X86::DX: DestReg = X86::RDX; break;
14877       case X86::CX: DestReg = X86::RCX; break;
14878       case X86::BX: DestReg = X86::RBX; break;
14879       case X86::SI: DestReg = X86::RSI; break;
14880       case X86::DI: DestReg = X86::RDI; break;
14881       case X86::BP: DestReg = X86::RBP; break;
14882       case X86::SP: DestReg = X86::RSP; break;
14883       }
14884       if (DestReg) {
14885         Res.first = DestReg;
14886         Res.second = X86::GR64RegisterClass;
14887       }
14888     }
14889   } else if (Res.second == X86::FR32RegisterClass ||
14890              Res.second == X86::FR64RegisterClass ||
14891              Res.second == X86::VR128RegisterClass) {
14892     // Handle references to XMM physical registers that got mapped into the
14893     // wrong class.  This can happen with constraints like {xmm0} where the
14894     // target independent register mapper will just pick the first match it can
14895     // find, ignoring the required type.
14896     if (VT == MVT::f32)
14897       Res.second = X86::FR32RegisterClass;
14898     else if (VT == MVT::f64)
14899       Res.second = X86::FR64RegisterClass;
14900     else if (X86::VR128RegisterClass->hasType(VT))
14901       Res.second = X86::VR128RegisterClass;
14902   }
14903
14904   return Res;
14905 }