a2a140f1b8d95d558c0408a0288a378a368e9b0d
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
173   X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   // 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     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
319       // Expand FP_TO_UINT into a select.
320       // FIXME: We would like to use a Custom expander here eventually to do
321       // the optimal thing for SSE vs. the default expansion in the legalizer.
322       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
323     else
324       // With SSE3 we can use fisttpll to convert to a signed i64; without
325       // SSE, we're stuck with a fistpll.
326       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0, e = 4; i != e; ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
382   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
383   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
384   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
385   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
386   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
387   if (Subtarget->is64Bit()) {
388     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
389     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
390   }
391
392   if (Subtarget->hasPOPCNT()) {
393     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
394   } else {
395     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
396     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
397     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
400   }
401
402   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
403   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
404
405   // These should be promoted to a larger select which is supported.
406   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
407   // X86 wants to expand cmov itself.
408   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
413   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
419   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
422     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
423   }
424   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
425
426   // Darwin ABI issue.
427   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
428   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
429   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
431   if (Subtarget->is64Bit())
432     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
433   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
434   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
435   if (Subtarget->is64Bit()) {
436     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
437     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
438     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
439     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
440     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
441   }
442   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
443   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
444   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
446   if (Subtarget->is64Bit()) {
447     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
448     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
450   }
451
452   if (Subtarget->hasXMM())
453     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
454
455   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // On X86 and X86-64, atomic operations are lowered to locked instructions.
459   // Locked instructions, in turn, have implicit fence semantics (all memory
460   // operations are flushed before issuing the locked instruction, and they
461   // are not buffered), so we can fold away the common pattern of
462   // fence-atomic-fence.
463   setShouldFoldAtomicFences(true);
464
465   // Expand certain atomics
466   for (unsigned i = 0, e = 4; i != e; ++i) {
467     MVT VT = IntVTs[i];
468     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
469     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
470     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
471   }
472
473   if (!Subtarget->is64Bit()) {
474     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
475     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
476     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
477     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
478     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
479     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
480     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
481     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
482   }
483
484   if (Subtarget->hasCmpxchg16b()) {
485     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
486   }
487
488   // FIXME - use subtarget debug flags
489   if (!Subtarget->isTargetDarwin() &&
490       !Subtarget->isTargetELF() &&
491       !Subtarget->isTargetCygMing()) {
492     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
493   }
494
495   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
496   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
497   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
498   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
499   if (Subtarget->is64Bit()) {
500     setExceptionPointerRegister(X86::RAX);
501     setExceptionSelectorRegister(X86::RDX);
502   } else {
503     setExceptionPointerRegister(X86::EAX);
504     setExceptionSelectorRegister(X86::EDX);
505   }
506   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
507   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
508
509   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
510   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
511
512   setOperationAction(ISD::TRAP, MVT::Other, Legal);
513
514   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
515   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
516   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
517   if (Subtarget->is64Bit()) {
518     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
519     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
520   } else {
521     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
522     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
523   }
524
525   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
526   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
527
528   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
529     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
530                        MVT::i64 : MVT::i32, Custom);
531   else if (EnableSegmentedStacks)
532     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
533                        MVT::i64 : MVT::i32, Custom);
534   else
535     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
536                        MVT::i64 : MVT::i32, Expand);
537
538   if (!UseSoftFloat && X86ScalarSSEf64) {
539     // f32 and f64 use SSE.
540     // Set up the FP register classes.
541     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
542     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
543
544     // Use ANDPD to simulate FABS.
545     setOperationAction(ISD::FABS , MVT::f64, Custom);
546     setOperationAction(ISD::FABS , MVT::f32, Custom);
547
548     // Use XORP to simulate FNEG.
549     setOperationAction(ISD::FNEG , MVT::f64, Custom);
550     setOperationAction(ISD::FNEG , MVT::f32, Custom);
551
552     // Use ANDPD and ORPD to simulate FCOPYSIGN.
553     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
554     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
555
556     // Lower this to FGETSIGNx86 plus an AND.
557     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
558     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
559
560     // We don't support sin/cos/fmod
561     setOperationAction(ISD::FSIN , MVT::f64, Expand);
562     setOperationAction(ISD::FCOS , MVT::f64, Expand);
563     setOperationAction(ISD::FSIN , MVT::f32, Expand);
564     setOperationAction(ISD::FCOS , MVT::f32, Expand);
565
566     // Expand FP immediates into loads from the stack, except for the special
567     // cases we handle.
568     addLegalFPImmediate(APFloat(+0.0)); // xorpd
569     addLegalFPImmediate(APFloat(+0.0f)); // xorps
570   } else if (!UseSoftFloat && X86ScalarSSEf32) {
571     // Use SSE for f32, x87 for f64.
572     // Set up the FP register classes.
573     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
574     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
575
576     // Use ANDPS to simulate FABS.
577     setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579     // Use XORP to simulate FNEG.
580     setOperationAction(ISD::FNEG , MVT::f32, Custom);
581
582     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
583
584     // Use ANDPS and ORPS to simulate FCOPYSIGN.
585     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
586     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
587
588     // We don't support sin/cos/fmod
589     setOperationAction(ISD::FSIN , MVT::f32, Expand);
590     setOperationAction(ISD::FCOS , MVT::f32, Expand);
591
592     // Special cases we handle for FP constants.
593     addLegalFPImmediate(APFloat(+0.0f)); // xorps
594     addLegalFPImmediate(APFloat(+0.0)); // FLD0
595     addLegalFPImmediate(APFloat(+1.0)); // FLD1
596     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
597     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
598
599     if (!UnsafeFPMath) {
600       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
601       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
602     }
603   } else if (!UseSoftFloat) {
604     // f32 and f64 in x87.
605     // Set up the FP register classes.
606     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
607     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
608
609     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
610     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
611     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
612     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
613
614     if (!UnsafeFPMath) {
615       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
616       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
617     }
618     addLegalFPImmediate(APFloat(+0.0)); // FLD0
619     addLegalFPImmediate(APFloat(+1.0)); // FLD1
620     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
621     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
622     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
623     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
624     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
625     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
626   }
627
628   // We don't support FMA.
629   setOperationAction(ISD::FMA, MVT::f64, Expand);
630   setOperationAction(ISD::FMA, MVT::f32, Expand);
631
632   // Long double always uses X87.
633   if (!UseSoftFloat) {
634     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
635     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
636     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
637     {
638       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
639       addLegalFPImmediate(TmpFlt);  // FLD0
640       TmpFlt.changeSign();
641       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
642
643       bool ignored;
644       APFloat TmpFlt2(+1.0);
645       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
646                       &ignored);
647       addLegalFPImmediate(TmpFlt2);  // FLD1
648       TmpFlt2.changeSign();
649       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
650     }
651
652     if (!UnsafeFPMath) {
653       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
654       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
655     }
656
657     setOperationAction(ISD::FMA, MVT::f80, Expand);
658   }
659
660   // Always use a library call for pow.
661   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
662   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
663   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
664
665   setOperationAction(ISD::FLOG, MVT::f80, Expand);
666   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
667   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
668   setOperationAction(ISD::FEXP, MVT::f80, Expand);
669   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
670
671   // First set operation action for all vector types to either promote
672   // (for widening) or expand (for scalarization). Then we will selectively
673   // turn on ones that can be effectively codegen'd.
674   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
675        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
676     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
677     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
678     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
679     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
680     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
681     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
691     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
693     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
694     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
726     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
731     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
732          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
733       setTruncStoreAction((MVT::SimpleValueType)VT,
734                           (MVT::SimpleValueType)InnerVT, Expand);
735     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
736     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
737     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
738   }
739
740   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
741   // with -msoft-float, disable use of MMX as well.
742   if (!UseSoftFloat && Subtarget->hasMMX()) {
743     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
744     // No operations on x86mmx supported, everything uses intrinsics.
745   }
746
747   // MMX-sized vectors (other than x86mmx) are expected to be expanded
748   // into smaller operations.
749   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
750   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
751   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
752   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
753   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
754   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
755   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
756   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
757   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
758   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
759   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
760   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
761   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
762   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
763   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
764   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
765   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
766   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
767   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
768   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
771   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
772   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
773   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
774   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
775   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
776   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
777   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
778
779   if (!UseSoftFloat && Subtarget->hasXMM()) {
780     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
781
782     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
787     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
788     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
789     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
790     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
793     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
794   }
795
796   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
797     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
798
799     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
800     // registers cannot be used even for integer operations.
801     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
802     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
803     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
804     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
805
806     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
807     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
808     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
809     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822
823     setOperationAction(ISD::SETCC,              MVT::v2f64, Custom);
824     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
827
828     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
829     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
830     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
831     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
833
834     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
835     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
836     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
837     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
838     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
839
840     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
841     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
842       EVT VT = (MVT::SimpleValueType)i;
843       // Do not attempt to custom lower non-power-of-2 vectors
844       if (!isPowerOf2_32(VT.getVectorNumElements()))
845         continue;
846       // Do not attempt to custom lower non-128-bit vectors
847       if (!VT.is128BitVector())
848         continue;
849       setOperationAction(ISD::BUILD_VECTOR,
850                          VT.getSimpleVT().SimpleTy, Custom);
851       setOperationAction(ISD::VECTOR_SHUFFLE,
852                          VT.getSimpleVT().SimpleTy, Custom);
853       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
854                          VT.getSimpleVT().SimpleTy, Custom);
855     }
856
857     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
858     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
859     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
860     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
862     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
863
864     if (Subtarget->is64Bit()) {
865       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
866       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
867     }
868
869     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
870     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
871       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
872       EVT VT = SVT;
873
874       // Do not attempt to promote non-128-bit vectors
875       if (!VT.is128BitVector())
876         continue;
877
878       setOperationAction(ISD::AND,    SVT, Promote);
879       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
880       setOperationAction(ISD::OR,     SVT, Promote);
881       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
882       setOperationAction(ISD::XOR,    SVT, Promote);
883       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
884       setOperationAction(ISD::LOAD,   SVT, Promote);
885       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
886       setOperationAction(ISD::SELECT, SVT, Promote);
887       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
888     }
889
890     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
891
892     // Custom lower v2i64 and v2f64 selects.
893     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
894     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
895     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
896     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
897
898     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
899     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
900   }
901
902   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
903     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
904     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
905     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
906     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
907     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
908     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
909     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
910     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
911     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
912     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
913
914     // FIXME: Do we need to handle scalar-to-vector here?
915     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
916
917     // Can turn SHL into an integer multiply.
918     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
919     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
920
921     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
922     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
923     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
924     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
925     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
926
927     // i8 and i16 vectors are custom , because the source register and source
928     // source memory operand types are not the same width.  f32 vectors are
929     // custom since the immediate controlling the insert encodes additional
930     // information.
931     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
932     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
933     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
934     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
935
936     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
938     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
939     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
940
941     if (Subtarget->is64Bit()) {
942       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
944     }
945   }
946
947   if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
948     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
949     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
950     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
951     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
952
953     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
954     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
955     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
956
957     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
959   }
960
961   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
962     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
963
964   if (!UseSoftFloat && Subtarget->hasAVX()) {
965     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
966     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
967     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
968     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
969     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
970     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
971
972     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
973     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
974     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
975
976     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
977     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
978     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
979     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
980     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
981     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
982
983     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
989
990     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
991     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
992     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
993
994     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
995     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
996     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
997     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
998     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
999     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1000
1001     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1002     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1003     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1004     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1005
1006     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1007     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1008     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1009     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1010
1011     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1012     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1013
1014     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1015     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1016     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1017     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1018
1019     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1020     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1021     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1022
1023     setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1024     setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1025     setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1026     setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1027
1028     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1029     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1030     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1031     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1032
1033     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1034     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1035     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1036     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1037
1038     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1039     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1040     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1041     // Don't lower v32i8 because there is no 128-bit byte mul
1042
1043     // Custom lower several nodes for 256-bit types.
1044     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1045                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1046       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1047       EVT VT = SVT;
1048
1049       // Extract subvector is special because the value type
1050       // (result) is 128-bit but the source is 256-bit wide.
1051       if (VT.is128BitVector())
1052         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1053
1054       // Do not attempt to custom lower other non-256-bit vectors
1055       if (!VT.is256BitVector())
1056         continue;
1057
1058       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1059       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1060       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1061       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1062       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1063       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1064     }
1065
1066     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1067     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1068       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1069       EVT VT = SVT;
1070
1071       // Do not attempt to promote non-256-bit vectors
1072       if (!VT.is256BitVector())
1073         continue;
1074
1075       setOperationAction(ISD::AND,    SVT, Promote);
1076       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1077       setOperationAction(ISD::OR,     SVT, Promote);
1078       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1079       setOperationAction(ISD::XOR,    SVT, Promote);
1080       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1081       setOperationAction(ISD::LOAD,   SVT, Promote);
1082       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1083       setOperationAction(ISD::SELECT, SVT, Promote);
1084       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1085     }
1086   }
1087
1088   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1089   // of this type with custom code.
1090   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1091          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1092     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1093   }
1094
1095   // We want to custom lower some of our intrinsics.
1096   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1097
1098
1099   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1100   // handle type legalization for these operations here.
1101   //
1102   // FIXME: We really should do custom legalization for addition and
1103   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1104   // than generic legalization for 64-bit multiplication-with-overflow, though.
1105   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1106     // Add/Sub/Mul with overflow operations are custom lowered.
1107     MVT VT = IntVTs[i];
1108     setOperationAction(ISD::SADDO, VT, Custom);
1109     setOperationAction(ISD::UADDO, VT, Custom);
1110     setOperationAction(ISD::SSUBO, VT, Custom);
1111     setOperationAction(ISD::USUBO, VT, Custom);
1112     setOperationAction(ISD::SMULO, VT, Custom);
1113     setOperationAction(ISD::UMULO, VT, Custom);
1114   }
1115
1116   // There are no 8-bit 3-address imul/mul instructions
1117   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1118   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1119
1120   if (!Subtarget->is64Bit()) {
1121     // These libcalls are not available in 32-bit.
1122     setLibcallName(RTLIB::SHL_I128, 0);
1123     setLibcallName(RTLIB::SRL_I128, 0);
1124     setLibcallName(RTLIB::SRA_I128, 0);
1125   }
1126
1127   // We have target-specific dag combine patterns for the following nodes:
1128   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1129   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1130   setTargetDAGCombine(ISD::BUILD_VECTOR);
1131   setTargetDAGCombine(ISD::SELECT);
1132   setTargetDAGCombine(ISD::SHL);
1133   setTargetDAGCombine(ISD::SRA);
1134   setTargetDAGCombine(ISD::SRL);
1135   setTargetDAGCombine(ISD::OR);
1136   setTargetDAGCombine(ISD::AND);
1137   setTargetDAGCombine(ISD::ADD);
1138   setTargetDAGCombine(ISD::SUB);
1139   setTargetDAGCombine(ISD::STORE);
1140   setTargetDAGCombine(ISD::ZERO_EXTEND);
1141   setTargetDAGCombine(ISD::SINT_TO_FP);
1142   if (Subtarget->is64Bit())
1143     setTargetDAGCombine(ISD::MUL);
1144
1145   computeRegisterProperties();
1146
1147   // On Darwin, -Os means optimize for size without hurting performance,
1148   // do not reduce the limit.
1149   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1150   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1151   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1152   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1153   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1154   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1155   setPrefLoopAlignment(16);
1156   benefitFromCodePlacementOpt = true;
1157
1158   setPrefFunctionAlignment(4);
1159 }
1160
1161
1162 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1163   if (!VT.isVector()) return MVT::i8;
1164   return VT.changeVectorElementTypeToInteger();
1165 }
1166
1167
1168 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1169 /// the desired ByVal argument alignment.
1170 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1171   if (MaxAlign == 16)
1172     return;
1173   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1174     if (VTy->getBitWidth() == 128)
1175       MaxAlign = 16;
1176   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1177     unsigned EltAlign = 0;
1178     getMaxByValAlign(ATy->getElementType(), EltAlign);
1179     if (EltAlign > MaxAlign)
1180       MaxAlign = EltAlign;
1181   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1182     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1183       unsigned EltAlign = 0;
1184       getMaxByValAlign(STy->getElementType(i), EltAlign);
1185       if (EltAlign > MaxAlign)
1186         MaxAlign = EltAlign;
1187       if (MaxAlign == 16)
1188         break;
1189     }
1190   }
1191   return;
1192 }
1193
1194 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1195 /// function arguments in the caller parameter area. For X86, aggregates
1196 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1197 /// are at 4-byte boundaries.
1198 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1199   if (Subtarget->is64Bit()) {
1200     // Max of 8 and alignment of type.
1201     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1202     if (TyAlign > 8)
1203       return TyAlign;
1204     return 8;
1205   }
1206
1207   unsigned Align = 4;
1208   if (Subtarget->hasXMM())
1209     getMaxByValAlign(Ty, Align);
1210   return Align;
1211 }
1212
1213 /// getOptimalMemOpType - Returns the target specific optimal type for load
1214 /// and store operations as a result of memset, memcpy, and memmove
1215 /// lowering. If DstAlign is zero that means it's safe to destination
1216 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1217 /// means there isn't a need to check it against alignment requirement,
1218 /// probably because the source does not need to be loaded. If
1219 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1220 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1221 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1222 /// constant so it does not need to be loaded.
1223 /// It returns EVT::Other if the type should be determined using generic
1224 /// target-independent logic.
1225 EVT
1226 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1227                                        unsigned DstAlign, unsigned SrcAlign,
1228                                        bool NonScalarIntSafe,
1229                                        bool MemcpyStrSrc,
1230                                        MachineFunction &MF) const {
1231   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1232   // linux.  This is because the stack realignment code can't handle certain
1233   // cases like PR2962.  This should be removed when PR2962 is fixed.
1234   const Function *F = MF.getFunction();
1235   if (NonScalarIntSafe &&
1236       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1237     if (Size >= 16 &&
1238         (Subtarget->isUnalignedMemAccessFast() ||
1239          ((DstAlign == 0 || DstAlign >= 16) &&
1240           (SrcAlign == 0 || SrcAlign >= 16))) &&
1241         Subtarget->getStackAlignment() >= 16) {
1242       if (Subtarget->hasSSE2())
1243         return MVT::v4i32;
1244       if (Subtarget->hasSSE1())
1245         return MVT::v4f32;
1246     } else if (!MemcpyStrSrc && Size >= 8 &&
1247                !Subtarget->is64Bit() &&
1248                Subtarget->getStackAlignment() >= 8 &&
1249                Subtarget->hasXMMInt()) {
1250       // Do not use f64 to lower memcpy if source is string constant. It's
1251       // better to use i32 to avoid the loads.
1252       return MVT::f64;
1253     }
1254   }
1255   if (Subtarget->is64Bit() && Size >= 8)
1256     return MVT::i64;
1257   return MVT::i32;
1258 }
1259
1260 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1261 /// current function.  The returned value is a member of the
1262 /// MachineJumpTableInfo::JTEntryKind enum.
1263 unsigned X86TargetLowering::getJumpTableEncoding() const {
1264   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1265   // symbol.
1266   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1267       Subtarget->isPICStyleGOT())
1268     return MachineJumpTableInfo::EK_Custom32;
1269
1270   // Otherwise, use the normal jump table encoding heuristics.
1271   return TargetLowering::getJumpTableEncoding();
1272 }
1273
1274 const MCExpr *
1275 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1276                                              const MachineBasicBlock *MBB,
1277                                              unsigned uid,MCContext &Ctx) const{
1278   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1279          Subtarget->isPICStyleGOT());
1280   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1281   // entries.
1282   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1283                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1284 }
1285
1286 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1287 /// jumptable.
1288 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1289                                                     SelectionDAG &DAG) const {
1290   if (!Subtarget->is64Bit())
1291     // This doesn't have DebugLoc associated with it, but is not really the
1292     // same as a Register.
1293     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1294   return Table;
1295 }
1296
1297 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1298 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1299 /// MCExpr.
1300 const MCExpr *X86TargetLowering::
1301 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1302                              MCContext &Ctx) const {
1303   // X86-64 uses RIP relative addressing based on the jump table label.
1304   if (Subtarget->isPICStyleRIPRel())
1305     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1306
1307   // Otherwise, the reference is relative to the PIC base.
1308   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1309 }
1310
1311 // FIXME: Why this routine is here? Move to RegInfo!
1312 std::pair<const TargetRegisterClass*, uint8_t>
1313 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1314   const TargetRegisterClass *RRC = 0;
1315   uint8_t Cost = 1;
1316   switch (VT.getSimpleVT().SimpleTy) {
1317   default:
1318     return TargetLowering::findRepresentativeClass(VT);
1319   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1320     RRC = (Subtarget->is64Bit()
1321            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1322     break;
1323   case MVT::x86mmx:
1324     RRC = X86::VR64RegisterClass;
1325     break;
1326   case MVT::f32: case MVT::f64:
1327   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1328   case MVT::v4f32: case MVT::v2f64:
1329   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1330   case MVT::v4f64:
1331     RRC = X86::VR128RegisterClass;
1332     break;
1333   }
1334   return std::make_pair(RRC, Cost);
1335 }
1336
1337 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1338                                                unsigned &Offset) const {
1339   if (!Subtarget->isTargetLinux())
1340     return false;
1341
1342   if (Subtarget->is64Bit()) {
1343     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1344     Offset = 0x28;
1345     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1346       AddressSpace = 256;
1347     else
1348       AddressSpace = 257;
1349   } else {
1350     // %gs:0x14 on i386
1351     Offset = 0x14;
1352     AddressSpace = 256;
1353   }
1354   return true;
1355 }
1356
1357
1358 //===----------------------------------------------------------------------===//
1359 //               Return Value Calling Convention Implementation
1360 //===----------------------------------------------------------------------===//
1361
1362 #include "X86GenCallingConv.inc"
1363
1364 bool
1365 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1366                                   MachineFunction &MF, bool isVarArg,
1367                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1368                         LLVMContext &Context) const {
1369   SmallVector<CCValAssign, 16> RVLocs;
1370   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1371                  RVLocs, Context);
1372   return CCInfo.CheckReturn(Outs, RetCC_X86);
1373 }
1374
1375 SDValue
1376 X86TargetLowering::LowerReturn(SDValue Chain,
1377                                CallingConv::ID CallConv, bool isVarArg,
1378                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1379                                const SmallVectorImpl<SDValue> &OutVals,
1380                                DebugLoc dl, SelectionDAG &DAG) const {
1381   MachineFunction &MF = DAG.getMachineFunction();
1382   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1383
1384   SmallVector<CCValAssign, 16> RVLocs;
1385   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1386                  RVLocs, *DAG.getContext());
1387   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1388
1389   // Add the regs to the liveout set for the function.
1390   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1391   for (unsigned i = 0; i != RVLocs.size(); ++i)
1392     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1393       MRI.addLiveOut(RVLocs[i].getLocReg());
1394
1395   SDValue Flag;
1396
1397   SmallVector<SDValue, 6> RetOps;
1398   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1399   // Operand #1 = Bytes To Pop
1400   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1401                    MVT::i16));
1402
1403   // Copy the result values into the output registers.
1404   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1405     CCValAssign &VA = RVLocs[i];
1406     assert(VA.isRegLoc() && "Can only return in registers!");
1407     SDValue ValToCopy = OutVals[i];
1408     EVT ValVT = ValToCopy.getValueType();
1409
1410     // If this is x86-64, and we disabled SSE, we can't return FP values,
1411     // or SSE or MMX vectors.
1412     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1413          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1414           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1415       report_fatal_error("SSE register return with SSE disabled");
1416     }
1417     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1418     // llvm-gcc has never done it right and no one has noticed, so this
1419     // should be OK for now.
1420     if (ValVT == MVT::f64 &&
1421         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1422       report_fatal_error("SSE2 register return with SSE2 disabled");
1423
1424     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1425     // the RET instruction and handled by the FP Stackifier.
1426     if (VA.getLocReg() == X86::ST0 ||
1427         VA.getLocReg() == X86::ST1) {
1428       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1429       // change the value to the FP stack register class.
1430       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1431         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1432       RetOps.push_back(ValToCopy);
1433       // Don't emit a copytoreg.
1434       continue;
1435     }
1436
1437     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1438     // which is returned in RAX / RDX.
1439     if (Subtarget->is64Bit()) {
1440       if (ValVT == MVT::x86mmx) {
1441         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1442           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1443           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1444                                   ValToCopy);
1445           // If we don't have SSE2 available, convert to v4f32 so the generated
1446           // register is legal.
1447           if (!Subtarget->hasSSE2())
1448             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1449         }
1450       }
1451     }
1452
1453     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1454     Flag = Chain.getValue(1);
1455   }
1456
1457   // The x86-64 ABI for returning structs by value requires that we copy
1458   // the sret argument into %rax for the return. We saved the argument into
1459   // a virtual register in the entry block, so now we copy the value out
1460   // and into %rax.
1461   if (Subtarget->is64Bit() &&
1462       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1463     MachineFunction &MF = DAG.getMachineFunction();
1464     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1465     unsigned Reg = FuncInfo->getSRetReturnReg();
1466     assert(Reg &&
1467            "SRetReturnReg should have been set in LowerFormalArguments().");
1468     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1469
1470     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1471     Flag = Chain.getValue(1);
1472
1473     // RAX now acts like a return value.
1474     MRI.addLiveOut(X86::RAX);
1475   }
1476
1477   RetOps[0] = Chain;  // Update chain.
1478
1479   // Add the flag if we have it.
1480   if (Flag.getNode())
1481     RetOps.push_back(Flag);
1482
1483   return DAG.getNode(X86ISD::RET_FLAG, dl,
1484                      MVT::Other, &RetOps[0], RetOps.size());
1485 }
1486
1487 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1488   if (N->getNumValues() != 1)
1489     return false;
1490   if (!N->hasNUsesOfValue(1, 0))
1491     return false;
1492
1493   SDNode *Copy = *N->use_begin();
1494   if (Copy->getOpcode() != ISD::CopyToReg &&
1495       Copy->getOpcode() != ISD::FP_EXTEND)
1496     return false;
1497
1498   bool HasRet = false;
1499   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1500        UI != UE; ++UI) {
1501     if (UI->getOpcode() != X86ISD::RET_FLAG)
1502       return false;
1503     HasRet = true;
1504   }
1505
1506   return HasRet;
1507 }
1508
1509 EVT
1510 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1511                                             ISD::NodeType ExtendKind) const {
1512   MVT ReturnMVT;
1513   // TODO: Is this also valid on 32-bit?
1514   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1515     ReturnMVT = MVT::i8;
1516   else
1517     ReturnMVT = MVT::i32;
1518
1519   EVT MinVT = getRegisterType(Context, ReturnMVT);
1520   return VT.bitsLT(MinVT) ? MinVT : VT;
1521 }
1522
1523 /// LowerCallResult - Lower the result values of a call into the
1524 /// appropriate copies out of appropriate physical registers.
1525 ///
1526 SDValue
1527 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1528                                    CallingConv::ID CallConv, bool isVarArg,
1529                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1530                                    DebugLoc dl, SelectionDAG &DAG,
1531                                    SmallVectorImpl<SDValue> &InVals) const {
1532
1533   // Assign locations to each value returned by this call.
1534   SmallVector<CCValAssign, 16> RVLocs;
1535   bool Is64Bit = Subtarget->is64Bit();
1536   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1537                  getTargetMachine(), RVLocs, *DAG.getContext());
1538   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1539
1540   // Copy all of the result registers out of their specified physreg.
1541   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1542     CCValAssign &VA = RVLocs[i];
1543     EVT CopyVT = VA.getValVT();
1544
1545     // If this is x86-64, and we disabled SSE, we can't return FP values
1546     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1547         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1548       report_fatal_error("SSE register return with SSE disabled");
1549     }
1550
1551     SDValue Val;
1552
1553     // If this is a call to a function that returns an fp value on the floating
1554     // point stack, we must guarantee the the value is popped from the stack, so
1555     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1556     // if the return value is not used. We use the FpPOP_RETVAL instruction
1557     // instead.
1558     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1559       // If we prefer to use the value in xmm registers, copy it out as f80 and
1560       // use a truncate to move it from fp stack reg to xmm reg.
1561       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1562       SDValue Ops[] = { Chain, InFlag };
1563       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1564                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1565       Val = Chain.getValue(0);
1566
1567       // Round the f80 to the right size, which also moves it to the appropriate
1568       // xmm register.
1569       if (CopyVT != VA.getValVT())
1570         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1571                           // This truncation won't change the value.
1572                           DAG.getIntPtrConstant(1));
1573     } else {
1574       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1575                                  CopyVT, InFlag).getValue(1);
1576       Val = Chain.getValue(0);
1577     }
1578     InFlag = Chain.getValue(2);
1579     InVals.push_back(Val);
1580   }
1581
1582   return Chain;
1583 }
1584
1585
1586 //===----------------------------------------------------------------------===//
1587 //                C & StdCall & Fast Calling Convention implementation
1588 //===----------------------------------------------------------------------===//
1589 //  StdCall calling convention seems to be standard for many Windows' API
1590 //  routines and around. It differs from C calling convention just a little:
1591 //  callee should clean up the stack, not caller. Symbols should be also
1592 //  decorated in some fancy way :) It doesn't support any vector arguments.
1593 //  For info on fast calling convention see Fast Calling Convention (tail call)
1594 //  implementation LowerX86_32FastCCCallTo.
1595
1596 /// CallIsStructReturn - Determines whether a call uses struct return
1597 /// semantics.
1598 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1599   if (Outs.empty())
1600     return false;
1601
1602   return Outs[0].Flags.isSRet();
1603 }
1604
1605 /// ArgsAreStructReturn - Determines whether a function uses struct
1606 /// return semantics.
1607 static bool
1608 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1609   if (Ins.empty())
1610     return false;
1611
1612   return Ins[0].Flags.isSRet();
1613 }
1614
1615 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1616 /// by "Src" to address "Dst" with size and alignment information specified by
1617 /// the specific parameter attribute. The copy will be passed as a byval
1618 /// function parameter.
1619 static SDValue
1620 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1621                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1622                           DebugLoc dl) {
1623   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1624
1625   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1626                        /*isVolatile*/false, /*AlwaysInline=*/true,
1627                        MachinePointerInfo(), MachinePointerInfo());
1628 }
1629
1630 /// IsTailCallConvention - Return true if the calling convention is one that
1631 /// supports tail call optimization.
1632 static bool IsTailCallConvention(CallingConv::ID CC) {
1633   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1634 }
1635
1636 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1637   if (!CI->isTailCall())
1638     return false;
1639
1640   CallSite CS(CI);
1641   CallingConv::ID CalleeCC = CS.getCallingConv();
1642   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1643     return false;
1644
1645   return true;
1646 }
1647
1648 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1649 /// a tailcall target by changing its ABI.
1650 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1651   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1652 }
1653
1654 SDValue
1655 X86TargetLowering::LowerMemArgument(SDValue Chain,
1656                                     CallingConv::ID CallConv,
1657                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1658                                     DebugLoc dl, SelectionDAG &DAG,
1659                                     const CCValAssign &VA,
1660                                     MachineFrameInfo *MFI,
1661                                     unsigned i) const {
1662   // Create the nodes corresponding to a load from this parameter slot.
1663   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1664   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1665   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1666   EVT ValVT;
1667
1668   // If value is passed by pointer we have address passed instead of the value
1669   // itself.
1670   if (VA.getLocInfo() == CCValAssign::Indirect)
1671     ValVT = VA.getLocVT();
1672   else
1673     ValVT = VA.getValVT();
1674
1675   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1676   // changed with more analysis.
1677   // In case of tail call optimization mark all arguments mutable. Since they
1678   // could be overwritten by lowering of arguments in case of a tail call.
1679   if (Flags.isByVal()) {
1680     unsigned Bytes = Flags.getByValSize();
1681     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1682     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1683     return DAG.getFrameIndex(FI, getPointerTy());
1684   } else {
1685     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1686                                     VA.getLocMemOffset(), isImmutable);
1687     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1688     return DAG.getLoad(ValVT, dl, Chain, FIN,
1689                        MachinePointerInfo::getFixedStack(FI),
1690                        false, false, 0);
1691   }
1692 }
1693
1694 SDValue
1695 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1696                                         CallingConv::ID CallConv,
1697                                         bool isVarArg,
1698                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1699                                         DebugLoc dl,
1700                                         SelectionDAG &DAG,
1701                                         SmallVectorImpl<SDValue> &InVals)
1702                                           const {
1703   MachineFunction &MF = DAG.getMachineFunction();
1704   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1705
1706   const Function* Fn = MF.getFunction();
1707   if (Fn->hasExternalLinkage() &&
1708       Subtarget->isTargetCygMing() &&
1709       Fn->getName() == "main")
1710     FuncInfo->setForceFramePointer(true);
1711
1712   MachineFrameInfo *MFI = MF.getFrameInfo();
1713   bool Is64Bit = Subtarget->is64Bit();
1714   bool IsWin64 = Subtarget->isTargetWin64();
1715
1716   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1717          "Var args not supported with calling convention fastcc or ghc");
1718
1719   // Assign locations to all of the incoming arguments.
1720   SmallVector<CCValAssign, 16> ArgLocs;
1721   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1722                  ArgLocs, *DAG.getContext());
1723
1724   // Allocate shadow area for Win64
1725   if (IsWin64) {
1726     CCInfo.AllocateStack(32, 8);
1727   }
1728
1729   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1730
1731   unsigned LastVal = ~0U;
1732   SDValue ArgValue;
1733   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1734     CCValAssign &VA = ArgLocs[i];
1735     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1736     // places.
1737     assert(VA.getValNo() != LastVal &&
1738            "Don't support value assigned to multiple locs yet");
1739     LastVal = VA.getValNo();
1740
1741     if (VA.isRegLoc()) {
1742       EVT RegVT = VA.getLocVT();
1743       TargetRegisterClass *RC = NULL;
1744       if (RegVT == MVT::i32)
1745         RC = X86::GR32RegisterClass;
1746       else if (Is64Bit && RegVT == MVT::i64)
1747         RC = X86::GR64RegisterClass;
1748       else if (RegVT == MVT::f32)
1749         RC = X86::FR32RegisterClass;
1750       else if (RegVT == MVT::f64)
1751         RC = X86::FR64RegisterClass;
1752       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1753         RC = X86::VR256RegisterClass;
1754       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1755         RC = X86::VR128RegisterClass;
1756       else if (RegVT == MVT::x86mmx)
1757         RC = X86::VR64RegisterClass;
1758       else
1759         llvm_unreachable("Unknown argument type!");
1760
1761       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1762       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1763
1764       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1765       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1766       // right size.
1767       if (VA.getLocInfo() == CCValAssign::SExt)
1768         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1769                                DAG.getValueType(VA.getValVT()));
1770       else if (VA.getLocInfo() == CCValAssign::ZExt)
1771         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1772                                DAG.getValueType(VA.getValVT()));
1773       else if (VA.getLocInfo() == CCValAssign::BCvt)
1774         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1775
1776       if (VA.isExtInLoc()) {
1777         // Handle MMX values passed in XMM regs.
1778         if (RegVT.isVector()) {
1779           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1780                                  ArgValue);
1781         } else
1782           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1783       }
1784     } else {
1785       assert(VA.isMemLoc());
1786       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1787     }
1788
1789     // If value is passed via pointer - do a load.
1790     if (VA.getLocInfo() == CCValAssign::Indirect)
1791       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1792                              MachinePointerInfo(), false, false, 0);
1793
1794     InVals.push_back(ArgValue);
1795   }
1796
1797   // The x86-64 ABI for returning structs by value requires that we copy
1798   // the sret argument into %rax for the return. Save the argument into
1799   // a virtual register so that we can access it from the return points.
1800   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1801     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1802     unsigned Reg = FuncInfo->getSRetReturnReg();
1803     if (!Reg) {
1804       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1805       FuncInfo->setSRetReturnReg(Reg);
1806     }
1807     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1808     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1809   }
1810
1811   unsigned StackSize = CCInfo.getNextStackOffset();
1812   // Align stack specially for tail calls.
1813   if (FuncIsMadeTailCallSafe(CallConv))
1814     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1815
1816   // If the function takes variable number of arguments, make a frame index for
1817   // the start of the first vararg value... for expansion of llvm.va_start.
1818   if (isVarArg) {
1819     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1820                     CallConv != CallingConv::X86_ThisCall)) {
1821       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1822     }
1823     if (Is64Bit) {
1824       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1825
1826       // FIXME: We should really autogenerate these arrays
1827       static const unsigned GPR64ArgRegsWin64[] = {
1828         X86::RCX, X86::RDX, X86::R8,  X86::R9
1829       };
1830       static const unsigned GPR64ArgRegs64Bit[] = {
1831         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1832       };
1833       static const unsigned XMMArgRegs64Bit[] = {
1834         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1835         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1836       };
1837       const unsigned *GPR64ArgRegs;
1838       unsigned NumXMMRegs = 0;
1839
1840       if (IsWin64) {
1841         // The XMM registers which might contain var arg parameters are shadowed
1842         // in their paired GPR.  So we only need to save the GPR to their home
1843         // slots.
1844         TotalNumIntRegs = 4;
1845         GPR64ArgRegs = GPR64ArgRegsWin64;
1846       } else {
1847         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1848         GPR64ArgRegs = GPR64ArgRegs64Bit;
1849
1850         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1851       }
1852       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1853                                                        TotalNumIntRegs);
1854
1855       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1856       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1857              "SSE register cannot be used when SSE is disabled!");
1858       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1859              "SSE register cannot be used when SSE is disabled!");
1860       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1861         // Kernel mode asks for SSE to be disabled, so don't push them
1862         // on the stack.
1863         TotalNumXMMRegs = 0;
1864
1865       if (IsWin64) {
1866         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1867         // Get to the caller-allocated home save location.  Add 8 to account
1868         // for the return address.
1869         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1870         FuncInfo->setRegSaveFrameIndex(
1871           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1872         // Fixup to set vararg frame on shadow area (4 x i64).
1873         if (NumIntRegs < 4)
1874           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1875       } else {
1876         // For X86-64, if there are vararg parameters that are passed via
1877         // registers, then we must store them to their spots on the stack so they
1878         // may be loaded by deferencing the result of va_next.
1879         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1880         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1881         FuncInfo->setRegSaveFrameIndex(
1882           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1883                                false));
1884       }
1885
1886       // Store the integer parameter registers.
1887       SmallVector<SDValue, 8> MemOps;
1888       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1889                                         getPointerTy());
1890       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1891       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1892         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1893                                   DAG.getIntPtrConstant(Offset));
1894         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1895                                      X86::GR64RegisterClass);
1896         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1897         SDValue Store =
1898           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1899                        MachinePointerInfo::getFixedStack(
1900                          FuncInfo->getRegSaveFrameIndex(), Offset),
1901                        false, false, 0);
1902         MemOps.push_back(Store);
1903         Offset += 8;
1904       }
1905
1906       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1907         // Now store the XMM (fp + vector) parameter registers.
1908         SmallVector<SDValue, 11> SaveXMMOps;
1909         SaveXMMOps.push_back(Chain);
1910
1911         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1912         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1913         SaveXMMOps.push_back(ALVal);
1914
1915         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1916                                FuncInfo->getRegSaveFrameIndex()));
1917         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1918                                FuncInfo->getVarArgsFPOffset()));
1919
1920         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1921           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1922                                        X86::VR128RegisterClass);
1923           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1924           SaveXMMOps.push_back(Val);
1925         }
1926         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1927                                      MVT::Other,
1928                                      &SaveXMMOps[0], SaveXMMOps.size()));
1929       }
1930
1931       if (!MemOps.empty())
1932         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1933                             &MemOps[0], MemOps.size());
1934     }
1935   }
1936
1937   // Some CCs need callee pop.
1938   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1939     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1940   } else {
1941     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1942     // If this is an sret function, the return should pop the hidden pointer.
1943     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1944       FuncInfo->setBytesToPopOnReturn(4);
1945   }
1946
1947   if (!Is64Bit) {
1948     // RegSaveFrameIndex is X86-64 only.
1949     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1950     if (CallConv == CallingConv::X86_FastCall ||
1951         CallConv == CallingConv::X86_ThisCall)
1952       // fastcc functions can't have varargs.
1953       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1954   }
1955
1956   FuncInfo->setArgumentStackSize(StackSize);
1957
1958   return Chain;
1959 }
1960
1961 SDValue
1962 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1963                                     SDValue StackPtr, SDValue Arg,
1964                                     DebugLoc dl, SelectionDAG &DAG,
1965                                     const CCValAssign &VA,
1966                                     ISD::ArgFlagsTy Flags) const {
1967   unsigned LocMemOffset = VA.getLocMemOffset();
1968   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1969   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1970   if (Flags.isByVal())
1971     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1972
1973   return DAG.getStore(Chain, dl, Arg, PtrOff,
1974                       MachinePointerInfo::getStack(LocMemOffset),
1975                       false, false, 0);
1976 }
1977
1978 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1979 /// optimization is performed and it is required.
1980 SDValue
1981 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1982                                            SDValue &OutRetAddr, SDValue Chain,
1983                                            bool IsTailCall, bool Is64Bit,
1984                                            int FPDiff, DebugLoc dl) const {
1985   // Adjust the Return address stack slot.
1986   EVT VT = getPointerTy();
1987   OutRetAddr = getReturnAddressFrameIndex(DAG);
1988
1989   // Load the "old" Return address.
1990   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1991                            false, false, 0);
1992   return SDValue(OutRetAddr.getNode(), 1);
1993 }
1994
1995 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1996 /// optimization is performed and it is required (FPDiff!=0).
1997 static SDValue
1998 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1999                          SDValue Chain, SDValue RetAddrFrIdx,
2000                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2001   // Store the return address to the appropriate stack slot.
2002   if (!FPDiff) return Chain;
2003   // Calculate the new stack slot for the return address.
2004   int SlotSize = Is64Bit ? 8 : 4;
2005   int NewReturnAddrFI =
2006     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2007   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2008   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2009   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2010                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2011                        false, false, 0);
2012   return Chain;
2013 }
2014
2015 SDValue
2016 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2017                              CallingConv::ID CallConv, bool isVarArg,
2018                              bool &isTailCall,
2019                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2020                              const SmallVectorImpl<SDValue> &OutVals,
2021                              const SmallVectorImpl<ISD::InputArg> &Ins,
2022                              DebugLoc dl, SelectionDAG &DAG,
2023                              SmallVectorImpl<SDValue> &InVals) const {
2024   MachineFunction &MF = DAG.getMachineFunction();
2025   bool Is64Bit        = Subtarget->is64Bit();
2026   bool IsWin64        = Subtarget->isTargetWin64();
2027   bool IsStructRet    = CallIsStructReturn(Outs);
2028   bool IsSibcall      = false;
2029
2030   if (isTailCall) {
2031     // Check if it's really possible to do a tail call.
2032     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2033                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2034                                                    Outs, OutVals, Ins, DAG);
2035
2036     // Sibcalls are automatically detected tailcalls which do not require
2037     // ABI changes.
2038     if (!GuaranteedTailCallOpt && isTailCall)
2039       IsSibcall = true;
2040
2041     if (isTailCall)
2042       ++NumTailCalls;
2043   }
2044
2045   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2046          "Var args not supported with calling convention fastcc or ghc");
2047
2048   // Analyze operands of the call, assigning locations to each operand.
2049   SmallVector<CCValAssign, 16> ArgLocs;
2050   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2051                  ArgLocs, *DAG.getContext());
2052
2053   // Allocate shadow area for Win64
2054   if (IsWin64) {
2055     CCInfo.AllocateStack(32, 8);
2056   }
2057
2058   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2059
2060   // Get a count of how many bytes are to be pushed on the stack.
2061   unsigned NumBytes = CCInfo.getNextStackOffset();
2062   if (IsSibcall)
2063     // This is a sibcall. The memory operands are available in caller's
2064     // own caller's stack.
2065     NumBytes = 0;
2066   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2067     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2068
2069   int FPDiff = 0;
2070   if (isTailCall && !IsSibcall) {
2071     // Lower arguments at fp - stackoffset + fpdiff.
2072     unsigned NumBytesCallerPushed =
2073       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2074     FPDiff = NumBytesCallerPushed - NumBytes;
2075
2076     // Set the delta of movement of the returnaddr stackslot.
2077     // But only set if delta is greater than previous delta.
2078     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2079       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2080   }
2081
2082   if (!IsSibcall)
2083     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2084
2085   SDValue RetAddrFrIdx;
2086   // Load return address for tail calls.
2087   if (isTailCall && FPDiff)
2088     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2089                                     Is64Bit, FPDiff, dl);
2090
2091   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2092   SmallVector<SDValue, 8> MemOpChains;
2093   SDValue StackPtr;
2094
2095   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2096   // of tail call optimization arguments are handle later.
2097   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2098     CCValAssign &VA = ArgLocs[i];
2099     EVT RegVT = VA.getLocVT();
2100     SDValue Arg = OutVals[i];
2101     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2102     bool isByVal = Flags.isByVal();
2103
2104     // Promote the value if needed.
2105     switch (VA.getLocInfo()) {
2106     default: llvm_unreachable("Unknown loc info!");
2107     case CCValAssign::Full: break;
2108     case CCValAssign::SExt:
2109       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2110       break;
2111     case CCValAssign::ZExt:
2112       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2113       break;
2114     case CCValAssign::AExt:
2115       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2116         // Special case: passing MMX values in XMM registers.
2117         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2118         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2119         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2120       } else
2121         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2122       break;
2123     case CCValAssign::BCvt:
2124       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2125       break;
2126     case CCValAssign::Indirect: {
2127       // Store the argument.
2128       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2129       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2130       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2131                            MachinePointerInfo::getFixedStack(FI),
2132                            false, false, 0);
2133       Arg = SpillSlot;
2134       break;
2135     }
2136     }
2137
2138     if (VA.isRegLoc()) {
2139       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2140       if (isVarArg && IsWin64) {
2141         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2142         // shadow reg if callee is a varargs function.
2143         unsigned ShadowReg = 0;
2144         switch (VA.getLocReg()) {
2145         case X86::XMM0: ShadowReg = X86::RCX; break;
2146         case X86::XMM1: ShadowReg = X86::RDX; break;
2147         case X86::XMM2: ShadowReg = X86::R8; break;
2148         case X86::XMM3: ShadowReg = X86::R9; break;
2149         }
2150         if (ShadowReg)
2151           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2152       }
2153     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2154       assert(VA.isMemLoc());
2155       if (StackPtr.getNode() == 0)
2156         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2157       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2158                                              dl, DAG, VA, Flags));
2159     }
2160   }
2161
2162   if (!MemOpChains.empty())
2163     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2164                         &MemOpChains[0], MemOpChains.size());
2165
2166   // Build a sequence of copy-to-reg nodes chained together with token chain
2167   // and flag operands which copy the outgoing args into registers.
2168   SDValue InFlag;
2169   // Tail call byval lowering might overwrite argument registers so in case of
2170   // tail call optimization the copies to registers are lowered later.
2171   if (!isTailCall)
2172     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2173       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2174                                RegsToPass[i].second, InFlag);
2175       InFlag = Chain.getValue(1);
2176     }
2177
2178   if (Subtarget->isPICStyleGOT()) {
2179     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2180     // GOT pointer.
2181     if (!isTailCall) {
2182       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2183                                DAG.getNode(X86ISD::GlobalBaseReg,
2184                                            DebugLoc(), getPointerTy()),
2185                                InFlag);
2186       InFlag = Chain.getValue(1);
2187     } else {
2188       // If we are tail calling and generating PIC/GOT style code load the
2189       // address of the callee into ECX. The value in ecx is used as target of
2190       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2191       // for tail calls on PIC/GOT architectures. Normally we would just put the
2192       // address of GOT into ebx and then call target@PLT. But for tail calls
2193       // ebx would be restored (since ebx is callee saved) before jumping to the
2194       // target@PLT.
2195
2196       // Note: The actual moving to ECX is done further down.
2197       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2198       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2199           !G->getGlobal()->hasProtectedVisibility())
2200         Callee = LowerGlobalAddress(Callee, DAG);
2201       else if (isa<ExternalSymbolSDNode>(Callee))
2202         Callee = LowerExternalSymbol(Callee, DAG);
2203     }
2204   }
2205
2206   if (Is64Bit && isVarArg && !IsWin64) {
2207     // From AMD64 ABI document:
2208     // For calls that may call functions that use varargs or stdargs
2209     // (prototype-less calls or calls to functions containing ellipsis (...) in
2210     // the declaration) %al is used as hidden argument to specify the number
2211     // of SSE registers used. The contents of %al do not need to match exactly
2212     // the number of registers, but must be an ubound on the number of SSE
2213     // registers used and is in the range 0 - 8 inclusive.
2214
2215     // Count the number of XMM registers allocated.
2216     static const unsigned XMMArgRegs[] = {
2217       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2218       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2219     };
2220     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2221     assert((Subtarget->hasXMM() || !NumXMMRegs)
2222            && "SSE registers cannot be used when SSE is disabled");
2223
2224     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2225                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2226     InFlag = Chain.getValue(1);
2227   }
2228
2229
2230   // For tail calls lower the arguments to the 'real' stack slot.
2231   if (isTailCall) {
2232     // Force all the incoming stack arguments to be loaded from the stack
2233     // before any new outgoing arguments are stored to the stack, because the
2234     // outgoing stack slots may alias the incoming argument stack slots, and
2235     // the alias isn't otherwise explicit. This is slightly more conservative
2236     // than necessary, because it means that each store effectively depends
2237     // on every argument instead of just those arguments it would clobber.
2238     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2239
2240     SmallVector<SDValue, 8> MemOpChains2;
2241     SDValue FIN;
2242     int FI = 0;
2243     // Do not flag preceding copytoreg stuff together with the following stuff.
2244     InFlag = SDValue();
2245     if (GuaranteedTailCallOpt) {
2246       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2247         CCValAssign &VA = ArgLocs[i];
2248         if (VA.isRegLoc())
2249           continue;
2250         assert(VA.isMemLoc());
2251         SDValue Arg = OutVals[i];
2252         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2253         // Create frame index.
2254         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2255         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2256         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2257         FIN = DAG.getFrameIndex(FI, getPointerTy());
2258
2259         if (Flags.isByVal()) {
2260           // Copy relative to framepointer.
2261           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2262           if (StackPtr.getNode() == 0)
2263             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2264                                           getPointerTy());
2265           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2266
2267           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2268                                                            ArgChain,
2269                                                            Flags, DAG, dl));
2270         } else {
2271           // Store relative to framepointer.
2272           MemOpChains2.push_back(
2273             DAG.getStore(ArgChain, dl, Arg, FIN,
2274                          MachinePointerInfo::getFixedStack(FI),
2275                          false, false, 0));
2276         }
2277       }
2278     }
2279
2280     if (!MemOpChains2.empty())
2281       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2282                           &MemOpChains2[0], MemOpChains2.size());
2283
2284     // Copy arguments to their registers.
2285     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2286       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2287                                RegsToPass[i].second, InFlag);
2288       InFlag = Chain.getValue(1);
2289     }
2290     InFlag =SDValue();
2291
2292     // Store the return address to the appropriate stack slot.
2293     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2294                                      FPDiff, dl);
2295   }
2296
2297   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2298     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2299     // In the 64-bit large code model, we have to make all calls
2300     // through a register, since the call instruction's 32-bit
2301     // pc-relative offset may not be large enough to hold the whole
2302     // address.
2303   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2304     // If the callee is a GlobalAddress node (quite common, every direct call
2305     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2306     // it.
2307
2308     // We should use extra load for direct calls to dllimported functions in
2309     // non-JIT mode.
2310     const GlobalValue *GV = G->getGlobal();
2311     if (!GV->hasDLLImportLinkage()) {
2312       unsigned char OpFlags = 0;
2313       bool ExtraLoad = false;
2314       unsigned WrapperKind = ISD::DELETED_NODE;
2315
2316       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2317       // external symbols most go through the PLT in PIC mode.  If the symbol
2318       // has hidden or protected visibility, or if it is static or local, then
2319       // we don't need to use the PLT - we can directly call it.
2320       if (Subtarget->isTargetELF() &&
2321           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2322           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2323         OpFlags = X86II::MO_PLT;
2324       } else if (Subtarget->isPICStyleStubAny() &&
2325                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2326                  (!Subtarget->getTargetTriple().isMacOSX() ||
2327                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2328         // PC-relative references to external symbols should go through $stub,
2329         // unless we're building with the leopard linker or later, which
2330         // automatically synthesizes these stubs.
2331         OpFlags = X86II::MO_DARWIN_STUB;
2332       } else if (Subtarget->isPICStyleRIPRel() &&
2333                  isa<Function>(GV) &&
2334                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2335         // If the function is marked as non-lazy, generate an indirect call
2336         // which loads from the GOT directly. This avoids runtime overhead
2337         // at the cost of eager binding (and one extra byte of encoding).
2338         OpFlags = X86II::MO_GOTPCREL;
2339         WrapperKind = X86ISD::WrapperRIP;
2340         ExtraLoad = true;
2341       }
2342
2343       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2344                                           G->getOffset(), OpFlags);
2345
2346       // Add a wrapper if needed.
2347       if (WrapperKind != ISD::DELETED_NODE)
2348         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2349       // Add extra indirection if needed.
2350       if (ExtraLoad)
2351         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2352                              MachinePointerInfo::getGOT(),
2353                              false, false, 0);
2354     }
2355   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2356     unsigned char OpFlags = 0;
2357
2358     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2359     // external symbols should go through the PLT.
2360     if (Subtarget->isTargetELF() &&
2361         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2362       OpFlags = X86II::MO_PLT;
2363     } else if (Subtarget->isPICStyleStubAny() &&
2364                (!Subtarget->getTargetTriple().isMacOSX() ||
2365                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2366       // PC-relative references to external symbols should go through $stub,
2367       // unless we're building with the leopard linker or later, which
2368       // automatically synthesizes these stubs.
2369       OpFlags = X86II::MO_DARWIN_STUB;
2370     }
2371
2372     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2373                                          OpFlags);
2374   }
2375
2376   // Returns a chain & a flag for retval copy to use.
2377   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2378   SmallVector<SDValue, 8> Ops;
2379
2380   if (!IsSibcall && isTailCall) {
2381     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2382                            DAG.getIntPtrConstant(0, true), InFlag);
2383     InFlag = Chain.getValue(1);
2384   }
2385
2386   Ops.push_back(Chain);
2387   Ops.push_back(Callee);
2388
2389   if (isTailCall)
2390     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2391
2392   // Add argument registers to the end of the list so that they are known live
2393   // into the call.
2394   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2395     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2396                                   RegsToPass[i].second.getValueType()));
2397
2398   // Add an implicit use GOT pointer in EBX.
2399   if (!isTailCall && Subtarget->isPICStyleGOT())
2400     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2401
2402   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2403   if (Is64Bit && isVarArg && !IsWin64)
2404     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2405
2406   if (InFlag.getNode())
2407     Ops.push_back(InFlag);
2408
2409   if (isTailCall) {
2410     // We used to do:
2411     //// If this is the first return lowered for this function, add the regs
2412     //// to the liveout set for the function.
2413     // This isn't right, although it's probably harmless on x86; liveouts
2414     // should be computed from returns not tail calls.  Consider a void
2415     // function making a tail call to a function returning int.
2416     return DAG.getNode(X86ISD::TC_RETURN, dl,
2417                        NodeTys, &Ops[0], Ops.size());
2418   }
2419
2420   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2421   InFlag = Chain.getValue(1);
2422
2423   // Create the CALLSEQ_END node.
2424   unsigned NumBytesForCalleeToPush;
2425   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2426     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2427   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2428     // If this is a call to a struct-return function, the callee
2429     // pops the hidden struct pointer, so we have to push it back.
2430     // This is common for Darwin/X86, Linux & Mingw32 targets.
2431     NumBytesForCalleeToPush = 4;
2432   else
2433     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2434
2435   // Returns a flag for retval copy to use.
2436   if (!IsSibcall) {
2437     Chain = DAG.getCALLSEQ_END(Chain,
2438                                DAG.getIntPtrConstant(NumBytes, true),
2439                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2440                                                      true),
2441                                InFlag);
2442     InFlag = Chain.getValue(1);
2443   }
2444
2445   // Handle result values, copying them out of physregs into vregs that we
2446   // return.
2447   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2448                          Ins, dl, DAG, InVals);
2449 }
2450
2451
2452 //===----------------------------------------------------------------------===//
2453 //                Fast Calling Convention (tail call) implementation
2454 //===----------------------------------------------------------------------===//
2455
2456 //  Like std call, callee cleans arguments, convention except that ECX is
2457 //  reserved for storing the tail called function address. Only 2 registers are
2458 //  free for argument passing (inreg). Tail call optimization is performed
2459 //  provided:
2460 //                * tailcallopt is enabled
2461 //                * caller/callee are fastcc
2462 //  On X86_64 architecture with GOT-style position independent code only local
2463 //  (within module) calls are supported at the moment.
2464 //  To keep the stack aligned according to platform abi the function
2465 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2466 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2467 //  If a tail called function callee has more arguments than the caller the
2468 //  caller needs to make sure that there is room to move the RETADDR to. This is
2469 //  achieved by reserving an area the size of the argument delta right after the
2470 //  original REtADDR, but before the saved framepointer or the spilled registers
2471 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2472 //  stack layout:
2473 //    arg1
2474 //    arg2
2475 //    RETADDR
2476 //    [ new RETADDR
2477 //      move area ]
2478 //    (possible EBP)
2479 //    ESI
2480 //    EDI
2481 //    local1 ..
2482
2483 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2484 /// for a 16 byte align requirement.
2485 unsigned
2486 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2487                                                SelectionDAG& DAG) const {
2488   MachineFunction &MF = DAG.getMachineFunction();
2489   const TargetMachine &TM = MF.getTarget();
2490   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2491   unsigned StackAlignment = TFI.getStackAlignment();
2492   uint64_t AlignMask = StackAlignment - 1;
2493   int64_t Offset = StackSize;
2494   uint64_t SlotSize = TD->getPointerSize();
2495   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2496     // Number smaller than 12 so just add the difference.
2497     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2498   } else {
2499     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2500     Offset = ((~AlignMask) & Offset) + StackAlignment +
2501       (StackAlignment-SlotSize);
2502   }
2503   return Offset;
2504 }
2505
2506 /// MatchingStackOffset - Return true if the given stack call argument is
2507 /// already available in the same position (relatively) of the caller's
2508 /// incoming argument stack.
2509 static
2510 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2511                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2512                          const X86InstrInfo *TII) {
2513   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2514   int FI = INT_MAX;
2515   if (Arg.getOpcode() == ISD::CopyFromReg) {
2516     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2517     if (!TargetRegisterInfo::isVirtualRegister(VR))
2518       return false;
2519     MachineInstr *Def = MRI->getVRegDef(VR);
2520     if (!Def)
2521       return false;
2522     if (!Flags.isByVal()) {
2523       if (!TII->isLoadFromStackSlot(Def, FI))
2524         return false;
2525     } else {
2526       unsigned Opcode = Def->getOpcode();
2527       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2528           Def->getOperand(1).isFI()) {
2529         FI = Def->getOperand(1).getIndex();
2530         Bytes = Flags.getByValSize();
2531       } else
2532         return false;
2533     }
2534   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2535     if (Flags.isByVal())
2536       // ByVal argument is passed in as a pointer but it's now being
2537       // dereferenced. e.g.
2538       // define @foo(%struct.X* %A) {
2539       //   tail call @bar(%struct.X* byval %A)
2540       // }
2541       return false;
2542     SDValue Ptr = Ld->getBasePtr();
2543     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2544     if (!FINode)
2545       return false;
2546     FI = FINode->getIndex();
2547   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2548     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2549     FI = FINode->getIndex();
2550     Bytes = Flags.getByValSize();
2551   } else
2552     return false;
2553
2554   assert(FI != INT_MAX);
2555   if (!MFI->isFixedObjectIndex(FI))
2556     return false;
2557   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2558 }
2559
2560 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2561 /// for tail call optimization. Targets which want to do tail call
2562 /// optimization should implement this function.
2563 bool
2564 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2565                                                      CallingConv::ID CalleeCC,
2566                                                      bool isVarArg,
2567                                                      bool isCalleeStructRet,
2568                                                      bool isCallerStructRet,
2569                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2570                                     const SmallVectorImpl<SDValue> &OutVals,
2571                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2572                                                      SelectionDAG& DAG) const {
2573   if (!IsTailCallConvention(CalleeCC) &&
2574       CalleeCC != CallingConv::C)
2575     return false;
2576
2577   // If -tailcallopt is specified, make fastcc functions tail-callable.
2578   const MachineFunction &MF = DAG.getMachineFunction();
2579   const Function *CallerF = DAG.getMachineFunction().getFunction();
2580   CallingConv::ID CallerCC = CallerF->getCallingConv();
2581   bool CCMatch = CallerCC == CalleeCC;
2582
2583   if (GuaranteedTailCallOpt) {
2584     if (IsTailCallConvention(CalleeCC) && CCMatch)
2585       return true;
2586     return false;
2587   }
2588
2589   // Look for obvious safe cases to perform tail call optimization that do not
2590   // require ABI changes. This is what gcc calls sibcall.
2591
2592   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2593   // emit a special epilogue.
2594   if (RegInfo->needsStackRealignment(MF))
2595     return false;
2596
2597   // Also avoid sibcall optimization if either caller or callee uses struct
2598   // return semantics.
2599   if (isCalleeStructRet || isCallerStructRet)
2600     return false;
2601
2602   // An stdcall caller is expected to clean up its arguments; the callee
2603   // isn't going to do that.
2604   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2605     return false;
2606
2607   // Do not sibcall optimize vararg calls unless all arguments are passed via
2608   // registers.
2609   if (isVarArg && !Outs.empty()) {
2610
2611     // Optimizing for varargs on Win64 is unlikely to be safe without
2612     // additional testing.
2613     if (Subtarget->isTargetWin64())
2614       return false;
2615
2616     SmallVector<CCValAssign, 16> ArgLocs;
2617     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2618                    getTargetMachine(), ArgLocs, *DAG.getContext());
2619
2620     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2621     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2622       if (!ArgLocs[i].isRegLoc())
2623         return false;
2624   }
2625
2626   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2627   // Therefore if it's not used by the call it is not safe to optimize this into
2628   // a sibcall.
2629   bool Unused = false;
2630   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2631     if (!Ins[i].Used) {
2632       Unused = true;
2633       break;
2634     }
2635   }
2636   if (Unused) {
2637     SmallVector<CCValAssign, 16> RVLocs;
2638     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2639                    getTargetMachine(), RVLocs, *DAG.getContext());
2640     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2641     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2642       CCValAssign &VA = RVLocs[i];
2643       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2644         return false;
2645     }
2646   }
2647
2648   // If the calling conventions do not match, then we'd better make sure the
2649   // results are returned in the same way as what the caller expects.
2650   if (!CCMatch) {
2651     SmallVector<CCValAssign, 16> RVLocs1;
2652     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2653                     getTargetMachine(), RVLocs1, *DAG.getContext());
2654     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2655
2656     SmallVector<CCValAssign, 16> RVLocs2;
2657     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2658                     getTargetMachine(), RVLocs2, *DAG.getContext());
2659     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2660
2661     if (RVLocs1.size() != RVLocs2.size())
2662       return false;
2663     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2664       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2665         return false;
2666       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2667         return false;
2668       if (RVLocs1[i].isRegLoc()) {
2669         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2670           return false;
2671       } else {
2672         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2673           return false;
2674       }
2675     }
2676   }
2677
2678   // If the callee takes no arguments then go on to check the results of the
2679   // call.
2680   if (!Outs.empty()) {
2681     // Check if stack adjustment is needed. For now, do not do this if any
2682     // argument is passed on the stack.
2683     SmallVector<CCValAssign, 16> ArgLocs;
2684     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2685                    getTargetMachine(), ArgLocs, *DAG.getContext());
2686
2687     // Allocate shadow area for Win64
2688     if (Subtarget->isTargetWin64()) {
2689       CCInfo.AllocateStack(32, 8);
2690     }
2691
2692     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2693     if (CCInfo.getNextStackOffset()) {
2694       MachineFunction &MF = DAG.getMachineFunction();
2695       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2696         return false;
2697
2698       // Check if the arguments are already laid out in the right way as
2699       // the caller's fixed stack objects.
2700       MachineFrameInfo *MFI = MF.getFrameInfo();
2701       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2702       const X86InstrInfo *TII =
2703         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2704       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2705         CCValAssign &VA = ArgLocs[i];
2706         SDValue Arg = OutVals[i];
2707         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2708         if (VA.getLocInfo() == CCValAssign::Indirect)
2709           return false;
2710         if (!VA.isRegLoc()) {
2711           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2712                                    MFI, MRI, TII))
2713             return false;
2714         }
2715       }
2716     }
2717
2718     // If the tailcall address may be in a register, then make sure it's
2719     // possible to register allocate for it. In 32-bit, the call address can
2720     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2721     // callee-saved registers are restored. These happen to be the same
2722     // registers used to pass 'inreg' arguments so watch out for those.
2723     if (!Subtarget->is64Bit() &&
2724         !isa<GlobalAddressSDNode>(Callee) &&
2725         !isa<ExternalSymbolSDNode>(Callee)) {
2726       unsigned NumInRegs = 0;
2727       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2728         CCValAssign &VA = ArgLocs[i];
2729         if (!VA.isRegLoc())
2730           continue;
2731         unsigned Reg = VA.getLocReg();
2732         switch (Reg) {
2733         default: break;
2734         case X86::EAX: case X86::EDX: case X86::ECX:
2735           if (++NumInRegs == 3)
2736             return false;
2737           break;
2738         }
2739       }
2740     }
2741   }
2742
2743   return true;
2744 }
2745
2746 FastISel *
2747 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2748   return X86::createFastISel(funcInfo);
2749 }
2750
2751
2752 //===----------------------------------------------------------------------===//
2753 //                           Other Lowering Hooks
2754 //===----------------------------------------------------------------------===//
2755
2756 static bool MayFoldLoad(SDValue Op) {
2757   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2758 }
2759
2760 static bool MayFoldIntoStore(SDValue Op) {
2761   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2762 }
2763
2764 static bool isTargetShuffle(unsigned Opcode) {
2765   switch(Opcode) {
2766   default: return false;
2767   case X86ISD::PSHUFD:
2768   case X86ISD::PSHUFHW:
2769   case X86ISD::PSHUFLW:
2770   case X86ISD::SHUFPD:
2771   case X86ISD::PALIGN:
2772   case X86ISD::SHUFPS:
2773   case X86ISD::MOVLHPS:
2774   case X86ISD::MOVLHPD:
2775   case X86ISD::MOVHLPS:
2776   case X86ISD::MOVLPS:
2777   case X86ISD::MOVLPD:
2778   case X86ISD::MOVSHDUP:
2779   case X86ISD::MOVSLDUP:
2780   case X86ISD::MOVDDUP:
2781   case X86ISD::MOVSS:
2782   case X86ISD::MOVSD:
2783   case X86ISD::UNPCKLPS:
2784   case X86ISD::UNPCKLPD:
2785   case X86ISD::VUNPCKLPSY:
2786   case X86ISD::VUNPCKLPDY:
2787   case X86ISD::PUNPCKLWD:
2788   case X86ISD::PUNPCKLBW:
2789   case X86ISD::PUNPCKLDQ:
2790   case X86ISD::PUNPCKLQDQ:
2791   case X86ISD::UNPCKHPS:
2792   case X86ISD::UNPCKHPD:
2793   case X86ISD::VUNPCKHPSY:
2794   case X86ISD::VUNPCKHPDY:
2795   case X86ISD::PUNPCKHWD:
2796   case X86ISD::PUNPCKHBW:
2797   case X86ISD::PUNPCKHDQ:
2798   case X86ISD::PUNPCKHQDQ:
2799   case X86ISD::VPERMILPS:
2800   case X86ISD::VPERMILPSY:
2801   case X86ISD::VPERMILPD:
2802   case X86ISD::VPERMILPDY:
2803   case X86ISD::VPERM2F128:
2804     return true;
2805   }
2806   return false;
2807 }
2808
2809 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2810                                                SDValue V1, SelectionDAG &DAG) {
2811   switch(Opc) {
2812   default: llvm_unreachable("Unknown x86 shuffle node");
2813   case X86ISD::MOVSHDUP:
2814   case X86ISD::MOVSLDUP:
2815   case X86ISD::MOVDDUP:
2816     return DAG.getNode(Opc, dl, VT, V1);
2817   }
2818
2819   return SDValue();
2820 }
2821
2822 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2823                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2824   switch(Opc) {
2825   default: llvm_unreachable("Unknown x86 shuffle node");
2826   case X86ISD::PSHUFD:
2827   case X86ISD::PSHUFHW:
2828   case X86ISD::PSHUFLW:
2829   case X86ISD::VPERMILPS:
2830   case X86ISD::VPERMILPSY:
2831   case X86ISD::VPERMILPD:
2832   case X86ISD::VPERMILPDY:
2833     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2834   }
2835
2836   return SDValue();
2837 }
2838
2839 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2840                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2841   switch(Opc) {
2842   default: llvm_unreachable("Unknown x86 shuffle node");
2843   case X86ISD::PALIGN:
2844   case X86ISD::SHUFPD:
2845   case X86ISD::SHUFPS:
2846   case X86ISD::VPERM2F128:
2847     return DAG.getNode(Opc, dl, VT, V1, V2,
2848                        DAG.getConstant(TargetMask, MVT::i8));
2849   }
2850   return SDValue();
2851 }
2852
2853 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2854                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2855   switch(Opc) {
2856   default: llvm_unreachable("Unknown x86 shuffle node");
2857   case X86ISD::MOVLHPS:
2858   case X86ISD::MOVLHPD:
2859   case X86ISD::MOVHLPS:
2860   case X86ISD::MOVLPS:
2861   case X86ISD::MOVLPD:
2862   case X86ISD::MOVSS:
2863   case X86ISD::MOVSD:
2864   case X86ISD::UNPCKLPS:
2865   case X86ISD::UNPCKLPD:
2866   case X86ISD::VUNPCKLPSY:
2867   case X86ISD::VUNPCKLPDY:
2868   case X86ISD::PUNPCKLWD:
2869   case X86ISD::PUNPCKLBW:
2870   case X86ISD::PUNPCKLDQ:
2871   case X86ISD::PUNPCKLQDQ:
2872   case X86ISD::UNPCKHPS:
2873   case X86ISD::UNPCKHPD:
2874   case X86ISD::VUNPCKHPSY:
2875   case X86ISD::VUNPCKHPDY:
2876   case X86ISD::PUNPCKHWD:
2877   case X86ISD::PUNPCKHBW:
2878   case X86ISD::PUNPCKHDQ:
2879   case X86ISD::PUNPCKHQDQ:
2880     return DAG.getNode(Opc, dl, VT, V1, V2);
2881   }
2882   return SDValue();
2883 }
2884
2885 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2886   MachineFunction &MF = DAG.getMachineFunction();
2887   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2888   int ReturnAddrIndex = FuncInfo->getRAIndex();
2889
2890   if (ReturnAddrIndex == 0) {
2891     // Set up a frame object for the return address.
2892     uint64_t SlotSize = TD->getPointerSize();
2893     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2894                                                            false);
2895     FuncInfo->setRAIndex(ReturnAddrIndex);
2896   }
2897
2898   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2899 }
2900
2901
2902 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2903                                        bool hasSymbolicDisplacement) {
2904   // Offset should fit into 32 bit immediate field.
2905   if (!isInt<32>(Offset))
2906     return false;
2907
2908   // If we don't have a symbolic displacement - we don't have any extra
2909   // restrictions.
2910   if (!hasSymbolicDisplacement)
2911     return true;
2912
2913   // FIXME: Some tweaks might be needed for medium code model.
2914   if (M != CodeModel::Small && M != CodeModel::Kernel)
2915     return false;
2916
2917   // For small code model we assume that latest object is 16MB before end of 31
2918   // bits boundary. We may also accept pretty large negative constants knowing
2919   // that all objects are in the positive half of address space.
2920   if (M == CodeModel::Small && Offset < 16*1024*1024)
2921     return true;
2922
2923   // For kernel code model we know that all object resist in the negative half
2924   // of 32bits address space. We may not accept negative offsets, since they may
2925   // be just off and we may accept pretty large positive ones.
2926   if (M == CodeModel::Kernel && Offset > 0)
2927     return true;
2928
2929   return false;
2930 }
2931
2932 /// isCalleePop - Determines whether the callee is required to pop its
2933 /// own arguments. Callee pop is necessary to support tail calls.
2934 bool X86::isCalleePop(CallingConv::ID CallingConv,
2935                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2936   if (IsVarArg)
2937     return false;
2938
2939   switch (CallingConv) {
2940   default:
2941     return false;
2942   case CallingConv::X86_StdCall:
2943     return !is64Bit;
2944   case CallingConv::X86_FastCall:
2945     return !is64Bit;
2946   case CallingConv::X86_ThisCall:
2947     return !is64Bit;
2948   case CallingConv::Fast:
2949     return TailCallOpt;
2950   case CallingConv::GHC:
2951     return TailCallOpt;
2952   }
2953 }
2954
2955 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2956 /// specific condition code, returning the condition code and the LHS/RHS of the
2957 /// comparison to make.
2958 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2959                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2960   if (!isFP) {
2961     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2962       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2963         // X > -1   -> X == 0, jump !sign.
2964         RHS = DAG.getConstant(0, RHS.getValueType());
2965         return X86::COND_NS;
2966       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2967         // X < 0   -> X == 0, jump on sign.
2968         return X86::COND_S;
2969       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2970         // X < 1   -> X <= 0
2971         RHS = DAG.getConstant(0, RHS.getValueType());
2972         return X86::COND_LE;
2973       }
2974     }
2975
2976     switch (SetCCOpcode) {
2977     default: llvm_unreachable("Invalid integer condition!");
2978     case ISD::SETEQ:  return X86::COND_E;
2979     case ISD::SETGT:  return X86::COND_G;
2980     case ISD::SETGE:  return X86::COND_GE;
2981     case ISD::SETLT:  return X86::COND_L;
2982     case ISD::SETLE:  return X86::COND_LE;
2983     case ISD::SETNE:  return X86::COND_NE;
2984     case ISD::SETULT: return X86::COND_B;
2985     case ISD::SETUGT: return X86::COND_A;
2986     case ISD::SETULE: return X86::COND_BE;
2987     case ISD::SETUGE: return X86::COND_AE;
2988     }
2989   }
2990
2991   // First determine if it is required or is profitable to flip the operands.
2992
2993   // If LHS is a foldable load, but RHS is not, flip the condition.
2994   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2995       !ISD::isNON_EXTLoad(RHS.getNode())) {
2996     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2997     std::swap(LHS, RHS);
2998   }
2999
3000   switch (SetCCOpcode) {
3001   default: break;
3002   case ISD::SETOLT:
3003   case ISD::SETOLE:
3004   case ISD::SETUGT:
3005   case ISD::SETUGE:
3006     std::swap(LHS, RHS);
3007     break;
3008   }
3009
3010   // On a floating point condition, the flags are set as follows:
3011   // ZF  PF  CF   op
3012   //  0 | 0 | 0 | X > Y
3013   //  0 | 0 | 1 | X < Y
3014   //  1 | 0 | 0 | X == Y
3015   //  1 | 1 | 1 | unordered
3016   switch (SetCCOpcode) {
3017   default: llvm_unreachable("Condcode should be pre-legalized away");
3018   case ISD::SETUEQ:
3019   case ISD::SETEQ:   return X86::COND_E;
3020   case ISD::SETOLT:              // flipped
3021   case ISD::SETOGT:
3022   case ISD::SETGT:   return X86::COND_A;
3023   case ISD::SETOLE:              // flipped
3024   case ISD::SETOGE:
3025   case ISD::SETGE:   return X86::COND_AE;
3026   case ISD::SETUGT:              // flipped
3027   case ISD::SETULT:
3028   case ISD::SETLT:   return X86::COND_B;
3029   case ISD::SETUGE:              // flipped
3030   case ISD::SETULE:
3031   case ISD::SETLE:   return X86::COND_BE;
3032   case ISD::SETONE:
3033   case ISD::SETNE:   return X86::COND_NE;
3034   case ISD::SETUO:   return X86::COND_P;
3035   case ISD::SETO:    return X86::COND_NP;
3036   case ISD::SETOEQ:
3037   case ISD::SETUNE:  return X86::COND_INVALID;
3038   }
3039 }
3040
3041 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3042 /// code. Current x86 isa includes the following FP cmov instructions:
3043 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3044 static bool hasFPCMov(unsigned X86CC) {
3045   switch (X86CC) {
3046   default:
3047     return false;
3048   case X86::COND_B:
3049   case X86::COND_BE:
3050   case X86::COND_E:
3051   case X86::COND_P:
3052   case X86::COND_A:
3053   case X86::COND_AE:
3054   case X86::COND_NE:
3055   case X86::COND_NP:
3056     return true;
3057   }
3058 }
3059
3060 /// isFPImmLegal - Returns true if the target can instruction select the
3061 /// specified FP immediate natively. If false, the legalizer will
3062 /// materialize the FP immediate as a load from a constant pool.
3063 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3064   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3065     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3066       return true;
3067   }
3068   return false;
3069 }
3070
3071 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3072 /// the specified range (L, H].
3073 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3074   return (Val < 0) || (Val >= Low && Val < Hi);
3075 }
3076
3077 /// isUndefOrInRange - Return true if every element in Mask, begining
3078 /// from position Pos and ending in Pos+Size, falls within the specified
3079 /// range (L, L+Pos]. or is undef.
3080 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3081                              int Pos, int Size, int Low, int Hi) {
3082   for (int i = Pos, e = Pos+Size; i != e; ++i)
3083     if (!isUndefOrInRange(Mask[i], Low, Hi))
3084       return false;
3085   return true;
3086 }
3087
3088 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3089 /// specified value.
3090 static bool isUndefOrEqual(int Val, int CmpVal) {
3091   if (Val < 0 || Val == CmpVal)
3092     return true;
3093   return false;
3094 }
3095
3096 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3097 /// from position Pos and ending in Pos+Size, falls within the specified
3098 /// sequential range (L, L+Pos]. or is undef.
3099 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3100                                        int Pos, int Size, int Low) {
3101   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3102     if (!isUndefOrEqual(Mask[i], Low))
3103       return false;
3104   return true;
3105 }
3106
3107 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3108 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3109 /// the second operand.
3110 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3111   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3112     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3113   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3114     return (Mask[0] < 2 && Mask[1] < 2);
3115   return false;
3116 }
3117
3118 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3119   SmallVector<int, 8> M;
3120   N->getMask(M);
3121   return ::isPSHUFDMask(M, N->getValueType(0));
3122 }
3123
3124 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3125 /// is suitable for input to PSHUFHW.
3126 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3127   if (VT != MVT::v8i16)
3128     return false;
3129
3130   // Lower quadword copied in order or undef.
3131   for (int i = 0; i != 4; ++i)
3132     if (Mask[i] >= 0 && Mask[i] != i)
3133       return false;
3134
3135   // Upper quadword shuffled.
3136   for (int i = 4; i != 8; ++i)
3137     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3138       return false;
3139
3140   return true;
3141 }
3142
3143 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3144   SmallVector<int, 8> M;
3145   N->getMask(M);
3146   return ::isPSHUFHWMask(M, N->getValueType(0));
3147 }
3148
3149 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3150 /// is suitable for input to PSHUFLW.
3151 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3152   if (VT != MVT::v8i16)
3153     return false;
3154
3155   // Upper quadword copied in order.
3156   for (int i = 4; i != 8; ++i)
3157     if (Mask[i] >= 0 && Mask[i] != i)
3158       return false;
3159
3160   // Lower quadword shuffled.
3161   for (int i = 0; i != 4; ++i)
3162     if (Mask[i] >= 4)
3163       return false;
3164
3165   return true;
3166 }
3167
3168 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3169   SmallVector<int, 8> M;
3170   N->getMask(M);
3171   return ::isPSHUFLWMask(M, N->getValueType(0));
3172 }
3173
3174 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3175 /// is suitable for input to PALIGNR.
3176 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3177                           bool hasSSSE3) {
3178   int i, e = VT.getVectorNumElements();
3179   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3180     return false;
3181
3182   // Do not handle v2i64 / v2f64 shuffles with palignr.
3183   if (e < 4 || !hasSSSE3)
3184     return false;
3185
3186   for (i = 0; i != e; ++i)
3187     if (Mask[i] >= 0)
3188       break;
3189
3190   // All undef, not a palignr.
3191   if (i == e)
3192     return false;
3193
3194   // Make sure we're shifting in the right direction.
3195   if (Mask[i] <= i)
3196     return false;
3197
3198   int s = Mask[i] - i;
3199
3200   // Check the rest of the elements to see if they are consecutive.
3201   for (++i; i != e; ++i) {
3202     int m = Mask[i];
3203     if (m >= 0 && m != s+i)
3204       return false;
3205   }
3206   return true;
3207 }
3208
3209 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3210 /// specifies a shuffle of elements that is suitable for input to 256-bit
3211 /// VSHUFPSY.
3212 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3213                           const X86Subtarget *Subtarget) {
3214   int NumElems = VT.getVectorNumElements();
3215
3216   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3217     return false;
3218
3219   if (NumElems != 8)
3220     return false;
3221
3222   // VSHUFPSY divides the resulting vector into 4 chunks.
3223   // The sources are also splitted into 4 chunks, and each destination
3224   // chunk must come from a different source chunk.
3225   //
3226   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3227   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3228   //
3229   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3230   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3231   //
3232   int QuarterSize = NumElems/4;
3233   int HalfSize = QuarterSize*2;
3234   for (int i = 0; i < QuarterSize; ++i)
3235     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3236       return false;
3237   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3238     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3239       return false;
3240
3241   // The mask of the second half must be the same as the first but with
3242   // the appropriate offsets. This works in the same way as VPERMILPS
3243   // works with masks.
3244   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3245     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3246       return false;
3247     int FstHalfIdx = i-HalfSize;
3248     if (Mask[FstHalfIdx] < 0)
3249       continue;
3250     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3251       return false;
3252   }
3253   for (int i = QuarterSize*3; i < NumElems; ++i) {
3254     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3255       return false;
3256     int FstHalfIdx = i-HalfSize;
3257     if (Mask[FstHalfIdx] < 0)
3258       continue;
3259     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3260       return false;
3261
3262   }
3263
3264   return true;
3265 }
3266
3267 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3268 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3269 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3270   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3271   EVT VT = SVOp->getValueType(0);
3272   int NumElems = VT.getVectorNumElements();
3273
3274   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3275          "Only supports v8i32 and v8f32 types");
3276
3277   int HalfSize = NumElems/2;
3278   unsigned Mask = 0;
3279   for (int i = 0; i != NumElems ; ++i) {
3280     if (SVOp->getMaskElt(i) < 0)
3281       continue;
3282     // The mask of the first half must be equal to the second one.
3283     unsigned Shamt = (i%HalfSize)*2;
3284     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3285     Mask |= Elt << Shamt;
3286   }
3287
3288   return Mask;
3289 }
3290
3291 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3292 /// specifies a shuffle of elements that is suitable for input to 256-bit
3293 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3294 /// version and the mask of the second half isn't binded with the first
3295 /// one.
3296 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3297                            const X86Subtarget *Subtarget) {
3298   int NumElems = VT.getVectorNumElements();
3299
3300   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3301     return false;
3302
3303   if (NumElems != 4)
3304     return false;
3305
3306   // VSHUFPSY divides the resulting vector into 4 chunks.
3307   // The sources are also splitted into 4 chunks, and each destination
3308   // chunk must come from a different source chunk.
3309   //
3310   //  SRC1 =>      X3       X2       X1       X0
3311   //  SRC2 =>      Y3       Y2       Y1       Y0
3312   //
3313   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3314   //
3315   int QuarterSize = NumElems/4;
3316   int HalfSize = QuarterSize*2;
3317   for (int i = 0; i < QuarterSize; ++i)
3318     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3319       return false;
3320   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3321     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3322       return false;
3323   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3324     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3325       return false;
3326   for (int i = QuarterSize*3; i < NumElems; ++i)
3327     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3328       return false;
3329
3330   return true;
3331 }
3332
3333 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3334 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3335 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3336   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3337   EVT VT = SVOp->getValueType(0);
3338   int NumElems = VT.getVectorNumElements();
3339
3340   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3341          "Only supports v4i64 and v4f64 types");
3342
3343   int HalfSize = NumElems/2;
3344   unsigned Mask = 0;
3345   for (int i = 0; i != NumElems ; ++i) {
3346     if (SVOp->getMaskElt(i) < 0)
3347       continue;
3348     int Elt = SVOp->getMaskElt(i) % HalfSize;
3349     Mask |= Elt << i;
3350   }
3351
3352   return Mask;
3353 }
3354
3355 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3356 /// specifies a shuffle of elements that is suitable for input to 128-bit
3357 /// SHUFPS and SHUFPD.
3358 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3359   int NumElems = VT.getVectorNumElements();
3360
3361   if (VT.getSizeInBits() != 128)
3362     return false;
3363
3364   if (NumElems != 2 && NumElems != 4)
3365     return false;
3366
3367   int Half = NumElems / 2;
3368   for (int i = 0; i < Half; ++i)
3369     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3370       return false;
3371   for (int i = Half; i < NumElems; ++i)
3372     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3373       return false;
3374
3375   return true;
3376 }
3377
3378 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3379   SmallVector<int, 8> M;
3380   N->getMask(M);
3381   return ::isSHUFPMask(M, N->getValueType(0));
3382 }
3383
3384 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3385 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3386 /// half elements to come from vector 1 (which would equal the dest.) and
3387 /// the upper half to come from vector 2.
3388 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3389   int NumElems = VT.getVectorNumElements();
3390
3391   if (NumElems != 2 && NumElems != 4)
3392     return false;
3393
3394   int Half = NumElems / 2;
3395   for (int i = 0; i < Half; ++i)
3396     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3397       return false;
3398   for (int i = Half; i < NumElems; ++i)
3399     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3400       return false;
3401   return true;
3402 }
3403
3404 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3405   SmallVector<int, 8> M;
3406   N->getMask(M);
3407   return isCommutedSHUFPMask(M, N->getValueType(0));
3408 }
3409
3410 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3411 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3412 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3413   EVT VT = N->getValueType(0);
3414   unsigned NumElems = VT.getVectorNumElements();
3415
3416   if (VT.getSizeInBits() != 128)
3417     return false;
3418
3419   if (NumElems != 4)
3420     return false;
3421
3422   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3423   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3424          isUndefOrEqual(N->getMaskElt(1), 7) &&
3425          isUndefOrEqual(N->getMaskElt(2), 2) &&
3426          isUndefOrEqual(N->getMaskElt(3), 3);
3427 }
3428
3429 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3430 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3431 /// <2, 3, 2, 3>
3432 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3433   EVT VT = N->getValueType(0);
3434   unsigned NumElems = VT.getVectorNumElements();
3435
3436   if (VT.getSizeInBits() != 128)
3437     return false;
3438
3439   if (NumElems != 4)
3440     return false;
3441
3442   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3443          isUndefOrEqual(N->getMaskElt(1), 3) &&
3444          isUndefOrEqual(N->getMaskElt(2), 2) &&
3445          isUndefOrEqual(N->getMaskElt(3), 3);
3446 }
3447
3448 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3449 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3450 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3451   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3452
3453   if (NumElems != 2 && NumElems != 4)
3454     return false;
3455
3456   for (unsigned i = 0; i < NumElems/2; ++i)
3457     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3458       return false;
3459
3460   for (unsigned i = NumElems/2; i < NumElems; ++i)
3461     if (!isUndefOrEqual(N->getMaskElt(i), i))
3462       return false;
3463
3464   return true;
3465 }
3466
3467 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3468 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3469 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3470   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3471
3472   if ((NumElems != 2 && NumElems != 4)
3473       || N->getValueType(0).getSizeInBits() > 128)
3474     return false;
3475
3476   for (unsigned i = 0; i < NumElems/2; ++i)
3477     if (!isUndefOrEqual(N->getMaskElt(i), i))
3478       return false;
3479
3480   for (unsigned i = 0; i < NumElems/2; ++i)
3481     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3482       return false;
3483
3484   return true;
3485 }
3486
3487 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3488 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3489 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3490                          bool V2IsSplat = false) {
3491   int NumElts = VT.getVectorNumElements();
3492
3493   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3494          "Unsupported vector type for unpckh");
3495
3496   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3497     return false;
3498
3499   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3500   // independently on 128-bit lanes.
3501   unsigned NumLanes = VT.getSizeInBits()/128;
3502   unsigned NumLaneElts = NumElts/NumLanes;
3503
3504   unsigned Start = 0;
3505   unsigned End = NumLaneElts;
3506   for (unsigned s = 0; s < NumLanes; ++s) {
3507     for (unsigned i = Start, j = s * NumLaneElts;
3508          i != End;
3509          i += 2, ++j) {
3510       int BitI  = Mask[i];
3511       int BitI1 = Mask[i+1];
3512       if (!isUndefOrEqual(BitI, j))
3513         return false;
3514       if (V2IsSplat) {
3515         if (!isUndefOrEqual(BitI1, NumElts))
3516           return false;
3517       } else {
3518         if (!isUndefOrEqual(BitI1, j + NumElts))
3519           return false;
3520       }
3521     }
3522     // Process the next 128 bits.
3523     Start += NumLaneElts;
3524     End += NumLaneElts;
3525   }
3526
3527   return true;
3528 }
3529
3530 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3531   SmallVector<int, 8> M;
3532   N->getMask(M);
3533   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3534 }
3535
3536 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3537 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3538 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3539                          bool V2IsSplat = false) {
3540   int NumElts = VT.getVectorNumElements();
3541
3542   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3543          "Unsupported vector type for unpckh");
3544
3545   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3546     return false;
3547
3548   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3549   // independently on 128-bit lanes.
3550   unsigned NumLanes = VT.getSizeInBits()/128;
3551   unsigned NumLaneElts = NumElts/NumLanes;
3552
3553   unsigned Start = 0;
3554   unsigned End = NumLaneElts;
3555   for (unsigned l = 0; l != NumLanes; ++l) {
3556     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3557                              i != End; i += 2, ++j) {
3558       int BitI  = Mask[i];
3559       int BitI1 = Mask[i+1];
3560       if (!isUndefOrEqual(BitI, j))
3561         return false;
3562       if (V2IsSplat) {
3563         if (isUndefOrEqual(BitI1, NumElts))
3564           return false;
3565       } else {
3566         if (!isUndefOrEqual(BitI1, j+NumElts))
3567           return false;
3568       }
3569     }
3570     // Process the next 128 bits.
3571     Start += NumLaneElts;
3572     End += NumLaneElts;
3573   }
3574   return true;
3575 }
3576
3577 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3578   SmallVector<int, 8> M;
3579   N->getMask(M);
3580   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3581 }
3582
3583 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3584 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3585 /// <0, 0, 1, 1>
3586 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3587   int NumElems = VT.getVectorNumElements();
3588   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3589     return false;
3590
3591   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3592   // FIXME: Need a better way to get rid of this, there's no latency difference
3593   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3594   // the former later. We should also remove the "_undef" special mask.
3595   if (NumElems == 4 && VT.getSizeInBits() == 256)
3596     return false;
3597
3598   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3599   // independently on 128-bit lanes.
3600   unsigned NumLanes = VT.getSizeInBits() / 128;
3601   unsigned NumLaneElts = NumElems / NumLanes;
3602
3603   for (unsigned s = 0; s < NumLanes; ++s) {
3604     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3605          i != NumLaneElts * (s + 1);
3606          i += 2, ++j) {
3607       int BitI  = Mask[i];
3608       int BitI1 = Mask[i+1];
3609
3610       if (!isUndefOrEqual(BitI, j))
3611         return false;
3612       if (!isUndefOrEqual(BitI1, j))
3613         return false;
3614     }
3615   }
3616
3617   return true;
3618 }
3619
3620 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3621   SmallVector<int, 8> M;
3622   N->getMask(M);
3623   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3624 }
3625
3626 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3627 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3628 /// <2, 2, 3, 3>
3629 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3630   int NumElems = VT.getVectorNumElements();
3631   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3632     return false;
3633
3634   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3635     int BitI  = Mask[i];
3636     int BitI1 = Mask[i+1];
3637     if (!isUndefOrEqual(BitI, j))
3638       return false;
3639     if (!isUndefOrEqual(BitI1, j))
3640       return false;
3641   }
3642   return true;
3643 }
3644
3645 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3646   SmallVector<int, 8> M;
3647   N->getMask(M);
3648   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3649 }
3650
3651 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3652 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3653 /// MOVSD, and MOVD, i.e. setting the lowest element.
3654 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3655   if (VT.getVectorElementType().getSizeInBits() < 32)
3656     return false;
3657
3658   int NumElts = VT.getVectorNumElements();
3659
3660   if (!isUndefOrEqual(Mask[0], NumElts))
3661     return false;
3662
3663   for (int i = 1; i < NumElts; ++i)
3664     if (!isUndefOrEqual(Mask[i], i))
3665       return false;
3666
3667   return true;
3668 }
3669
3670 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3671   SmallVector<int, 8> M;
3672   N->getMask(M);
3673   return ::isMOVLMask(M, N->getValueType(0));
3674 }
3675
3676 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3677 /// as permutations between 128-bit chunks or halves. As an example: this
3678 /// shuffle bellow:
3679 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3680 /// The first half comes from the second half of V1 and the second half from the
3681 /// the second half of V2.
3682 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3683                              const X86Subtarget *Subtarget) {
3684   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3685     return false;
3686
3687   // The shuffle result is divided into half A and half B. In total the two
3688   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3689   // B must come from C, D, E or F.
3690   int HalfSize = VT.getVectorNumElements()/2;
3691   bool MatchA = false, MatchB = false;
3692
3693   // Check if A comes from one of C, D, E, F.
3694   for (int Half = 0; Half < 4; ++Half) {
3695     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3696       MatchA = true;
3697       break;
3698     }
3699   }
3700
3701   // Check if B comes from one of C, D, E, F.
3702   for (int Half = 0; Half < 4; ++Half) {
3703     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3704       MatchB = true;
3705       break;
3706     }
3707   }
3708
3709   return MatchA && MatchB;
3710 }
3711
3712 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3713 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3714 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3715   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3716   EVT VT = SVOp->getValueType(0);
3717
3718   int HalfSize = VT.getVectorNumElements()/2;
3719
3720   int FstHalf = 0, SndHalf = 0;
3721   for (int i = 0; i < HalfSize; ++i) {
3722     if (SVOp->getMaskElt(i) > 0) {
3723       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3724       break;
3725     }
3726   }
3727   for (int i = HalfSize; i < HalfSize*2; ++i) {
3728     if (SVOp->getMaskElt(i) > 0) {
3729       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3730       break;
3731     }
3732   }
3733
3734   return (FstHalf | (SndHalf << 4));
3735 }
3736
3737 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3738 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3739 /// Note that VPERMIL mask matching is different depending whether theunderlying
3740 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3741 /// to the same elements of the low, but to the higher half of the source.
3742 /// In VPERMILPD the two lanes could be shuffled independently of each other
3743 /// with the same restriction that lanes can't be crossed.
3744 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3745                             const X86Subtarget *Subtarget) {
3746   int NumElts = VT.getVectorNumElements();
3747   int NumLanes = VT.getSizeInBits()/128;
3748
3749   if (!Subtarget->hasAVX())
3750     return false;
3751
3752   // Match any permutation of 128-bit vector with 64-bit types
3753   if (NumLanes == 1 && NumElts != 2)
3754     return false;
3755
3756   // Only match 256-bit with 32 types
3757   if (VT.getSizeInBits() == 256 && NumElts != 4)
3758     return false;
3759
3760   // The mask on the high lane is independent of the low. Both can match
3761   // any element in inside its own lane, but can't cross.
3762   int LaneSize = NumElts/NumLanes;
3763   for (int l = 0; l < NumLanes; ++l)
3764     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3765       int LaneStart = l*LaneSize;
3766       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3767         return false;
3768     }
3769
3770   return true;
3771 }
3772
3773 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3774 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3775 /// Note that VPERMIL mask matching is different depending whether theunderlying
3776 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3777 /// to the same elements of the low, but to the higher half of the source.
3778 /// In VPERMILPD the two lanes could be shuffled independently of each other
3779 /// with the same restriction that lanes can't be crossed.
3780 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3781                             const X86Subtarget *Subtarget) {
3782   unsigned NumElts = VT.getVectorNumElements();
3783   unsigned NumLanes = VT.getSizeInBits()/128;
3784
3785   if (!Subtarget->hasAVX())
3786     return false;
3787
3788   // Match any permutation of 128-bit vector with 32-bit types
3789   if (NumLanes == 1 && NumElts != 4)
3790     return false;
3791
3792   // Only match 256-bit with 32 types
3793   if (VT.getSizeInBits() == 256 && NumElts != 8)
3794     return false;
3795
3796   // The mask on the high lane should be the same as the low. Actually,
3797   // they can differ if any of the corresponding index in a lane is undef
3798   // and the other stays in range.
3799   int LaneSize = NumElts/NumLanes;
3800   for (int i = 0; i < LaneSize; ++i) {
3801     int HighElt = i+LaneSize;
3802     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3803     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3804
3805     if (!HighValid || !LowValid)
3806       return false;
3807     if (Mask[i] < 0 || Mask[HighElt] < 0)
3808       continue;
3809     if (Mask[HighElt]-Mask[i] != LaneSize)
3810       return false;
3811   }
3812
3813   return true;
3814 }
3815
3816 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3817 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3818 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3819   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3820   EVT VT = SVOp->getValueType(0);
3821
3822   int NumElts = VT.getVectorNumElements();
3823   int NumLanes = VT.getSizeInBits()/128;
3824   int LaneSize = NumElts/NumLanes;
3825
3826   // Although the mask is equal for both lanes do it twice to get the cases
3827   // where a mask will match because the same mask element is undef on the
3828   // first half but valid on the second. This would get pathological cases
3829   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3830   unsigned Mask = 0;
3831   for (int l = 0; l < NumLanes; ++l) {
3832     for (int i = 0; i < LaneSize; ++i) {
3833       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3834       if (MaskElt < 0)
3835         continue;
3836       if (MaskElt >= LaneSize)
3837         MaskElt -= LaneSize;
3838       Mask |= MaskElt << (i*2);
3839     }
3840   }
3841
3842   return Mask;
3843 }
3844
3845 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3846 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3847 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3848   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3849   EVT VT = SVOp->getValueType(0);
3850
3851   int NumElts = VT.getVectorNumElements();
3852   int NumLanes = VT.getSizeInBits()/128;
3853
3854   unsigned Mask = 0;
3855   int LaneSize = NumElts/NumLanes;
3856   for (int l = 0; l < NumLanes; ++l)
3857     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3858       int MaskElt = SVOp->getMaskElt(i);
3859       if (MaskElt < 0)
3860         continue;
3861       Mask |= (MaskElt-l*LaneSize) << i;
3862     }
3863
3864   return Mask;
3865 }
3866
3867 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3868 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3869 /// element of vector 2 and the other elements to come from vector 1 in order.
3870 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3871                                bool V2IsSplat = false, bool V2IsUndef = false) {
3872   int NumOps = VT.getVectorNumElements();
3873   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3874     return false;
3875
3876   if (!isUndefOrEqual(Mask[0], 0))
3877     return false;
3878
3879   for (int i = 1; i < NumOps; ++i)
3880     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3881           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3882           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3883       return false;
3884
3885   return true;
3886 }
3887
3888 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3889                            bool V2IsUndef = false) {
3890   SmallVector<int, 8> M;
3891   N->getMask(M);
3892   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3893 }
3894
3895 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3896 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3897 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3898 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3899                          const X86Subtarget *Subtarget) {
3900   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3901     return false;
3902
3903   // The second vector must be undef
3904   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3905     return false;
3906
3907   EVT VT = N->getValueType(0);
3908   unsigned NumElems = VT.getVectorNumElements();
3909
3910   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3911       (VT.getSizeInBits() == 256 && NumElems != 8))
3912     return false;
3913
3914   // "i+1" is the value the indexed mask element must have
3915   for (unsigned i = 0; i < NumElems; i += 2)
3916     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3917         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3918       return false;
3919
3920   return true;
3921 }
3922
3923 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3925 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3926 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3927                          const X86Subtarget *Subtarget) {
3928   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3929     return false;
3930
3931   // The second vector must be undef
3932   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3933     return false;
3934
3935   EVT VT = N->getValueType(0);
3936   unsigned NumElems = VT.getVectorNumElements();
3937
3938   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3939       (VT.getSizeInBits() == 256 && NumElems != 8))
3940     return false;
3941
3942   // "i" is the value the indexed mask element must have
3943   for (unsigned i = 0; i < NumElems; i += 2)
3944     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3945         !isUndefOrEqual(N->getMaskElt(i+1), i))
3946       return false;
3947
3948   return true;
3949 }
3950
3951 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to 256-bit
3953 /// version of MOVDDUP.
3954 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3955                            const X86Subtarget *Subtarget) {
3956   EVT VT = N->getValueType(0);
3957   int NumElts = VT.getVectorNumElements();
3958   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3959
3960   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3961       !V2IsUndef || NumElts != 4)
3962     return false;
3963
3964   for (int i = 0; i != NumElts/2; ++i)
3965     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3966       return false;
3967   for (int i = NumElts/2; i != NumElts; ++i)
3968     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3969       return false;
3970   return true;
3971 }
3972
3973 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3974 /// specifies a shuffle of elements that is suitable for input to 128-bit
3975 /// version of MOVDDUP.
3976 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3977   EVT VT = N->getValueType(0);
3978
3979   if (VT.getSizeInBits() != 128)
3980     return false;
3981
3982   int e = VT.getVectorNumElements() / 2;
3983   for (int i = 0; i < e; ++i)
3984     if (!isUndefOrEqual(N->getMaskElt(i), i))
3985       return false;
3986   for (int i = 0; i < e; ++i)
3987     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3988       return false;
3989   return true;
3990 }
3991
3992 /// isVEXTRACTF128Index - Return true if the specified
3993 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3994 /// suitable for input to VEXTRACTF128.
3995 bool X86::isVEXTRACTF128Index(SDNode *N) {
3996   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3997     return false;
3998
3999   // The index should be aligned on a 128-bit boundary.
4000   uint64_t Index =
4001     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4002
4003   unsigned VL = N->getValueType(0).getVectorNumElements();
4004   unsigned VBits = N->getValueType(0).getSizeInBits();
4005   unsigned ElSize = VBits / VL;
4006   bool Result = (Index * ElSize) % 128 == 0;
4007
4008   return Result;
4009 }
4010
4011 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4012 /// operand specifies a subvector insert that is suitable for input to
4013 /// VINSERTF128.
4014 bool X86::isVINSERTF128Index(SDNode *N) {
4015   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4016     return false;
4017
4018   // The index should be aligned on a 128-bit boundary.
4019   uint64_t Index =
4020     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4021
4022   unsigned VL = N->getValueType(0).getVectorNumElements();
4023   unsigned VBits = N->getValueType(0).getSizeInBits();
4024   unsigned ElSize = VBits / VL;
4025   bool Result = (Index * ElSize) % 128 == 0;
4026
4027   return Result;
4028 }
4029
4030 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4031 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4032 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4033   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4034   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4035
4036   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4037   unsigned Mask = 0;
4038   for (int i = 0; i < NumOperands; ++i) {
4039     int Val = SVOp->getMaskElt(NumOperands-i-1);
4040     if (Val < 0) Val = 0;
4041     if (Val >= NumOperands) Val -= NumOperands;
4042     Mask |= Val;
4043     if (i != NumOperands - 1)
4044       Mask <<= Shift;
4045   }
4046   return Mask;
4047 }
4048
4049 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4050 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4051 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4053   unsigned Mask = 0;
4054   // 8 nodes, but we only care about the last 4.
4055   for (unsigned i = 7; i >= 4; --i) {
4056     int Val = SVOp->getMaskElt(i);
4057     if (Val >= 0)
4058       Mask |= (Val - 4);
4059     if (i != 4)
4060       Mask <<= 2;
4061   }
4062   return Mask;
4063 }
4064
4065 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4067 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4069   unsigned Mask = 0;
4070   // 8 nodes, but we only care about the first 4.
4071   for (int i = 3; i >= 0; --i) {
4072     int Val = SVOp->getMaskElt(i);
4073     if (Val >= 0)
4074       Mask |= Val;
4075     if (i != 0)
4076       Mask <<= 2;
4077   }
4078   return Mask;
4079 }
4080
4081 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4083 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4084   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4085   EVT VVT = N->getValueType(0);
4086   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4087   int Val = 0;
4088
4089   unsigned i, e;
4090   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4091     Val = SVOp->getMaskElt(i);
4092     if (Val >= 0)
4093       break;
4094   }
4095   assert(Val - i > 0 && "PALIGNR imm should be positive");
4096   return (Val - i) * EltSize;
4097 }
4098
4099 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4100 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4101 /// instructions.
4102 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4103   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4104     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4105
4106   uint64_t Index =
4107     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4108
4109   EVT VecVT = N->getOperand(0).getValueType();
4110   EVT ElVT = VecVT.getVectorElementType();
4111
4112   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4113   return Index / NumElemsPerChunk;
4114 }
4115
4116 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4117 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4118 /// instructions.
4119 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4120   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4121     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4122
4123   uint64_t Index =
4124     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4125
4126   EVT VecVT = N->getValueType(0);
4127   EVT ElVT = VecVT.getVectorElementType();
4128
4129   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4130   return Index / NumElemsPerChunk;
4131 }
4132
4133 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4134 /// constant +0.0.
4135 bool X86::isZeroNode(SDValue Elt) {
4136   return ((isa<ConstantSDNode>(Elt) &&
4137            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4138           (isa<ConstantFPSDNode>(Elt) &&
4139            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4140 }
4141
4142 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4143 /// their permute mask.
4144 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4145                                     SelectionDAG &DAG) {
4146   EVT VT = SVOp->getValueType(0);
4147   unsigned NumElems = VT.getVectorNumElements();
4148   SmallVector<int, 8> MaskVec;
4149
4150   for (unsigned i = 0; i != NumElems; ++i) {
4151     int idx = SVOp->getMaskElt(i);
4152     if (idx < 0)
4153       MaskVec.push_back(idx);
4154     else if (idx < (int)NumElems)
4155       MaskVec.push_back(idx + NumElems);
4156     else
4157       MaskVec.push_back(idx - NumElems);
4158   }
4159   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4160                               SVOp->getOperand(0), &MaskVec[0]);
4161 }
4162
4163 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4164 /// the two vector operands have swapped position.
4165 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4166   unsigned NumElems = VT.getVectorNumElements();
4167   for (unsigned i = 0; i != NumElems; ++i) {
4168     int idx = Mask[i];
4169     if (idx < 0)
4170       continue;
4171     else if (idx < (int)NumElems)
4172       Mask[i] = idx + NumElems;
4173     else
4174       Mask[i] = idx - NumElems;
4175   }
4176 }
4177
4178 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4179 /// match movhlps. The lower half elements should come from upper half of
4180 /// V1 (and in order), and the upper half elements should come from the upper
4181 /// half of V2 (and in order).
4182 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4183   EVT VT = Op->getValueType(0);
4184   if (VT.getSizeInBits() != 128)
4185     return false;
4186   if (VT.getVectorNumElements() != 4)
4187     return false;
4188   for (unsigned i = 0, e = 2; i != e; ++i)
4189     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4190       return false;
4191   for (unsigned i = 2; i != 4; ++i)
4192     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4193       return false;
4194   return true;
4195 }
4196
4197 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4198 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4199 /// required.
4200 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4201   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4202     return false;
4203   N = N->getOperand(0).getNode();
4204   if (!ISD::isNON_EXTLoad(N))
4205     return false;
4206   if (LD)
4207     *LD = cast<LoadSDNode>(N);
4208   return true;
4209 }
4210
4211 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4212 /// match movlp{s|d}. The lower half elements should come from lower half of
4213 /// V1 (and in order), and the upper half elements should come from the upper
4214 /// half of V2 (and in order). And since V1 will become the source of the
4215 /// MOVLP, it must be either a vector load or a scalar load to vector.
4216 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4217                                ShuffleVectorSDNode *Op) {
4218   EVT VT = Op->getValueType(0);
4219   if (VT.getSizeInBits() != 128)
4220     return false;
4221
4222   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4223     return false;
4224   // Is V2 is a vector load, don't do this transformation. We will try to use
4225   // load folding shufps op.
4226   if (ISD::isNON_EXTLoad(V2))
4227     return false;
4228
4229   unsigned NumElems = VT.getVectorNumElements();
4230
4231   if (NumElems != 2 && NumElems != 4)
4232     return false;
4233   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4234     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4235       return false;
4236   for (unsigned i = NumElems/2; i != NumElems; ++i)
4237     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4238       return false;
4239   return true;
4240 }
4241
4242 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4243 /// all the same.
4244 static bool isSplatVector(SDNode *N) {
4245   if (N->getOpcode() != ISD::BUILD_VECTOR)
4246     return false;
4247
4248   SDValue SplatValue = N->getOperand(0);
4249   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4250     if (N->getOperand(i) != SplatValue)
4251       return false;
4252   return true;
4253 }
4254
4255 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4256 /// to an zero vector.
4257 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4258 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4259   SDValue V1 = N->getOperand(0);
4260   SDValue V2 = N->getOperand(1);
4261   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4262   for (unsigned i = 0; i != NumElems; ++i) {
4263     int Idx = N->getMaskElt(i);
4264     if (Idx >= (int)NumElems) {
4265       unsigned Opc = V2.getOpcode();
4266       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4267         continue;
4268       if (Opc != ISD::BUILD_VECTOR ||
4269           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4270         return false;
4271     } else if (Idx >= 0) {
4272       unsigned Opc = V1.getOpcode();
4273       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4274         continue;
4275       if (Opc != ISD::BUILD_VECTOR ||
4276           !X86::isZeroNode(V1.getOperand(Idx)))
4277         return false;
4278     }
4279   }
4280   return true;
4281 }
4282
4283 /// getZeroVector - Returns a vector of specified type with all zero elements.
4284 ///
4285 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4286                              DebugLoc dl) {
4287   assert(VT.isVector() && "Expected a vector type");
4288
4289   // Always build SSE zero vectors as <4 x i32> bitcasted
4290   // to their dest type. This ensures they get CSE'd.
4291   SDValue Vec;
4292   if (VT.getSizeInBits() == 128) {  // SSE
4293     if (HasSSE2) {  // SSE2
4294       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4295       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4296     } else { // SSE1
4297       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4298       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4299     }
4300   } else if (VT.getSizeInBits() == 256) { // AVX
4301     // 256-bit logic and arithmetic instructions in AVX are
4302     // all floating-point, no support for integer ops. Default
4303     // to emitting fp zeroed vectors then.
4304     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4305     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4306     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4307   }
4308   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4309 }
4310
4311 /// getOnesVector - Returns a vector of specified type with all bits set.
4312 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4313 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4314 /// original type, ensuring they get CSE'd.
4315 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4316   assert(VT.isVector() && "Expected a vector type");
4317   assert((VT.is128BitVector() || VT.is256BitVector())
4318          && "Expected a 128-bit or 256-bit vector type");
4319
4320   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4321   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4322                             Cst, Cst, Cst, Cst);
4323
4324   if (VT.is256BitVector()) {
4325     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4326                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4327     Vec = Insert128BitVector(InsV, Vec,
4328                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4329   }
4330
4331   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4332 }
4333
4334 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4335 /// that point to V2 points to its first element.
4336 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4337   EVT VT = SVOp->getValueType(0);
4338   unsigned NumElems = VT.getVectorNumElements();
4339
4340   bool Changed = false;
4341   SmallVector<int, 8> MaskVec;
4342   SVOp->getMask(MaskVec);
4343
4344   for (unsigned i = 0; i != NumElems; ++i) {
4345     if (MaskVec[i] > (int)NumElems) {
4346       MaskVec[i] = NumElems;
4347       Changed = true;
4348     }
4349   }
4350   if (Changed)
4351     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4352                                 SVOp->getOperand(1), &MaskVec[0]);
4353   return SDValue(SVOp, 0);
4354 }
4355
4356 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4357 /// operation of specified width.
4358 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4359                        SDValue V2) {
4360   unsigned NumElems = VT.getVectorNumElements();
4361   SmallVector<int, 8> Mask;
4362   Mask.push_back(NumElems);
4363   for (unsigned i = 1; i != NumElems; ++i)
4364     Mask.push_back(i);
4365   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4366 }
4367
4368 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4369 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4370                           SDValue V2) {
4371   unsigned NumElems = VT.getVectorNumElements();
4372   SmallVector<int, 8> Mask;
4373   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4374     Mask.push_back(i);
4375     Mask.push_back(i + NumElems);
4376   }
4377   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4378 }
4379
4380 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4381 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4382                           SDValue V2) {
4383   unsigned NumElems = VT.getVectorNumElements();
4384   unsigned Half = NumElems/2;
4385   SmallVector<int, 8> Mask;
4386   for (unsigned i = 0; i != Half; ++i) {
4387     Mask.push_back(i + Half);
4388     Mask.push_back(i + NumElems + Half);
4389   }
4390   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4391 }
4392
4393 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4394 // a generic shuffle instruction because the target has no such instructions.
4395 // Generate shuffles which repeat i16 and i8 several times until they can be
4396 // represented by v4f32 and then be manipulated by target suported shuffles.
4397 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4398   EVT VT = V.getValueType();
4399   int NumElems = VT.getVectorNumElements();
4400   DebugLoc dl = V.getDebugLoc();
4401
4402   while (NumElems > 4) {
4403     if (EltNo < NumElems/2) {
4404       V = getUnpackl(DAG, dl, VT, V, V);
4405     } else {
4406       V = getUnpackh(DAG, dl, VT, V, V);
4407       EltNo -= NumElems/2;
4408     }
4409     NumElems >>= 1;
4410   }
4411   return V;
4412 }
4413
4414 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4415 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4416   EVT VT = V.getValueType();
4417   DebugLoc dl = V.getDebugLoc();
4418   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4419          && "Vector size not supported");
4420
4421   if (VT.getSizeInBits() == 128) {
4422     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4423     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4424     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4425                              &SplatMask[0]);
4426   } else {
4427     // To use VPERMILPS to splat scalars, the second half of indicies must
4428     // refer to the higher part, which is a duplication of the lower one,
4429     // because VPERMILPS can only handle in-lane permutations.
4430     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4431                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4432
4433     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4434     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4435                              &SplatMask[0]);
4436   }
4437
4438   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4439 }
4440
4441 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4442 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4443   EVT SrcVT = SV->getValueType(0);
4444   SDValue V1 = SV->getOperand(0);
4445   DebugLoc dl = SV->getDebugLoc();
4446
4447   int EltNo = SV->getSplatIndex();
4448   int NumElems = SrcVT.getVectorNumElements();
4449   unsigned Size = SrcVT.getSizeInBits();
4450
4451   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4452           "Unknown how to promote splat for type");
4453
4454   // Extract the 128-bit part containing the splat element and update
4455   // the splat element index when it refers to the higher register.
4456   if (Size == 256) {
4457     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4458     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4459     if (Idx > 0)
4460       EltNo -= NumElems/2;
4461   }
4462
4463   // All i16 and i8 vector types can't be used directly by a generic shuffle
4464   // instruction because the target has no such instruction. Generate shuffles
4465   // which repeat i16 and i8 several times until they fit in i32, and then can
4466   // be manipulated by target suported shuffles.
4467   EVT EltVT = SrcVT.getVectorElementType();
4468   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4469     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4470
4471   // Recreate the 256-bit vector and place the same 128-bit vector
4472   // into the low and high part. This is necessary because we want
4473   // to use VPERM* to shuffle the vectors
4474   if (Size == 256) {
4475     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4476                          DAG.getConstant(0, MVT::i32), DAG, dl);
4477     V1 = Insert128BitVector(InsV, V1,
4478                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4479   }
4480
4481   return getLegalSplat(DAG, V1, EltNo);
4482 }
4483
4484 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4485 /// vector of zero or undef vector.  This produces a shuffle where the low
4486 /// element of V2 is swizzled into the zero/undef vector, landing at element
4487 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4488 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4489                                              bool isZero, bool HasSSE2,
4490                                              SelectionDAG &DAG) {
4491   EVT VT = V2.getValueType();
4492   SDValue V1 = isZero
4493     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4494   unsigned NumElems = VT.getVectorNumElements();
4495   SmallVector<int, 16> MaskVec;
4496   for (unsigned i = 0; i != NumElems; ++i)
4497     // If this is the insertion idx, put the low elt of V2 here.
4498     MaskVec.push_back(i == Idx ? NumElems : i);
4499   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4500 }
4501
4502 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4503 /// element of the result of the vector shuffle.
4504 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4505                                    unsigned Depth) {
4506   if (Depth == 6)
4507     return SDValue();  // Limit search depth.
4508
4509   SDValue V = SDValue(N, 0);
4510   EVT VT = V.getValueType();
4511   unsigned Opcode = V.getOpcode();
4512
4513   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4514   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4515     Index = SV->getMaskElt(Index);
4516
4517     if (Index < 0)
4518       return DAG.getUNDEF(VT.getVectorElementType());
4519
4520     int NumElems = VT.getVectorNumElements();
4521     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4522     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4523   }
4524
4525   // Recurse into target specific vector shuffles to find scalars.
4526   if (isTargetShuffle(Opcode)) {
4527     int NumElems = VT.getVectorNumElements();
4528     SmallVector<unsigned, 16> ShuffleMask;
4529     SDValue ImmN;
4530
4531     switch(Opcode) {
4532     case X86ISD::SHUFPS:
4533     case X86ISD::SHUFPD:
4534       ImmN = N->getOperand(N->getNumOperands()-1);
4535       DecodeSHUFPSMask(NumElems,
4536                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4537                        ShuffleMask);
4538       break;
4539     case X86ISD::PUNPCKHBW:
4540     case X86ISD::PUNPCKHWD:
4541     case X86ISD::PUNPCKHDQ:
4542     case X86ISD::PUNPCKHQDQ:
4543       DecodePUNPCKHMask(NumElems, ShuffleMask);
4544       break;
4545     case X86ISD::UNPCKHPS:
4546     case X86ISD::UNPCKHPD:
4547     case X86ISD::VUNPCKHPSY:
4548     case X86ISD::VUNPCKHPDY:
4549       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4550       break;
4551     case X86ISD::PUNPCKLBW:
4552     case X86ISD::PUNPCKLWD:
4553     case X86ISD::PUNPCKLDQ:
4554     case X86ISD::PUNPCKLQDQ:
4555       DecodePUNPCKLMask(VT, ShuffleMask);
4556       break;
4557     case X86ISD::UNPCKLPS:
4558     case X86ISD::UNPCKLPD:
4559     case X86ISD::VUNPCKLPSY:
4560     case X86ISD::VUNPCKLPDY:
4561       DecodeUNPCKLPMask(VT, ShuffleMask);
4562       break;
4563     case X86ISD::MOVHLPS:
4564       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4565       break;
4566     case X86ISD::MOVLHPS:
4567       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4568       break;
4569     case X86ISD::PSHUFD:
4570       ImmN = N->getOperand(N->getNumOperands()-1);
4571       DecodePSHUFMask(NumElems,
4572                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4573                       ShuffleMask);
4574       break;
4575     case X86ISD::PSHUFHW:
4576       ImmN = N->getOperand(N->getNumOperands()-1);
4577       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4578                         ShuffleMask);
4579       break;
4580     case X86ISD::PSHUFLW:
4581       ImmN = N->getOperand(N->getNumOperands()-1);
4582       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4583                         ShuffleMask);
4584       break;
4585     case X86ISD::MOVSS:
4586     case X86ISD::MOVSD: {
4587       // The index 0 always comes from the first element of the second source,
4588       // this is why MOVSS and MOVSD are used in the first place. The other
4589       // elements come from the other positions of the first source vector.
4590       unsigned OpNum = (Index == 0) ? 1 : 0;
4591       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4592                                  Depth+1);
4593     }
4594     case X86ISD::VPERMILPS:
4595       ImmN = N->getOperand(N->getNumOperands()-1);
4596       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4597                         ShuffleMask);
4598       break;
4599     case X86ISD::VPERMILPSY:
4600       ImmN = N->getOperand(N->getNumOperands()-1);
4601       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4602                         ShuffleMask);
4603       break;
4604     case X86ISD::VPERMILPD:
4605       ImmN = N->getOperand(N->getNumOperands()-1);
4606       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4607                         ShuffleMask);
4608       break;
4609     case X86ISD::VPERMILPDY:
4610       ImmN = N->getOperand(N->getNumOperands()-1);
4611       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4612                         ShuffleMask);
4613       break;
4614     case X86ISD::VPERM2F128:
4615       ImmN = N->getOperand(N->getNumOperands()-1);
4616       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4617                            ShuffleMask);
4618       break;
4619     case X86ISD::MOVDDUP:
4620     case X86ISD::MOVLHPD:
4621     case X86ISD::MOVLPD:
4622     case X86ISD::MOVLPS:
4623     case X86ISD::MOVSHDUP:
4624     case X86ISD::MOVSLDUP:
4625     case X86ISD::PALIGN:
4626       return SDValue(); // Not yet implemented.
4627     default:
4628       assert(0 && "unknown target shuffle node");
4629       return SDValue();
4630     }
4631
4632     Index = ShuffleMask[Index];
4633     if (Index < 0)
4634       return DAG.getUNDEF(VT.getVectorElementType());
4635
4636     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4637     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4638                                Depth+1);
4639   }
4640
4641   // Actual nodes that may contain scalar elements
4642   if (Opcode == ISD::BITCAST) {
4643     V = V.getOperand(0);
4644     EVT SrcVT = V.getValueType();
4645     unsigned NumElems = VT.getVectorNumElements();
4646
4647     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4648       return SDValue();
4649   }
4650
4651   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4652     return (Index == 0) ? V.getOperand(0)
4653                           : DAG.getUNDEF(VT.getVectorElementType());
4654
4655   if (V.getOpcode() == ISD::BUILD_VECTOR)
4656     return V.getOperand(Index);
4657
4658   return SDValue();
4659 }
4660
4661 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4662 /// shuffle operation which come from a consecutively from a zero. The
4663 /// search can start in two different directions, from left or right.
4664 static
4665 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4666                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4667   int i = 0;
4668
4669   while (i < NumElems) {
4670     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4671     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4672     if (!(Elt.getNode() &&
4673          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4674       break;
4675     ++i;
4676   }
4677
4678   return i;
4679 }
4680
4681 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4682 /// MaskE correspond consecutively to elements from one of the vector operands,
4683 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4684 static
4685 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4686                               int OpIdx, int NumElems, unsigned &OpNum) {
4687   bool SeenV1 = false;
4688   bool SeenV2 = false;
4689
4690   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4691     int Idx = SVOp->getMaskElt(i);
4692     // Ignore undef indicies
4693     if (Idx < 0)
4694       continue;
4695
4696     if (Idx < NumElems)
4697       SeenV1 = true;
4698     else
4699       SeenV2 = true;
4700
4701     // Only accept consecutive elements from the same vector
4702     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4703       return false;
4704   }
4705
4706   OpNum = SeenV1 ? 0 : 1;
4707   return true;
4708 }
4709
4710 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4711 /// logical left shift of a vector.
4712 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4713                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4714   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4715   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4716               false /* check zeros from right */, DAG);
4717   unsigned OpSrc;
4718
4719   if (!NumZeros)
4720     return false;
4721
4722   // Considering the elements in the mask that are not consecutive zeros,
4723   // check if they consecutively come from only one of the source vectors.
4724   //
4725   //               V1 = {X, A, B, C}     0
4726   //                         \  \  \    /
4727   //   vector_shuffle V1, V2 <1, 2, 3, X>
4728   //
4729   if (!isShuffleMaskConsecutive(SVOp,
4730             0,                   // Mask Start Index
4731             NumElems-NumZeros-1, // Mask End Index
4732             NumZeros,            // Where to start looking in the src vector
4733             NumElems,            // Number of elements in vector
4734             OpSrc))              // Which source operand ?
4735     return false;
4736
4737   isLeft = false;
4738   ShAmt = NumZeros;
4739   ShVal = SVOp->getOperand(OpSrc);
4740   return true;
4741 }
4742
4743 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4744 /// logical left shift of a vector.
4745 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4746                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4747   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4748   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4749               true /* check zeros from left */, DAG);
4750   unsigned OpSrc;
4751
4752   if (!NumZeros)
4753     return false;
4754
4755   // Considering the elements in the mask that are not consecutive zeros,
4756   // check if they consecutively come from only one of the source vectors.
4757   //
4758   //                           0    { A, B, X, X } = V2
4759   //                          / \    /  /
4760   //   vector_shuffle V1, V2 <X, X, 4, 5>
4761   //
4762   if (!isShuffleMaskConsecutive(SVOp,
4763             NumZeros,     // Mask Start Index
4764             NumElems-1,   // Mask End Index
4765             0,            // Where to start looking in the src vector
4766             NumElems,     // Number of elements in vector
4767             OpSrc))       // Which source operand ?
4768     return false;
4769
4770   isLeft = true;
4771   ShAmt = NumZeros;
4772   ShVal = SVOp->getOperand(OpSrc);
4773   return true;
4774 }
4775
4776 /// isVectorShift - Returns true if the shuffle can be implemented as a
4777 /// logical left or right shift of a vector.
4778 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4779                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4780   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4781       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4782     return true;
4783
4784   return false;
4785 }
4786
4787 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4788 ///
4789 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4790                                        unsigned NumNonZero, unsigned NumZero,
4791                                        SelectionDAG &DAG,
4792                                        const TargetLowering &TLI) {
4793   if (NumNonZero > 8)
4794     return SDValue();
4795
4796   DebugLoc dl = Op.getDebugLoc();
4797   SDValue V(0, 0);
4798   bool First = true;
4799   for (unsigned i = 0; i < 16; ++i) {
4800     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4801     if (ThisIsNonZero && First) {
4802       if (NumZero)
4803         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4804       else
4805         V = DAG.getUNDEF(MVT::v8i16);
4806       First = false;
4807     }
4808
4809     if ((i & 1) != 0) {
4810       SDValue ThisElt(0, 0), LastElt(0, 0);
4811       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4812       if (LastIsNonZero) {
4813         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4814                               MVT::i16, Op.getOperand(i-1));
4815       }
4816       if (ThisIsNonZero) {
4817         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4818         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4819                               ThisElt, DAG.getConstant(8, MVT::i8));
4820         if (LastIsNonZero)
4821           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4822       } else
4823         ThisElt = LastElt;
4824
4825       if (ThisElt.getNode())
4826         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4827                         DAG.getIntPtrConstant(i/2));
4828     }
4829   }
4830
4831   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4832 }
4833
4834 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4835 ///
4836 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4837                                      unsigned NumNonZero, unsigned NumZero,
4838                                      SelectionDAG &DAG,
4839                                      const TargetLowering &TLI) {
4840   if (NumNonZero > 4)
4841     return SDValue();
4842
4843   DebugLoc dl = Op.getDebugLoc();
4844   SDValue V(0, 0);
4845   bool First = true;
4846   for (unsigned i = 0; i < 8; ++i) {
4847     bool isNonZero = (NonZeros & (1 << i)) != 0;
4848     if (isNonZero) {
4849       if (First) {
4850         if (NumZero)
4851           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4852         else
4853           V = DAG.getUNDEF(MVT::v8i16);
4854         First = false;
4855       }
4856       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4857                       MVT::v8i16, V, Op.getOperand(i),
4858                       DAG.getIntPtrConstant(i));
4859     }
4860   }
4861
4862   return V;
4863 }
4864
4865 /// getVShift - Return a vector logical shift node.
4866 ///
4867 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4868                          unsigned NumBits, SelectionDAG &DAG,
4869                          const TargetLowering &TLI, DebugLoc dl) {
4870   EVT ShVT = MVT::v2i64;
4871   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4872   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4873   return DAG.getNode(ISD::BITCAST, dl, VT,
4874                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4875                              DAG.getConstant(NumBits,
4876                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4877 }
4878
4879 SDValue
4880 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4881                                           SelectionDAG &DAG) const {
4882
4883   // Check if the scalar load can be widened into a vector load. And if
4884   // the address is "base + cst" see if the cst can be "absorbed" into
4885   // the shuffle mask.
4886   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4887     SDValue Ptr = LD->getBasePtr();
4888     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4889       return SDValue();
4890     EVT PVT = LD->getValueType(0);
4891     if (PVT != MVT::i32 && PVT != MVT::f32)
4892       return SDValue();
4893
4894     int FI = -1;
4895     int64_t Offset = 0;
4896     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4897       FI = FINode->getIndex();
4898       Offset = 0;
4899     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4900                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4901       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4902       Offset = Ptr.getConstantOperandVal(1);
4903       Ptr = Ptr.getOperand(0);
4904     } else {
4905       return SDValue();
4906     }
4907
4908     // FIXME: 256-bit vector instructions don't require a strict alignment,
4909     // improve this code to support it better.
4910     unsigned RequiredAlign = VT.getSizeInBits()/8;
4911     SDValue Chain = LD->getChain();
4912     // Make sure the stack object alignment is at least 16 or 32.
4913     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4914     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4915       if (MFI->isFixedObjectIndex(FI)) {
4916         // Can't change the alignment. FIXME: It's possible to compute
4917         // the exact stack offset and reference FI + adjust offset instead.
4918         // If someone *really* cares about this. That's the way to implement it.
4919         return SDValue();
4920       } else {
4921         MFI->setObjectAlignment(FI, RequiredAlign);
4922       }
4923     }
4924
4925     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4926     // Ptr + (Offset & ~15).
4927     if (Offset < 0)
4928       return SDValue();
4929     if ((Offset % RequiredAlign) & 3)
4930       return SDValue();
4931     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4932     if (StartOffset)
4933       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4934                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4935
4936     int EltNo = (Offset - StartOffset) >> 2;
4937     int NumElems = VT.getVectorNumElements();
4938
4939     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4940     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4941     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4942                              LD->getPointerInfo().getWithOffset(StartOffset),
4943                              false, false, 0);
4944
4945     // Canonicalize it to a v4i32 or v8i32 shuffle.
4946     SmallVector<int, 8> Mask;
4947     for (int i = 0; i < NumElems; ++i)
4948       Mask.push_back(EltNo);
4949
4950     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4951     return DAG.getNode(ISD::BITCAST, dl, NVT,
4952                        DAG.getVectorShuffle(CanonVT, dl, V1,
4953                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4954   }
4955
4956   return SDValue();
4957 }
4958
4959 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4960 /// vector of type 'VT', see if the elements can be replaced by a single large
4961 /// load which has the same value as a build_vector whose operands are 'elts'.
4962 ///
4963 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4964 ///
4965 /// FIXME: we'd also like to handle the case where the last elements are zero
4966 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4967 /// There's even a handy isZeroNode for that purpose.
4968 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4969                                         DebugLoc &DL, SelectionDAG &DAG) {
4970   EVT EltVT = VT.getVectorElementType();
4971   unsigned NumElems = Elts.size();
4972
4973   LoadSDNode *LDBase = NULL;
4974   unsigned LastLoadedElt = -1U;
4975
4976   // For each element in the initializer, see if we've found a load or an undef.
4977   // If we don't find an initial load element, or later load elements are
4978   // non-consecutive, bail out.
4979   for (unsigned i = 0; i < NumElems; ++i) {
4980     SDValue Elt = Elts[i];
4981
4982     if (!Elt.getNode() ||
4983         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4984       return SDValue();
4985     if (!LDBase) {
4986       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4987         return SDValue();
4988       LDBase = cast<LoadSDNode>(Elt.getNode());
4989       LastLoadedElt = i;
4990       continue;
4991     }
4992     if (Elt.getOpcode() == ISD::UNDEF)
4993       continue;
4994
4995     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4996     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4997       return SDValue();
4998     LastLoadedElt = i;
4999   }
5000
5001   // If we have found an entire vector of loads and undefs, then return a large
5002   // load of the entire vector width starting at the base pointer.  If we found
5003   // consecutive loads for the low half, generate a vzext_load node.
5004   if (LastLoadedElt == NumElems - 1) {
5005     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5006       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5007                          LDBase->getPointerInfo(),
5008                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5009     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5010                        LDBase->getPointerInfo(),
5011                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5012                        LDBase->getAlignment());
5013   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5014              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5015     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5016     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5017     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
5018                                               Ops, 2, MVT::i32,
5019                                               LDBase->getMemOperand());
5020     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5021   }
5022   return SDValue();
5023 }
5024
5025 SDValue
5026 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5027   DebugLoc dl = Op.getDebugLoc();
5028
5029   EVT VT = Op.getValueType();
5030   EVT ExtVT = VT.getVectorElementType();
5031   unsigned NumElems = Op.getNumOperands();
5032
5033   // Vectors containing all zeros can be matched by pxor and xorps later
5034   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5035     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5036     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5037     if (Op.getValueType() == MVT::v4i32 ||
5038         Op.getValueType() == MVT::v8i32)
5039       return Op;
5040
5041     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
5042   }
5043
5044   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5045   // vectors or broken into v4i32 operations on 256-bit vectors.
5046   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5047     if (Op.getValueType() == MVT::v4i32)
5048       return Op;
5049
5050     return getOnesVector(Op.getValueType(), DAG, dl);
5051   }
5052
5053   unsigned EVTBits = ExtVT.getSizeInBits();
5054
5055   unsigned NumZero  = 0;
5056   unsigned NumNonZero = 0;
5057   unsigned NonZeros = 0;
5058   bool IsAllConstants = true;
5059   SmallSet<SDValue, 8> Values;
5060   for (unsigned i = 0; i < NumElems; ++i) {
5061     SDValue Elt = Op.getOperand(i);
5062     if (Elt.getOpcode() == ISD::UNDEF)
5063       continue;
5064     Values.insert(Elt);
5065     if (Elt.getOpcode() != ISD::Constant &&
5066         Elt.getOpcode() != ISD::ConstantFP)
5067       IsAllConstants = false;
5068     if (X86::isZeroNode(Elt))
5069       NumZero++;
5070     else {
5071       NonZeros |= (1 << i);
5072       NumNonZero++;
5073     }
5074   }
5075
5076   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5077   if (NumNonZero == 0)
5078     return DAG.getUNDEF(VT);
5079
5080   // Special case for single non-zero, non-undef, element.
5081   if (NumNonZero == 1) {
5082     unsigned Idx = CountTrailingZeros_32(NonZeros);
5083     SDValue Item = Op.getOperand(Idx);
5084
5085     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5086     // the value are obviously zero, truncate the value to i32 and do the
5087     // insertion that way.  Only do this if the value is non-constant or if the
5088     // value is a constant being inserted into element 0.  It is cheaper to do
5089     // a constant pool load than it is to do a movd + shuffle.
5090     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5091         (!IsAllConstants || Idx == 0)) {
5092       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5093         // Handle SSE only.
5094         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5095         EVT VecVT = MVT::v4i32;
5096         unsigned VecElts = 4;
5097
5098         // Truncate the value (which may itself be a constant) to i32, and
5099         // convert it to a vector with movd (S2V+shuffle to zero extend).
5100         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5101         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5102         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5103                                            Subtarget->hasSSE2(), DAG);
5104
5105         // Now we have our 32-bit value zero extended in the low element of
5106         // a vector.  If Idx != 0, swizzle it into place.
5107         if (Idx != 0) {
5108           SmallVector<int, 4> Mask;
5109           Mask.push_back(Idx);
5110           for (unsigned i = 1; i != VecElts; ++i)
5111             Mask.push_back(i);
5112           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5113                                       DAG.getUNDEF(Item.getValueType()),
5114                                       &Mask[0]);
5115         }
5116         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5117       }
5118     }
5119
5120     // If we have a constant or non-constant insertion into the low element of
5121     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5122     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5123     // depending on what the source datatype is.
5124     if (Idx == 0) {
5125       if (NumZero == 0) {
5126         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5127       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5128           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5129         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5130         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5131         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
5132                                            DAG);
5133       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5134         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5135         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5136         EVT MiddleVT = MVT::v4i32;
5137         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5138         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5139                                            Subtarget->hasSSE2(), DAG);
5140         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5141       }
5142     }
5143
5144     // Is it a vector logical left shift?
5145     if (NumElems == 2 && Idx == 1 &&
5146         X86::isZeroNode(Op.getOperand(0)) &&
5147         !X86::isZeroNode(Op.getOperand(1))) {
5148       unsigned NumBits = VT.getSizeInBits();
5149       return getVShift(true, VT,
5150                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5151                                    VT, Op.getOperand(1)),
5152                        NumBits/2, DAG, *this, dl);
5153     }
5154
5155     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5156       return SDValue();
5157
5158     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5159     // is a non-constant being inserted into an element other than the low one,
5160     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5161     // movd/movss) to move this into the low element, then shuffle it into
5162     // place.
5163     if (EVTBits == 32) {
5164       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5165
5166       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5167       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5168                                          Subtarget->hasSSE2(), DAG);
5169       SmallVector<int, 8> MaskVec;
5170       for (unsigned i = 0; i < NumElems; i++)
5171         MaskVec.push_back(i == Idx ? 0 : 1);
5172       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5173     }
5174   }
5175
5176   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5177   if (Values.size() == 1) {
5178     if (EVTBits == 32) {
5179       // Instead of a shuffle like this:
5180       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5181       // Check if it's possible to issue this instead.
5182       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5183       unsigned Idx = CountTrailingZeros_32(NonZeros);
5184       SDValue Item = Op.getOperand(Idx);
5185       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5186         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5187     }
5188     return SDValue();
5189   }
5190
5191   // A vector full of immediates; various special cases are already
5192   // handled, so this is best done with a single constant-pool load.
5193   if (IsAllConstants)
5194     return SDValue();
5195
5196   // For AVX-length vectors, build the individual 128-bit pieces and use
5197   // shuffles to put them in place.
5198   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5199     SmallVector<SDValue, 32> V;
5200     for (unsigned i = 0; i < NumElems; ++i)
5201       V.push_back(Op.getOperand(i));
5202
5203     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5204
5205     // Build both the lower and upper subvector.
5206     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5207     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5208                                 NumElems/2);
5209
5210     // Recreate the wider vector with the lower and upper part.
5211     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5212                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5213     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5214                               DAG, dl);
5215   }
5216
5217   // Let legalizer expand 2-wide build_vectors.
5218   if (EVTBits == 64) {
5219     if (NumNonZero == 1) {
5220       // One half is zero or undef.
5221       unsigned Idx = CountTrailingZeros_32(NonZeros);
5222       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5223                                  Op.getOperand(Idx));
5224       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5225                                          Subtarget->hasSSE2(), DAG);
5226     }
5227     return SDValue();
5228   }
5229
5230   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5231   if (EVTBits == 8 && NumElems == 16) {
5232     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5233                                         *this);
5234     if (V.getNode()) return V;
5235   }
5236
5237   if (EVTBits == 16 && NumElems == 8) {
5238     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5239                                       *this);
5240     if (V.getNode()) return V;
5241   }
5242
5243   // If element VT is == 32 bits, turn it into a number of shuffles.
5244   SmallVector<SDValue, 8> V;
5245   V.resize(NumElems);
5246   if (NumElems == 4 && NumZero > 0) {
5247     for (unsigned i = 0; i < 4; ++i) {
5248       bool isZero = !(NonZeros & (1 << i));
5249       if (isZero)
5250         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5251       else
5252         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5253     }
5254
5255     for (unsigned i = 0; i < 2; ++i) {
5256       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5257         default: break;
5258         case 0:
5259           V[i] = V[i*2];  // Must be a zero vector.
5260           break;
5261         case 1:
5262           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5263           break;
5264         case 2:
5265           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5266           break;
5267         case 3:
5268           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5269           break;
5270       }
5271     }
5272
5273     SmallVector<int, 8> MaskVec;
5274     bool Reverse = (NonZeros & 0x3) == 2;
5275     for (unsigned i = 0; i < 2; ++i)
5276       MaskVec.push_back(Reverse ? 1-i : i);
5277     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5278     for (unsigned i = 0; i < 2; ++i)
5279       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5280     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5281   }
5282
5283   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5284     // Check for a build vector of consecutive loads.
5285     for (unsigned i = 0; i < NumElems; ++i)
5286       V[i] = Op.getOperand(i);
5287
5288     // Check for elements which are consecutive loads.
5289     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5290     if (LD.getNode())
5291       return LD;
5292
5293     // For SSE 4.1, use insertps to put the high elements into the low element.
5294     if (getSubtarget()->hasSSE41()) {
5295       SDValue Result;
5296       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5297         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5298       else
5299         Result = DAG.getUNDEF(VT);
5300
5301       for (unsigned i = 1; i < NumElems; ++i) {
5302         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5303         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5304                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5305       }
5306       return Result;
5307     }
5308
5309     // Otherwise, expand into a number of unpckl*, start by extending each of
5310     // our (non-undef) elements to the full vector width with the element in the
5311     // bottom slot of the vector (which generates no code for SSE).
5312     for (unsigned i = 0; i < NumElems; ++i) {
5313       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5314         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5315       else
5316         V[i] = DAG.getUNDEF(VT);
5317     }
5318
5319     // Next, we iteratively mix elements, e.g. for v4f32:
5320     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5321     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5322     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5323     unsigned EltStride = NumElems >> 1;
5324     while (EltStride != 0) {
5325       for (unsigned i = 0; i < EltStride; ++i) {
5326         // If V[i+EltStride] is undef and this is the first round of mixing,
5327         // then it is safe to just drop this shuffle: V[i] is already in the
5328         // right place, the one element (since it's the first round) being
5329         // inserted as undef can be dropped.  This isn't safe for successive
5330         // rounds because they will permute elements within both vectors.
5331         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5332             EltStride == NumElems/2)
5333           continue;
5334
5335         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5336       }
5337       EltStride >>= 1;
5338     }
5339     return V[0];
5340   }
5341   return SDValue();
5342 }
5343
5344 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5345 // them in a MMX register.  This is better than doing a stack convert.
5346 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5347   DebugLoc dl = Op.getDebugLoc();
5348   EVT ResVT = Op.getValueType();
5349
5350   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5351          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5352   int Mask[2];
5353   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5354   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5355   InVec = Op.getOperand(1);
5356   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5357     unsigned NumElts = ResVT.getVectorNumElements();
5358     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5359     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5360                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5361   } else {
5362     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5363     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5364     Mask[0] = 0; Mask[1] = 2;
5365     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5366   }
5367   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5368 }
5369
5370 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5371 // to create 256-bit vectors from two other 128-bit ones.
5372 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5373   DebugLoc dl = Op.getDebugLoc();
5374   EVT ResVT = Op.getValueType();
5375
5376   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5377
5378   SDValue V1 = Op.getOperand(0);
5379   SDValue V2 = Op.getOperand(1);
5380   unsigned NumElems = ResVT.getVectorNumElements();
5381
5382   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5383                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5384   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5385                             DAG, dl);
5386 }
5387
5388 SDValue
5389 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5390   EVT ResVT = Op.getValueType();
5391
5392   assert(Op.getNumOperands() == 2);
5393   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5394          "Unsupported CONCAT_VECTORS for value type");
5395
5396   // We support concatenate two MMX registers and place them in a MMX register.
5397   // This is better than doing a stack convert.
5398   if (ResVT.is128BitVector())
5399     return LowerMMXCONCAT_VECTORS(Op, DAG);
5400
5401   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5402   // from two other 128-bit ones.
5403   return LowerAVXCONCAT_VECTORS(Op, DAG);
5404 }
5405
5406 // v8i16 shuffles - Prefer shuffles in the following order:
5407 // 1. [all]   pshuflw, pshufhw, optional move
5408 // 2. [ssse3] 1 x pshufb
5409 // 3. [ssse3] 2 x pshufb + 1 x por
5410 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5411 SDValue
5412 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5413                                             SelectionDAG &DAG) const {
5414   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5415   SDValue V1 = SVOp->getOperand(0);
5416   SDValue V2 = SVOp->getOperand(1);
5417   DebugLoc dl = SVOp->getDebugLoc();
5418   SmallVector<int, 8> MaskVals;
5419
5420   // Determine if more than 1 of the words in each of the low and high quadwords
5421   // of the result come from the same quadword of one of the two inputs.  Undef
5422   // mask values count as coming from any quadword, for better codegen.
5423   SmallVector<unsigned, 4> LoQuad(4);
5424   SmallVector<unsigned, 4> HiQuad(4);
5425   BitVector InputQuads(4);
5426   for (unsigned i = 0; i < 8; ++i) {
5427     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5428     int EltIdx = SVOp->getMaskElt(i);
5429     MaskVals.push_back(EltIdx);
5430     if (EltIdx < 0) {
5431       ++Quad[0];
5432       ++Quad[1];
5433       ++Quad[2];
5434       ++Quad[3];
5435       continue;
5436     }
5437     ++Quad[EltIdx / 4];
5438     InputQuads.set(EltIdx / 4);
5439   }
5440
5441   int BestLoQuad = -1;
5442   unsigned MaxQuad = 1;
5443   for (unsigned i = 0; i < 4; ++i) {
5444     if (LoQuad[i] > MaxQuad) {
5445       BestLoQuad = i;
5446       MaxQuad = LoQuad[i];
5447     }
5448   }
5449
5450   int BestHiQuad = -1;
5451   MaxQuad = 1;
5452   for (unsigned i = 0; i < 4; ++i) {
5453     if (HiQuad[i] > MaxQuad) {
5454       BestHiQuad = i;
5455       MaxQuad = HiQuad[i];
5456     }
5457   }
5458
5459   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5460   // of the two input vectors, shuffle them into one input vector so only a
5461   // single pshufb instruction is necessary. If There are more than 2 input
5462   // quads, disable the next transformation since it does not help SSSE3.
5463   bool V1Used = InputQuads[0] || InputQuads[1];
5464   bool V2Used = InputQuads[2] || InputQuads[3];
5465   if (Subtarget->hasSSSE3()) {
5466     if (InputQuads.count() == 2 && V1Used && V2Used) {
5467       BestLoQuad = InputQuads.find_first();
5468       BestHiQuad = InputQuads.find_next(BestLoQuad);
5469     }
5470     if (InputQuads.count() > 2) {
5471       BestLoQuad = -1;
5472       BestHiQuad = -1;
5473     }
5474   }
5475
5476   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5477   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5478   // words from all 4 input quadwords.
5479   SDValue NewV;
5480   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5481     SmallVector<int, 8> MaskV;
5482     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5483     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5484     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5485                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5486                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5487     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5488
5489     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5490     // source words for the shuffle, to aid later transformations.
5491     bool AllWordsInNewV = true;
5492     bool InOrder[2] = { true, true };
5493     for (unsigned i = 0; i != 8; ++i) {
5494       int idx = MaskVals[i];
5495       if (idx != (int)i)
5496         InOrder[i/4] = false;
5497       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5498         continue;
5499       AllWordsInNewV = false;
5500       break;
5501     }
5502
5503     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5504     if (AllWordsInNewV) {
5505       for (int i = 0; i != 8; ++i) {
5506         int idx = MaskVals[i];
5507         if (idx < 0)
5508           continue;
5509         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5510         if ((idx != i) && idx < 4)
5511           pshufhw = false;
5512         if ((idx != i) && idx > 3)
5513           pshuflw = false;
5514       }
5515       V1 = NewV;
5516       V2Used = false;
5517       BestLoQuad = 0;
5518       BestHiQuad = 1;
5519     }
5520
5521     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5522     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5523     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5524       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5525       unsigned TargetMask = 0;
5526       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5527                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5528       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5529                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5530       V1 = NewV.getOperand(0);
5531       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5532     }
5533   }
5534
5535   // If we have SSSE3, and all words of the result are from 1 input vector,
5536   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5537   // is present, fall back to case 4.
5538   if (Subtarget->hasSSSE3()) {
5539     SmallVector<SDValue,16> pshufbMask;
5540
5541     // If we have elements from both input vectors, set the high bit of the
5542     // shuffle mask element to zero out elements that come from V2 in the V1
5543     // mask, and elements that come from V1 in the V2 mask, so that the two
5544     // results can be OR'd together.
5545     bool TwoInputs = V1Used && V2Used;
5546     for (unsigned i = 0; i != 8; ++i) {
5547       int EltIdx = MaskVals[i] * 2;
5548       if (TwoInputs && (EltIdx >= 16)) {
5549         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5550         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5551         continue;
5552       }
5553       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5554       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5555     }
5556     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5557     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5558                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5559                                  MVT::v16i8, &pshufbMask[0], 16));
5560     if (!TwoInputs)
5561       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5562
5563     // Calculate the shuffle mask for the second input, shuffle it, and
5564     // OR it with the first shuffled input.
5565     pshufbMask.clear();
5566     for (unsigned i = 0; i != 8; ++i) {
5567       int EltIdx = MaskVals[i] * 2;
5568       if (EltIdx < 16) {
5569         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5570         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5571         continue;
5572       }
5573       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5574       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5575     }
5576     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5577     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5578                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5579                                  MVT::v16i8, &pshufbMask[0], 16));
5580     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5581     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5582   }
5583
5584   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5585   // and update MaskVals with new element order.
5586   BitVector InOrder(8);
5587   if (BestLoQuad >= 0) {
5588     SmallVector<int, 8> MaskV;
5589     for (int i = 0; i != 4; ++i) {
5590       int idx = MaskVals[i];
5591       if (idx < 0) {
5592         MaskV.push_back(-1);
5593         InOrder.set(i);
5594       } else if ((idx / 4) == BestLoQuad) {
5595         MaskV.push_back(idx & 3);
5596         InOrder.set(i);
5597       } else {
5598         MaskV.push_back(-1);
5599       }
5600     }
5601     for (unsigned i = 4; i != 8; ++i)
5602       MaskV.push_back(i);
5603     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5604                                 &MaskV[0]);
5605
5606     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5607       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5608                                NewV.getOperand(0),
5609                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5610                                DAG);
5611   }
5612
5613   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5614   // and update MaskVals with the new element order.
5615   if (BestHiQuad >= 0) {
5616     SmallVector<int, 8> MaskV;
5617     for (unsigned i = 0; i != 4; ++i)
5618       MaskV.push_back(i);
5619     for (unsigned i = 4; i != 8; ++i) {
5620       int idx = MaskVals[i];
5621       if (idx < 0) {
5622         MaskV.push_back(-1);
5623         InOrder.set(i);
5624       } else if ((idx / 4) == BestHiQuad) {
5625         MaskV.push_back((idx & 3) + 4);
5626         InOrder.set(i);
5627       } else {
5628         MaskV.push_back(-1);
5629       }
5630     }
5631     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5632                                 &MaskV[0]);
5633
5634     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5635       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5636                               NewV.getOperand(0),
5637                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5638                               DAG);
5639   }
5640
5641   // In case BestHi & BestLo were both -1, which means each quadword has a word
5642   // from each of the four input quadwords, calculate the InOrder bitvector now
5643   // before falling through to the insert/extract cleanup.
5644   if (BestLoQuad == -1 && BestHiQuad == -1) {
5645     NewV = V1;
5646     for (int i = 0; i != 8; ++i)
5647       if (MaskVals[i] < 0 || MaskVals[i] == i)
5648         InOrder.set(i);
5649   }
5650
5651   // The other elements are put in the right place using pextrw and pinsrw.
5652   for (unsigned i = 0; i != 8; ++i) {
5653     if (InOrder[i])
5654       continue;
5655     int EltIdx = MaskVals[i];
5656     if (EltIdx < 0)
5657       continue;
5658     SDValue ExtOp = (EltIdx < 8)
5659     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5660                   DAG.getIntPtrConstant(EltIdx))
5661     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5662                   DAG.getIntPtrConstant(EltIdx - 8));
5663     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5664                        DAG.getIntPtrConstant(i));
5665   }
5666   return NewV;
5667 }
5668
5669 // v16i8 shuffles - Prefer shuffles in the following order:
5670 // 1. [ssse3] 1 x pshufb
5671 // 2. [ssse3] 2 x pshufb + 1 x por
5672 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5673 static
5674 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5675                                  SelectionDAG &DAG,
5676                                  const X86TargetLowering &TLI) {
5677   SDValue V1 = SVOp->getOperand(0);
5678   SDValue V2 = SVOp->getOperand(1);
5679   DebugLoc dl = SVOp->getDebugLoc();
5680   SmallVector<int, 16> MaskVals;
5681   SVOp->getMask(MaskVals);
5682
5683   // If we have SSSE3, case 1 is generated when all result bytes come from
5684   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5685   // present, fall back to case 3.
5686   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5687   bool V1Only = true;
5688   bool V2Only = true;
5689   for (unsigned i = 0; i < 16; ++i) {
5690     int EltIdx = MaskVals[i];
5691     if (EltIdx < 0)
5692       continue;
5693     if (EltIdx < 16)
5694       V2Only = false;
5695     else
5696       V1Only = false;
5697   }
5698
5699   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5700   if (TLI.getSubtarget()->hasSSSE3()) {
5701     SmallVector<SDValue,16> pshufbMask;
5702
5703     // If all result elements are from one input vector, then only translate
5704     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5705     //
5706     // Otherwise, we have elements from both input vectors, and must zero out
5707     // elements that come from V2 in the first mask, and V1 in the second mask
5708     // so that we can OR them together.
5709     bool TwoInputs = !(V1Only || V2Only);
5710     for (unsigned i = 0; i != 16; ++i) {
5711       int EltIdx = MaskVals[i];
5712       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5713         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5714         continue;
5715       }
5716       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5717     }
5718     // If all the elements are from V2, assign it to V1 and return after
5719     // building the first pshufb.
5720     if (V2Only)
5721       V1 = V2;
5722     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5723                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5724                                  MVT::v16i8, &pshufbMask[0], 16));
5725     if (!TwoInputs)
5726       return V1;
5727
5728     // Calculate the shuffle mask for the second input, shuffle it, and
5729     // OR it with the first shuffled input.
5730     pshufbMask.clear();
5731     for (unsigned i = 0; i != 16; ++i) {
5732       int EltIdx = MaskVals[i];
5733       if (EltIdx < 16) {
5734         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5735         continue;
5736       }
5737       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5738     }
5739     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5740                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5741                                  MVT::v16i8, &pshufbMask[0], 16));
5742     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5743   }
5744
5745   // No SSSE3 - Calculate in place words and then fix all out of place words
5746   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5747   // the 16 different words that comprise the two doublequadword input vectors.
5748   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5749   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5750   SDValue NewV = V2Only ? V2 : V1;
5751   for (int i = 0; i != 8; ++i) {
5752     int Elt0 = MaskVals[i*2];
5753     int Elt1 = MaskVals[i*2+1];
5754
5755     // This word of the result is all undef, skip it.
5756     if (Elt0 < 0 && Elt1 < 0)
5757       continue;
5758
5759     // This word of the result is already in the correct place, skip it.
5760     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5761       continue;
5762     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5763       continue;
5764
5765     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5766     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5767     SDValue InsElt;
5768
5769     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5770     // using a single extract together, load it and store it.
5771     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5772       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5773                            DAG.getIntPtrConstant(Elt1 / 2));
5774       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5775                         DAG.getIntPtrConstant(i));
5776       continue;
5777     }
5778
5779     // If Elt1 is defined, extract it from the appropriate source.  If the
5780     // source byte is not also odd, shift the extracted word left 8 bits
5781     // otherwise clear the bottom 8 bits if we need to do an or.
5782     if (Elt1 >= 0) {
5783       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5784                            DAG.getIntPtrConstant(Elt1 / 2));
5785       if ((Elt1 & 1) == 0)
5786         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5787                              DAG.getConstant(8,
5788                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5789       else if (Elt0 >= 0)
5790         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5791                              DAG.getConstant(0xFF00, MVT::i16));
5792     }
5793     // If Elt0 is defined, extract it from the appropriate source.  If the
5794     // source byte is not also even, shift the extracted word right 8 bits. If
5795     // Elt1 was also defined, OR the extracted values together before
5796     // inserting them in the result.
5797     if (Elt0 >= 0) {
5798       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5799                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5800       if ((Elt0 & 1) != 0)
5801         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5802                               DAG.getConstant(8,
5803                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5804       else if (Elt1 >= 0)
5805         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5806                              DAG.getConstant(0x00FF, MVT::i16));
5807       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5808                          : InsElt0;
5809     }
5810     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5811                        DAG.getIntPtrConstant(i));
5812   }
5813   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5814 }
5815
5816 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5817 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5818 /// done when every pair / quad of shuffle mask elements point to elements in
5819 /// the right sequence. e.g.
5820 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5821 static
5822 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5823                                  SelectionDAG &DAG, DebugLoc dl) {
5824   EVT VT = SVOp->getValueType(0);
5825   SDValue V1 = SVOp->getOperand(0);
5826   SDValue V2 = SVOp->getOperand(1);
5827   unsigned NumElems = VT.getVectorNumElements();
5828   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5829   EVT NewVT;
5830   switch (VT.getSimpleVT().SimpleTy) {
5831   default: assert(false && "Unexpected!");
5832   case MVT::v4f32: NewVT = MVT::v2f64; break;
5833   case MVT::v4i32: NewVT = MVT::v2i64; break;
5834   case MVT::v8i16: NewVT = MVT::v4i32; break;
5835   case MVT::v16i8: NewVT = MVT::v4i32; break;
5836   }
5837
5838   int Scale = NumElems / NewWidth;
5839   SmallVector<int, 8> MaskVec;
5840   for (unsigned i = 0; i < NumElems; i += Scale) {
5841     int StartIdx = -1;
5842     for (int j = 0; j < Scale; ++j) {
5843       int EltIdx = SVOp->getMaskElt(i+j);
5844       if (EltIdx < 0)
5845         continue;
5846       if (StartIdx == -1)
5847         StartIdx = EltIdx - (EltIdx % Scale);
5848       if (EltIdx != StartIdx + j)
5849         return SDValue();
5850     }
5851     if (StartIdx == -1)
5852       MaskVec.push_back(-1);
5853     else
5854       MaskVec.push_back(StartIdx / Scale);
5855   }
5856
5857   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5858   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5859   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5860 }
5861
5862 /// getVZextMovL - Return a zero-extending vector move low node.
5863 ///
5864 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5865                             SDValue SrcOp, SelectionDAG &DAG,
5866                             const X86Subtarget *Subtarget, DebugLoc dl) {
5867   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5868     LoadSDNode *LD = NULL;
5869     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5870       LD = dyn_cast<LoadSDNode>(SrcOp);
5871     if (!LD) {
5872       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5873       // instead.
5874       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5875       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5876           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5877           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5878           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5879         // PR2108
5880         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5881         return DAG.getNode(ISD::BITCAST, dl, VT,
5882                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5883                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5884                                                    OpVT,
5885                                                    SrcOp.getOperand(0)
5886                                                           .getOperand(0))));
5887       }
5888     }
5889   }
5890
5891   return DAG.getNode(ISD::BITCAST, dl, VT,
5892                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5893                                  DAG.getNode(ISD::BITCAST, dl,
5894                                              OpVT, SrcOp)));
5895 }
5896
5897 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5898 /// shuffle node referes to only one lane in the sources.
5899 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5900   EVT VT = SVOp->getValueType(0);
5901   int NumElems = VT.getVectorNumElements();
5902   int HalfSize = NumElems/2;
5903   SmallVector<int, 16> M;
5904   SVOp->getMask(M);
5905   bool MatchA = false, MatchB = false;
5906
5907   for (int l = 0; l < NumElems*2; l += HalfSize) {
5908     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5909       MatchA = true;
5910       break;
5911     }
5912   }
5913
5914   for (int l = 0; l < NumElems*2; l += HalfSize) {
5915     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5916       MatchB = true;
5917       break;
5918     }
5919   }
5920
5921   return MatchA && MatchB;
5922 }
5923
5924 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5925 /// which could not be matched by any known target speficic shuffle
5926 static SDValue
5927 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5928   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5929     // If each half of a vector shuffle node referes to only one lane in the
5930     // source vectors, extract each used 128-bit lane and shuffle them using
5931     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5932     // the work to the legalizer.
5933     DebugLoc dl = SVOp->getDebugLoc();
5934     EVT VT = SVOp->getValueType(0);
5935     int NumElems = VT.getVectorNumElements();
5936     int HalfSize = NumElems/2;
5937
5938     // Extract the reference for each half
5939     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5940     int FstVecOpNum = 0, SndVecOpNum = 0;
5941     for (int i = 0; i < HalfSize; ++i) {
5942       int Elt = SVOp->getMaskElt(i);
5943       if (SVOp->getMaskElt(i) < 0)
5944         continue;
5945       FstVecOpNum = Elt/NumElems;
5946       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5947       break;
5948     }
5949     for (int i = HalfSize; i < NumElems; ++i) {
5950       int Elt = SVOp->getMaskElt(i);
5951       if (SVOp->getMaskElt(i) < 0)
5952         continue;
5953       SndVecOpNum = Elt/NumElems;
5954       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5955       break;
5956     }
5957
5958     // Extract the subvectors
5959     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5960                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5961     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5962                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5963
5964     // Generate 128-bit shuffles
5965     SmallVector<int, 16> MaskV1, MaskV2;
5966     for (int i = 0; i < HalfSize; ++i) {
5967       int Elt = SVOp->getMaskElt(i);
5968       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5969     }
5970     for (int i = HalfSize; i < NumElems; ++i) {
5971       int Elt = SVOp->getMaskElt(i);
5972       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5973     }
5974
5975     EVT NVT = V1.getValueType();
5976     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5977     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5978
5979     // Concatenate the result back
5980     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5981                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5982     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5983                               DAG, dl);
5984   }
5985
5986   return SDValue();
5987 }
5988
5989 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5990 /// 4 elements, and match them with several different shuffle types.
5991 static SDValue
5992 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5993   SDValue V1 = SVOp->getOperand(0);
5994   SDValue V2 = SVOp->getOperand(1);
5995   DebugLoc dl = SVOp->getDebugLoc();
5996   EVT VT = SVOp->getValueType(0);
5997
5998   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5999
6000   SmallVector<std::pair<int, int>, 8> Locs;
6001   Locs.resize(4);
6002   SmallVector<int, 8> Mask1(4U, -1);
6003   SmallVector<int, 8> PermMask;
6004   SVOp->getMask(PermMask);
6005
6006   unsigned NumHi = 0;
6007   unsigned NumLo = 0;
6008   for (unsigned i = 0; i != 4; ++i) {
6009     int Idx = PermMask[i];
6010     if (Idx < 0) {
6011       Locs[i] = std::make_pair(-1, -1);
6012     } else {
6013       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6014       if (Idx < 4) {
6015         Locs[i] = std::make_pair(0, NumLo);
6016         Mask1[NumLo] = Idx;
6017         NumLo++;
6018       } else {
6019         Locs[i] = std::make_pair(1, NumHi);
6020         if (2+NumHi < 4)
6021           Mask1[2+NumHi] = Idx;
6022         NumHi++;
6023       }
6024     }
6025   }
6026
6027   if (NumLo <= 2 && NumHi <= 2) {
6028     // If no more than two elements come from either vector. This can be
6029     // implemented with two shuffles. First shuffle gather the elements.
6030     // The second shuffle, which takes the first shuffle as both of its
6031     // vector operands, put the elements into the right order.
6032     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6033
6034     SmallVector<int, 8> Mask2(4U, -1);
6035
6036     for (unsigned i = 0; i != 4; ++i) {
6037       if (Locs[i].first == -1)
6038         continue;
6039       else {
6040         unsigned Idx = (i < 2) ? 0 : 4;
6041         Idx += Locs[i].first * 2 + Locs[i].second;
6042         Mask2[i] = Idx;
6043       }
6044     }
6045
6046     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6047   } else if (NumLo == 3 || NumHi == 3) {
6048     // Otherwise, we must have three elements from one vector, call it X, and
6049     // one element from the other, call it Y.  First, use a shufps to build an
6050     // intermediate vector with the one element from Y and the element from X
6051     // that will be in the same half in the final destination (the indexes don't
6052     // matter). Then, use a shufps to build the final vector, taking the half
6053     // containing the element from Y from the intermediate, and the other half
6054     // from X.
6055     if (NumHi == 3) {
6056       // Normalize it so the 3 elements come from V1.
6057       CommuteVectorShuffleMask(PermMask, VT);
6058       std::swap(V1, V2);
6059     }
6060
6061     // Find the element from V2.
6062     unsigned HiIndex;
6063     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6064       int Val = PermMask[HiIndex];
6065       if (Val < 0)
6066         continue;
6067       if (Val >= 4)
6068         break;
6069     }
6070
6071     Mask1[0] = PermMask[HiIndex];
6072     Mask1[1] = -1;
6073     Mask1[2] = PermMask[HiIndex^1];
6074     Mask1[3] = -1;
6075     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6076
6077     if (HiIndex >= 2) {
6078       Mask1[0] = PermMask[0];
6079       Mask1[1] = PermMask[1];
6080       Mask1[2] = HiIndex & 1 ? 6 : 4;
6081       Mask1[3] = HiIndex & 1 ? 4 : 6;
6082       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6083     } else {
6084       Mask1[0] = HiIndex & 1 ? 2 : 0;
6085       Mask1[1] = HiIndex & 1 ? 0 : 2;
6086       Mask1[2] = PermMask[2];
6087       Mask1[3] = PermMask[3];
6088       if (Mask1[2] >= 0)
6089         Mask1[2] += 4;
6090       if (Mask1[3] >= 0)
6091         Mask1[3] += 4;
6092       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6093     }
6094   }
6095
6096   // Break it into (shuffle shuffle_hi, shuffle_lo).
6097   Locs.clear();
6098   Locs.resize(4);
6099   SmallVector<int,8> LoMask(4U, -1);
6100   SmallVector<int,8> HiMask(4U, -1);
6101
6102   SmallVector<int,8> *MaskPtr = &LoMask;
6103   unsigned MaskIdx = 0;
6104   unsigned LoIdx = 0;
6105   unsigned HiIdx = 2;
6106   for (unsigned i = 0; i != 4; ++i) {
6107     if (i == 2) {
6108       MaskPtr = &HiMask;
6109       MaskIdx = 1;
6110       LoIdx = 0;
6111       HiIdx = 2;
6112     }
6113     int Idx = PermMask[i];
6114     if (Idx < 0) {
6115       Locs[i] = std::make_pair(-1, -1);
6116     } else if (Idx < 4) {
6117       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6118       (*MaskPtr)[LoIdx] = Idx;
6119       LoIdx++;
6120     } else {
6121       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6122       (*MaskPtr)[HiIdx] = Idx;
6123       HiIdx++;
6124     }
6125   }
6126
6127   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6128   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6129   SmallVector<int, 8> MaskOps;
6130   for (unsigned i = 0; i != 4; ++i) {
6131     if (Locs[i].first == -1) {
6132       MaskOps.push_back(-1);
6133     } else {
6134       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6135       MaskOps.push_back(Idx);
6136     }
6137   }
6138   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6139 }
6140
6141 static bool MayFoldVectorLoad(SDValue V) {
6142   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6143     V = V.getOperand(0);
6144   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6145     V = V.getOperand(0);
6146   if (MayFoldLoad(V))
6147     return true;
6148   return false;
6149 }
6150
6151 // FIXME: the version above should always be used. Since there's
6152 // a bug where several vector shuffles can't be folded because the
6153 // DAG is not updated during lowering and a node claims to have two
6154 // uses while it only has one, use this version, and let isel match
6155 // another instruction if the load really happens to have more than
6156 // one use. Remove this version after this bug get fixed.
6157 // rdar://8434668, PR8156
6158 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6159   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6160     V = V.getOperand(0);
6161   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6162     V = V.getOperand(0);
6163   if (ISD::isNormalLoad(V.getNode()))
6164     return true;
6165   return false;
6166 }
6167
6168 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6169 /// a vector extract, and if both can be later optimized into a single load.
6170 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6171 /// here because otherwise a target specific shuffle node is going to be
6172 /// emitted for this shuffle, and the optimization not done.
6173 /// FIXME: This is probably not the best approach, but fix the problem
6174 /// until the right path is decided.
6175 static
6176 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6177                                          const TargetLowering &TLI) {
6178   EVT VT = V.getValueType();
6179   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6180
6181   // Be sure that the vector shuffle is present in a pattern like this:
6182   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6183   if (!V.hasOneUse())
6184     return false;
6185
6186   SDNode *N = *V.getNode()->use_begin();
6187   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6188     return false;
6189
6190   SDValue EltNo = N->getOperand(1);
6191   if (!isa<ConstantSDNode>(EltNo))
6192     return false;
6193
6194   // If the bit convert changed the number of elements, it is unsafe
6195   // to examine the mask.
6196   bool HasShuffleIntoBitcast = false;
6197   if (V.getOpcode() == ISD::BITCAST) {
6198     EVT SrcVT = V.getOperand(0).getValueType();
6199     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6200       return false;
6201     V = V.getOperand(0);
6202     HasShuffleIntoBitcast = true;
6203   }
6204
6205   // Select the input vector, guarding against out of range extract vector.
6206   unsigned NumElems = VT.getVectorNumElements();
6207   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6208   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6209   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6210
6211   // Skip one more bit_convert if necessary
6212   if (V.getOpcode() == ISD::BITCAST)
6213     V = V.getOperand(0);
6214
6215   if (ISD::isNormalLoad(V.getNode())) {
6216     // Is the original load suitable?
6217     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6218
6219     // FIXME: avoid the multi-use bug that is preventing lots of
6220     // of foldings to be detected, this is still wrong of course, but
6221     // give the temporary desired behavior, and if it happens that
6222     // the load has real more uses, during isel it will not fold, and
6223     // will generate poor code.
6224     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6225       return false;
6226
6227     if (!HasShuffleIntoBitcast)
6228       return true;
6229
6230     // If there's a bitcast before the shuffle, check if the load type and
6231     // alignment is valid.
6232     unsigned Align = LN0->getAlignment();
6233     unsigned NewAlign =
6234       TLI.getTargetData()->getABITypeAlignment(
6235                                     VT.getTypeForEVT(*DAG.getContext()));
6236
6237     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6238       return false;
6239   }
6240
6241   return true;
6242 }
6243
6244 static
6245 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6246   EVT VT = Op.getValueType();
6247
6248   // Canonizalize to v2f64.
6249   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6250   return DAG.getNode(ISD::BITCAST, dl, VT,
6251                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6252                                           V1, DAG));
6253 }
6254
6255 static
6256 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6257                         bool HasSSE2) {
6258   SDValue V1 = Op.getOperand(0);
6259   SDValue V2 = Op.getOperand(1);
6260   EVT VT = Op.getValueType();
6261
6262   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6263
6264   if (HasSSE2 && VT == MVT::v2f64)
6265     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6266
6267   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6268   return DAG.getNode(ISD::BITCAST, dl, VT,
6269                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6270                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6271                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6272 }
6273
6274 static
6275 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6276   SDValue V1 = Op.getOperand(0);
6277   SDValue V2 = Op.getOperand(1);
6278   EVT VT = Op.getValueType();
6279
6280   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6281          "unsupported shuffle type");
6282
6283   if (V2.getOpcode() == ISD::UNDEF)
6284     V2 = V1;
6285
6286   // v4i32 or v4f32
6287   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6288 }
6289
6290 static inline unsigned getSHUFPOpcode(EVT VT) {
6291   switch(VT.getSimpleVT().SimpleTy) {
6292   case MVT::v8i32: // Use fp unit for int unpack.
6293   case MVT::v8f32:
6294   case MVT::v4i32: // Use fp unit for int unpack.
6295   case MVT::v4f32: return X86ISD::SHUFPS;
6296   case MVT::v4i64: // Use fp unit for int unpack.
6297   case MVT::v4f64:
6298   case MVT::v2i64: // Use fp unit for int unpack.
6299   case MVT::v2f64: return X86ISD::SHUFPD;
6300   default:
6301     llvm_unreachable("Unknown type for shufp*");
6302   }
6303   return 0;
6304 }
6305
6306 static
6307 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6308   SDValue V1 = Op.getOperand(0);
6309   SDValue V2 = Op.getOperand(1);
6310   EVT VT = Op.getValueType();
6311   unsigned NumElems = VT.getVectorNumElements();
6312
6313   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6314   // operand of these instructions is only memory, so check if there's a
6315   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6316   // same masks.
6317   bool CanFoldLoad = false;
6318
6319   // Trivial case, when V2 comes from a load.
6320   if (MayFoldVectorLoad(V2))
6321     CanFoldLoad = true;
6322
6323   // When V1 is a load, it can be folded later into a store in isel, example:
6324   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6325   //    turns into:
6326   //  (MOVLPSmr addr:$src1, VR128:$src2)
6327   // So, recognize this potential and also use MOVLPS or MOVLPD
6328   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6329     CanFoldLoad = true;
6330
6331   // Both of them can't be memory operations though.
6332   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6333     CanFoldLoad = false;
6334
6335   if (CanFoldLoad) {
6336     if (HasSSE2 && NumElems == 2)
6337       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6338
6339     if (NumElems == 4)
6340       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6341   }
6342
6343   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6344   // movl and movlp will both match v2i64, but v2i64 is never matched by
6345   // movl earlier because we make it strict to avoid messing with the movlp load
6346   // folding logic (see the code above getMOVLP call). Match it here then,
6347   // this is horrible, but will stay like this until we move all shuffle
6348   // matching to x86 specific nodes. Note that for the 1st condition all
6349   // types are matched with movsd.
6350   if (HasSSE2) {
6351     if (NumElems == 2)
6352       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6353     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6354   }
6355
6356   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6357
6358   // Invert the operand order and use SHUFPS to match it.
6359   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6360                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6361 }
6362
6363 static inline unsigned getUNPCKLOpcode(EVT VT) {
6364   switch(VT.getSimpleVT().SimpleTy) {
6365   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6366   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6367   case MVT::v4f32: return X86ISD::UNPCKLPS;
6368   case MVT::v2f64: return X86ISD::UNPCKLPD;
6369   case MVT::v8i32: // Use fp unit for int unpack.
6370   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6371   case MVT::v4i64: // Use fp unit for int unpack.
6372   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6373   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6374   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6375   default:
6376     llvm_unreachable("Unknown type for unpckl");
6377   }
6378   return 0;
6379 }
6380
6381 static inline unsigned getUNPCKHOpcode(EVT VT) {
6382   switch(VT.getSimpleVT().SimpleTy) {
6383   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6384   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6385   case MVT::v4f32: return X86ISD::UNPCKHPS;
6386   case MVT::v2f64: return X86ISD::UNPCKHPD;
6387   case MVT::v8i32: // Use fp unit for int unpack.
6388   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6389   case MVT::v4i64: // Use fp unit for int unpack.
6390   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6391   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6392   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6393   default:
6394     llvm_unreachable("Unknown type for unpckh");
6395   }
6396   return 0;
6397 }
6398
6399 static inline unsigned getVPERMILOpcode(EVT VT) {
6400   switch(VT.getSimpleVT().SimpleTy) {
6401   case MVT::v4i32:
6402   case MVT::v4f32: return X86ISD::VPERMILPS;
6403   case MVT::v2i64:
6404   case MVT::v2f64: return X86ISD::VPERMILPD;
6405   case MVT::v8i32:
6406   case MVT::v8f32: return X86ISD::VPERMILPSY;
6407   case MVT::v4i64:
6408   case MVT::v4f64: return X86ISD::VPERMILPDY;
6409   default:
6410     llvm_unreachable("Unknown type for vpermil");
6411   }
6412   return 0;
6413 }
6414
6415 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6416 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6417 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6418 static bool isVectorBroadcast(SDValue &Op) {
6419   EVT VT = Op.getValueType();
6420   bool Is256 = VT.getSizeInBits() == 256;
6421
6422   assert((VT.getSizeInBits() == 128 || Is256) &&
6423          "Unsupported type for vbroadcast node");
6424
6425   SDValue V = Op;
6426   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6427     V = V.getOperand(0);
6428
6429   if (Is256 && !(V.hasOneUse() &&
6430                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6431                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6432     return false;
6433
6434   if (Is256)
6435     V = V.getOperand(1);
6436
6437   if (!V.hasOneUse())
6438     return false;
6439
6440   // Check the source scalar_to_vector type. 256-bit broadcasts are
6441   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6442   // for 32-bit scalars.
6443   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6444     return false;
6445
6446   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6447   if (ScalarSize != 32 && ScalarSize != 64)
6448     return false;
6449   if (!Is256 && ScalarSize == 64)
6450     return false;
6451
6452   V = V.getOperand(0);
6453   if (!MayFoldLoad(V))
6454     return false;
6455
6456   // Return the load node
6457   Op = V;
6458   return true;
6459 }
6460
6461 static
6462 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6463                                const TargetLowering &TLI,
6464                                const X86Subtarget *Subtarget) {
6465   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6466   EVT VT = Op.getValueType();
6467   DebugLoc dl = Op.getDebugLoc();
6468   SDValue V1 = Op.getOperand(0);
6469   SDValue V2 = Op.getOperand(1);
6470
6471   if (isZeroShuffle(SVOp))
6472     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6473
6474   // Handle splat operations
6475   if (SVOp->isSplat()) {
6476     unsigned NumElem = VT.getVectorNumElements();
6477     int Size = VT.getSizeInBits();
6478     // Special case, this is the only place now where it's allowed to return
6479     // a vector_shuffle operation without using a target specific node, because
6480     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6481     // this be moved to DAGCombine instead?
6482     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6483       return Op;
6484
6485     // Use vbroadcast whenever the splat comes from a foldable load
6486     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6487       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6488
6489     // Handle splats by matching through known shuffle masks
6490     if ((Size == 128 && NumElem <= 4) ||
6491         (Size == 256 && NumElem < 8))
6492       return SDValue();
6493
6494     // All remaning splats are promoted to target supported vector shuffles.
6495     return PromoteSplat(SVOp, DAG);
6496   }
6497
6498   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6499   // do it!
6500   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6501     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6502     if (NewOp.getNode())
6503       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6504   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6505     // FIXME: Figure out a cleaner way to do this.
6506     // Try to make use of movq to zero out the top part.
6507     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6508       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6509       if (NewOp.getNode()) {
6510         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6511           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6512                               DAG, Subtarget, dl);
6513       }
6514     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6515       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6516       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6517         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6518                             DAG, Subtarget, dl);
6519     }
6520   }
6521   return SDValue();
6522 }
6523
6524 SDValue
6525 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6526   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6527   SDValue V1 = Op.getOperand(0);
6528   SDValue V2 = Op.getOperand(1);
6529   EVT VT = Op.getValueType();
6530   DebugLoc dl = Op.getDebugLoc();
6531   unsigned NumElems = VT.getVectorNumElements();
6532   bool isMMX = VT.getSizeInBits() == 64;
6533   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6534   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6535   bool V1IsSplat = false;
6536   bool V2IsSplat = false;
6537   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6538   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6539   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6540   MachineFunction &MF = DAG.getMachineFunction();
6541   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6542
6543   // Shuffle operations on MMX not supported.
6544   if (isMMX)
6545     return Op;
6546
6547   // Vector shuffle lowering takes 3 steps:
6548   //
6549   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6550   //    narrowing and commutation of operands should be handled.
6551   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6552   //    shuffle nodes.
6553   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6554   //    so the shuffle can be broken into other shuffles and the legalizer can
6555   //    try the lowering again.
6556   //
6557   // The general ideia is that no vector_shuffle operation should be left to
6558   // be matched during isel, all of them must be converted to a target specific
6559   // node here.
6560
6561   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6562   // narrowing and commutation of operands should be handled. The actual code
6563   // doesn't include all of those, work in progress...
6564   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6565   if (NewOp.getNode())
6566     return NewOp;
6567
6568   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6569   // unpckh_undef). Only use pshufd if speed is more important than size.
6570   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6571     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6572   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6573     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6574
6575   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6576       RelaxedMayFoldVectorLoad(V1))
6577     return getMOVDDup(Op, dl, V1, DAG);
6578
6579   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6580     return getMOVHighToLow(Op, dl, DAG);
6581
6582   // Use to match splats
6583   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6584       (VT == MVT::v2f64 || VT == MVT::v2i64))
6585     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6586
6587   if (X86::isPSHUFDMask(SVOp)) {
6588     // The actual implementation will match the mask in the if above and then
6589     // during isel it can match several different instructions, not only pshufd
6590     // as its name says, sad but true, emulate the behavior for now...
6591     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6592         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6593
6594     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6595
6596     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6597       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6598
6599     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6600                                 TargetMask, DAG);
6601   }
6602
6603   // Check if this can be converted into a logical shift.
6604   bool isLeft = false;
6605   unsigned ShAmt = 0;
6606   SDValue ShVal;
6607   bool isShift = getSubtarget()->hasSSE2() &&
6608     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6609   if (isShift && ShVal.hasOneUse()) {
6610     // If the shifted value has multiple uses, it may be cheaper to use
6611     // v_set0 + movlhps or movhlps, etc.
6612     EVT EltVT = VT.getVectorElementType();
6613     ShAmt *= EltVT.getSizeInBits();
6614     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6615   }
6616
6617   if (X86::isMOVLMask(SVOp)) {
6618     if (V1IsUndef)
6619       return V2;
6620     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6621       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6622     if (!X86::isMOVLPMask(SVOp)) {
6623       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6624         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6625
6626       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6627         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6628     }
6629   }
6630
6631   // FIXME: fold these into legal mask.
6632   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6633     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6634
6635   if (X86::isMOVHLPSMask(SVOp))
6636     return getMOVHighToLow(Op, dl, DAG);
6637
6638   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6639     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6640
6641   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6642     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6643
6644   if (X86::isMOVLPMask(SVOp))
6645     return getMOVLP(Op, dl, DAG, HasSSE2);
6646
6647   if (ShouldXformToMOVHLPS(SVOp) ||
6648       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6649     return CommuteVectorShuffle(SVOp, DAG);
6650
6651   if (isShift) {
6652     // No better options. Use a vshl / vsrl.
6653     EVT EltVT = VT.getVectorElementType();
6654     ShAmt *= EltVT.getSizeInBits();
6655     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6656   }
6657
6658   bool Commuted = false;
6659   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6660   // 1,1,1,1 -> v8i16 though.
6661   V1IsSplat = isSplatVector(V1.getNode());
6662   V2IsSplat = isSplatVector(V2.getNode());
6663
6664   // Canonicalize the splat or undef, if present, to be on the RHS.
6665   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6666     Op = CommuteVectorShuffle(SVOp, DAG);
6667     SVOp = cast<ShuffleVectorSDNode>(Op);
6668     V1 = SVOp->getOperand(0);
6669     V2 = SVOp->getOperand(1);
6670     std::swap(V1IsSplat, V2IsSplat);
6671     std::swap(V1IsUndef, V2IsUndef);
6672     Commuted = true;
6673   }
6674
6675   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6676     // Shuffling low element of v1 into undef, just return v1.
6677     if (V2IsUndef)
6678       return V1;
6679     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6680     // the instruction selector will not match, so get a canonical MOVL with
6681     // swapped operands to undo the commute.
6682     return getMOVL(DAG, dl, VT, V2, V1);
6683   }
6684
6685   if (X86::isUNPCKLMask(SVOp))
6686     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6687
6688   if (X86::isUNPCKHMask(SVOp))
6689     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6690
6691   if (V2IsSplat) {
6692     // Normalize mask so all entries that point to V2 points to its first
6693     // element then try to match unpck{h|l} again. If match, return a
6694     // new vector_shuffle with the corrected mask.
6695     SDValue NewMask = NormalizeMask(SVOp, DAG);
6696     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6697     if (NSVOp != SVOp) {
6698       if (X86::isUNPCKLMask(NSVOp, true)) {
6699         return NewMask;
6700       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6701         return NewMask;
6702       }
6703     }
6704   }
6705
6706   if (Commuted) {
6707     // Commute is back and try unpck* again.
6708     // FIXME: this seems wrong.
6709     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6710     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6711
6712     if (X86::isUNPCKLMask(NewSVOp))
6713       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6714
6715     if (X86::isUNPCKHMask(NewSVOp))
6716       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6717   }
6718
6719   // Normalize the node to match x86 shuffle ops if needed
6720   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6721     return CommuteVectorShuffle(SVOp, DAG);
6722
6723   // The checks below are all present in isShuffleMaskLegal, but they are
6724   // inlined here right now to enable us to directly emit target specific
6725   // nodes, and remove one by one until they don't return Op anymore.
6726   SmallVector<int, 16> M;
6727   SVOp->getMask(M);
6728
6729   if (isPALIGNRMask(M, VT, HasSSSE3))
6730     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6731                                 X86::getShufflePALIGNRImmediate(SVOp),
6732                                 DAG);
6733
6734   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6735       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6736     if (VT == MVT::v2f64)
6737       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6738     if (VT == MVT::v2i64)
6739       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6740   }
6741
6742   if (isPSHUFHWMask(M, VT))
6743     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6744                                 X86::getShufflePSHUFHWImmediate(SVOp),
6745                                 DAG);
6746
6747   if (isPSHUFLWMask(M, VT))
6748     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6749                                 X86::getShufflePSHUFLWImmediate(SVOp),
6750                                 DAG);
6751
6752   if (isSHUFPMask(M, VT))
6753     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6754                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6755
6756   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6757     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6758   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6759     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6760
6761   //===--------------------------------------------------------------------===//
6762   // Generate target specific nodes for 128 or 256-bit shuffles only
6763   // supported in the AVX instruction set.
6764   //
6765
6766   // Handle VMOVDDUPY permutations
6767   if (isMOVDDUPYMask(SVOp, Subtarget))
6768     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6769
6770   // Handle VPERMILPS* permutations
6771   if (isVPERMILPSMask(M, VT, Subtarget))
6772     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6773                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6774
6775   // Handle VPERMILPD* permutations
6776   if (isVPERMILPDMask(M, VT, Subtarget))
6777     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6778                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6779
6780   // Handle VPERM2F128 permutations
6781   if (isVPERM2F128Mask(M, VT, Subtarget))
6782     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6783                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6784
6785   // Handle VSHUFPSY permutations
6786   if (isVSHUFPSYMask(M, VT, Subtarget))
6787     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6788                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6789
6790   // Handle VSHUFPDY permutations
6791   if (isVSHUFPDYMask(M, VT, Subtarget))
6792     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6793                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6794
6795   //===--------------------------------------------------------------------===//
6796   // Since no target specific shuffle was selected for this generic one,
6797   // lower it into other known shuffles. FIXME: this isn't true yet, but
6798   // this is the plan.
6799   //
6800
6801   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6802   if (VT == MVT::v8i16) {
6803     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6804     if (NewOp.getNode())
6805       return NewOp;
6806   }
6807
6808   if (VT == MVT::v16i8) {
6809     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6810     if (NewOp.getNode())
6811       return NewOp;
6812   }
6813
6814   // Handle all 128-bit wide vectors with 4 elements, and match them with
6815   // several different shuffle types.
6816   if (NumElems == 4 && VT.getSizeInBits() == 128)
6817     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6818
6819   // Handle general 256-bit shuffles
6820   if (VT.is256BitVector())
6821     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6822
6823   return SDValue();
6824 }
6825
6826 SDValue
6827 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6828                                                 SelectionDAG &DAG) const {
6829   EVT VT = Op.getValueType();
6830   DebugLoc dl = Op.getDebugLoc();
6831
6832   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6833     return SDValue();
6834
6835   if (VT.getSizeInBits() == 8) {
6836     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6837                                     Op.getOperand(0), Op.getOperand(1));
6838     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6839                                     DAG.getValueType(VT));
6840     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6841   } else if (VT.getSizeInBits() == 16) {
6842     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6843     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6844     if (Idx == 0)
6845       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6846                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6847                                      DAG.getNode(ISD::BITCAST, dl,
6848                                                  MVT::v4i32,
6849                                                  Op.getOperand(0)),
6850                                      Op.getOperand(1)));
6851     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6852                                     Op.getOperand(0), Op.getOperand(1));
6853     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6854                                     DAG.getValueType(VT));
6855     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6856   } else if (VT == MVT::f32) {
6857     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6858     // the result back to FR32 register. It's only worth matching if the
6859     // result has a single use which is a store or a bitcast to i32.  And in
6860     // the case of a store, it's not worth it if the index is a constant 0,
6861     // because a MOVSSmr can be used instead, which is smaller and faster.
6862     if (!Op.hasOneUse())
6863       return SDValue();
6864     SDNode *User = *Op.getNode()->use_begin();
6865     if ((User->getOpcode() != ISD::STORE ||
6866          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6867           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6868         (User->getOpcode() != ISD::BITCAST ||
6869          User->getValueType(0) != MVT::i32))
6870       return SDValue();
6871     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6872                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6873                                               Op.getOperand(0)),
6874                                               Op.getOperand(1));
6875     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6876   } else if (VT == MVT::i32) {
6877     // ExtractPS works with constant index.
6878     if (isa<ConstantSDNode>(Op.getOperand(1)))
6879       return Op;
6880   }
6881   return SDValue();
6882 }
6883
6884
6885 SDValue
6886 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6887                                            SelectionDAG &DAG) const {
6888   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6889     return SDValue();
6890
6891   SDValue Vec = Op.getOperand(0);
6892   EVT VecVT = Vec.getValueType();
6893
6894   // If this is a 256-bit vector result, first extract the 128-bit vector and
6895   // then extract the element from the 128-bit vector.
6896   if (VecVT.getSizeInBits() == 256) {
6897     DebugLoc dl = Op.getNode()->getDebugLoc();
6898     unsigned NumElems = VecVT.getVectorNumElements();
6899     SDValue Idx = Op.getOperand(1);
6900     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6901
6902     // Get the 128-bit vector.
6903     bool Upper = IdxVal >= NumElems/2;
6904     Vec = Extract128BitVector(Vec,
6905                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6906
6907     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6908                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6909   }
6910
6911   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6912
6913   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6914     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6915     if (Res.getNode())
6916       return Res;
6917   }
6918
6919   EVT VT = Op.getValueType();
6920   DebugLoc dl = Op.getDebugLoc();
6921   // TODO: handle v16i8.
6922   if (VT.getSizeInBits() == 16) {
6923     SDValue Vec = Op.getOperand(0);
6924     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6925     if (Idx == 0)
6926       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6927                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6928                                      DAG.getNode(ISD::BITCAST, dl,
6929                                                  MVT::v4i32, Vec),
6930                                      Op.getOperand(1)));
6931     // Transform it so it match pextrw which produces a 32-bit result.
6932     EVT EltVT = MVT::i32;
6933     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6934                                     Op.getOperand(0), Op.getOperand(1));
6935     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6936                                     DAG.getValueType(VT));
6937     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6938   } else if (VT.getSizeInBits() == 32) {
6939     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6940     if (Idx == 0)
6941       return Op;
6942
6943     // SHUFPS the element to the lowest double word, then movss.
6944     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6945     EVT VVT = Op.getOperand(0).getValueType();
6946     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6947                                        DAG.getUNDEF(VVT), Mask);
6948     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6949                        DAG.getIntPtrConstant(0));
6950   } else if (VT.getSizeInBits() == 64) {
6951     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6952     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6953     //        to match extract_elt for f64.
6954     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6955     if (Idx == 0)
6956       return Op;
6957
6958     // UNPCKHPD the element to the lowest double word, then movsd.
6959     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6960     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6961     int Mask[2] = { 1, -1 };
6962     EVT VVT = Op.getOperand(0).getValueType();
6963     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6964                                        DAG.getUNDEF(VVT), Mask);
6965     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6966                        DAG.getIntPtrConstant(0));
6967   }
6968
6969   return SDValue();
6970 }
6971
6972 SDValue
6973 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6974                                                SelectionDAG &DAG) const {
6975   EVT VT = Op.getValueType();
6976   EVT EltVT = VT.getVectorElementType();
6977   DebugLoc dl = Op.getDebugLoc();
6978
6979   SDValue N0 = Op.getOperand(0);
6980   SDValue N1 = Op.getOperand(1);
6981   SDValue N2 = Op.getOperand(2);
6982
6983   if (VT.getSizeInBits() == 256)
6984     return SDValue();
6985
6986   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6987       isa<ConstantSDNode>(N2)) {
6988     unsigned Opc;
6989     if (VT == MVT::v8i16)
6990       Opc = X86ISD::PINSRW;
6991     else if (VT == MVT::v16i8)
6992       Opc = X86ISD::PINSRB;
6993     else
6994       Opc = X86ISD::PINSRB;
6995
6996     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6997     // argument.
6998     if (N1.getValueType() != MVT::i32)
6999       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7000     if (N2.getValueType() != MVT::i32)
7001       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7002     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7003   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7004     // Bits [7:6] of the constant are the source select.  This will always be
7005     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7006     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7007     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7008     // Bits [5:4] of the constant are the destination select.  This is the
7009     //  value of the incoming immediate.
7010     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7011     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7012     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7013     // Create this as a scalar to vector..
7014     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7015     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7016   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7017     // PINSR* works with constant index.
7018     return Op;
7019   }
7020   return SDValue();
7021 }
7022
7023 SDValue
7024 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7025   EVT VT = Op.getValueType();
7026   EVT EltVT = VT.getVectorElementType();
7027
7028   DebugLoc dl = Op.getDebugLoc();
7029   SDValue N0 = Op.getOperand(0);
7030   SDValue N1 = Op.getOperand(1);
7031   SDValue N2 = Op.getOperand(2);
7032
7033   // If this is a 256-bit vector result, first extract the 128-bit vector,
7034   // insert the element into the extracted half and then place it back.
7035   if (VT.getSizeInBits() == 256) {
7036     if (!isa<ConstantSDNode>(N2))
7037       return SDValue();
7038
7039     // Get the desired 128-bit vector half.
7040     unsigned NumElems = VT.getVectorNumElements();
7041     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7042     bool Upper = IdxVal >= NumElems/2;
7043     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7044     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7045
7046     // Insert the element into the desired half.
7047     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7048                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7049
7050     // Insert the changed part back to the 256-bit vector
7051     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7052   }
7053
7054   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7055     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7056
7057   if (EltVT == MVT::i8)
7058     return SDValue();
7059
7060   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7061     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7062     // as its second argument.
7063     if (N1.getValueType() != MVT::i32)
7064       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7065     if (N2.getValueType() != MVT::i32)
7066       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7067     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7068   }
7069   return SDValue();
7070 }
7071
7072 SDValue
7073 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7074   LLVMContext *Context = DAG.getContext();
7075   DebugLoc dl = Op.getDebugLoc();
7076   EVT OpVT = Op.getValueType();
7077
7078   // If this is a 256-bit vector result, first insert into a 128-bit
7079   // vector and then insert into the 256-bit vector.
7080   if (OpVT.getSizeInBits() > 128) {
7081     // Insert into a 128-bit vector.
7082     EVT VT128 = EVT::getVectorVT(*Context,
7083                                  OpVT.getVectorElementType(),
7084                                  OpVT.getVectorNumElements() / 2);
7085
7086     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7087
7088     // Insert the 128-bit vector.
7089     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7090                               DAG.getConstant(0, MVT::i32),
7091                               DAG, dl);
7092   }
7093
7094   if (Op.getValueType() == MVT::v1i64 &&
7095       Op.getOperand(0).getValueType() == MVT::i64)
7096     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7097
7098   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7099   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7100          "Expected an SSE type!");
7101   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7102                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7103 }
7104
7105 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7106 // a simple subregister reference or explicit instructions to grab
7107 // upper bits of a vector.
7108 SDValue
7109 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7110   if (Subtarget->hasAVX()) {
7111     DebugLoc dl = Op.getNode()->getDebugLoc();
7112     SDValue Vec = Op.getNode()->getOperand(0);
7113     SDValue Idx = Op.getNode()->getOperand(1);
7114
7115     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7116         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7117         return Extract128BitVector(Vec, Idx, DAG, dl);
7118     }
7119   }
7120   return SDValue();
7121 }
7122
7123 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7124 // simple superregister reference or explicit instructions to insert
7125 // the upper bits of a vector.
7126 SDValue
7127 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7128   if (Subtarget->hasAVX()) {
7129     DebugLoc dl = Op.getNode()->getDebugLoc();
7130     SDValue Vec = Op.getNode()->getOperand(0);
7131     SDValue SubVec = Op.getNode()->getOperand(1);
7132     SDValue Idx = Op.getNode()->getOperand(2);
7133
7134     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7135         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7136       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7137     }
7138   }
7139   return SDValue();
7140 }
7141
7142 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7143 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7144 // one of the above mentioned nodes. It has to be wrapped because otherwise
7145 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7146 // be used to form addressing mode. These wrapped nodes will be selected
7147 // into MOV32ri.
7148 SDValue
7149 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7150   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7151
7152   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7153   // global base reg.
7154   unsigned char OpFlag = 0;
7155   unsigned WrapperKind = X86ISD::Wrapper;
7156   CodeModel::Model M = getTargetMachine().getCodeModel();
7157
7158   if (Subtarget->isPICStyleRIPRel() &&
7159       (M == CodeModel::Small || M == CodeModel::Kernel))
7160     WrapperKind = X86ISD::WrapperRIP;
7161   else if (Subtarget->isPICStyleGOT())
7162     OpFlag = X86II::MO_GOTOFF;
7163   else if (Subtarget->isPICStyleStubPIC())
7164     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7165
7166   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7167                                              CP->getAlignment(),
7168                                              CP->getOffset(), OpFlag);
7169   DebugLoc DL = CP->getDebugLoc();
7170   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7171   // With PIC, the address is actually $g + Offset.
7172   if (OpFlag) {
7173     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7174                          DAG.getNode(X86ISD::GlobalBaseReg,
7175                                      DebugLoc(), getPointerTy()),
7176                          Result);
7177   }
7178
7179   return Result;
7180 }
7181
7182 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7183   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7184
7185   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7186   // global base reg.
7187   unsigned char OpFlag = 0;
7188   unsigned WrapperKind = X86ISD::Wrapper;
7189   CodeModel::Model M = getTargetMachine().getCodeModel();
7190
7191   if (Subtarget->isPICStyleRIPRel() &&
7192       (M == CodeModel::Small || M == CodeModel::Kernel))
7193     WrapperKind = X86ISD::WrapperRIP;
7194   else if (Subtarget->isPICStyleGOT())
7195     OpFlag = X86II::MO_GOTOFF;
7196   else if (Subtarget->isPICStyleStubPIC())
7197     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7198
7199   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7200                                           OpFlag);
7201   DebugLoc DL = JT->getDebugLoc();
7202   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7203
7204   // With PIC, the address is actually $g + Offset.
7205   if (OpFlag)
7206     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7207                          DAG.getNode(X86ISD::GlobalBaseReg,
7208                                      DebugLoc(), getPointerTy()),
7209                          Result);
7210
7211   return Result;
7212 }
7213
7214 SDValue
7215 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7216   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7217
7218   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7219   // global base reg.
7220   unsigned char OpFlag = 0;
7221   unsigned WrapperKind = X86ISD::Wrapper;
7222   CodeModel::Model M = getTargetMachine().getCodeModel();
7223
7224   if (Subtarget->isPICStyleRIPRel() &&
7225       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7226     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7227       OpFlag = X86II::MO_GOTPCREL;
7228     WrapperKind = X86ISD::WrapperRIP;
7229   } else if (Subtarget->isPICStyleGOT()) {
7230     OpFlag = X86II::MO_GOT;
7231   } else if (Subtarget->isPICStyleStubPIC()) {
7232     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7233   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7234     OpFlag = X86II::MO_DARWIN_NONLAZY;
7235   }
7236
7237   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7238
7239   DebugLoc DL = Op.getDebugLoc();
7240   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7241
7242
7243   // With PIC, the address is actually $g + Offset.
7244   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7245       !Subtarget->is64Bit()) {
7246     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7247                          DAG.getNode(X86ISD::GlobalBaseReg,
7248                                      DebugLoc(), getPointerTy()),
7249                          Result);
7250   }
7251
7252   // For symbols that require a load from a stub to get the address, emit the
7253   // load.
7254   if (isGlobalStubReference(OpFlag))
7255     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7256                          MachinePointerInfo::getGOT(), false, false, 0);
7257
7258   return Result;
7259 }
7260
7261 SDValue
7262 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7263   // Create the TargetBlockAddressAddress node.
7264   unsigned char OpFlags =
7265     Subtarget->ClassifyBlockAddressReference();
7266   CodeModel::Model M = getTargetMachine().getCodeModel();
7267   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7268   DebugLoc dl = Op.getDebugLoc();
7269   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7270                                        /*isTarget=*/true, OpFlags);
7271
7272   if (Subtarget->isPICStyleRIPRel() &&
7273       (M == CodeModel::Small || M == CodeModel::Kernel))
7274     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7275   else
7276     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7277
7278   // With PIC, the address is actually $g + Offset.
7279   if (isGlobalRelativeToPICBase(OpFlags)) {
7280     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7281                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7282                          Result);
7283   }
7284
7285   return Result;
7286 }
7287
7288 SDValue
7289 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7290                                       int64_t Offset,
7291                                       SelectionDAG &DAG) const {
7292   // Create the TargetGlobalAddress node, folding in the constant
7293   // offset if it is legal.
7294   unsigned char OpFlags =
7295     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7296   CodeModel::Model M = getTargetMachine().getCodeModel();
7297   SDValue Result;
7298   if (OpFlags == X86II::MO_NO_FLAG &&
7299       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7300     // A direct static reference to a global.
7301     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7302     Offset = 0;
7303   } else {
7304     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7305   }
7306
7307   if (Subtarget->isPICStyleRIPRel() &&
7308       (M == CodeModel::Small || M == CodeModel::Kernel))
7309     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7310   else
7311     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7312
7313   // With PIC, the address is actually $g + Offset.
7314   if (isGlobalRelativeToPICBase(OpFlags)) {
7315     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7316                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7317                          Result);
7318   }
7319
7320   // For globals that require a load from a stub to get the address, emit the
7321   // load.
7322   if (isGlobalStubReference(OpFlags))
7323     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7324                          MachinePointerInfo::getGOT(), false, false, 0);
7325
7326   // If there was a non-zero offset that we didn't fold, create an explicit
7327   // addition for it.
7328   if (Offset != 0)
7329     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7330                          DAG.getConstant(Offset, getPointerTy()));
7331
7332   return Result;
7333 }
7334
7335 SDValue
7336 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7337   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7338   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7339   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7340 }
7341
7342 static SDValue
7343 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7344            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7345            unsigned char OperandFlags) {
7346   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7347   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7348   DebugLoc dl = GA->getDebugLoc();
7349   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7350                                            GA->getValueType(0),
7351                                            GA->getOffset(),
7352                                            OperandFlags);
7353   if (InFlag) {
7354     SDValue Ops[] = { Chain,  TGA, *InFlag };
7355     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7356   } else {
7357     SDValue Ops[]  = { Chain, TGA };
7358     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7359   }
7360
7361   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7362   MFI->setAdjustsStack(true);
7363
7364   SDValue Flag = Chain.getValue(1);
7365   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7366 }
7367
7368 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7369 static SDValue
7370 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7371                                 const EVT PtrVT) {
7372   SDValue InFlag;
7373   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7374   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7375                                      DAG.getNode(X86ISD::GlobalBaseReg,
7376                                                  DebugLoc(), PtrVT), InFlag);
7377   InFlag = Chain.getValue(1);
7378
7379   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7380 }
7381
7382 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7383 static SDValue
7384 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7385                                 const EVT PtrVT) {
7386   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7387                     X86::RAX, X86II::MO_TLSGD);
7388 }
7389
7390 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7391 // "local exec" model.
7392 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7393                                    const EVT PtrVT, TLSModel::Model model,
7394                                    bool is64Bit) {
7395   DebugLoc dl = GA->getDebugLoc();
7396
7397   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7398   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7399                                                          is64Bit ? 257 : 256));
7400
7401   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7402                                       DAG.getIntPtrConstant(0),
7403                                       MachinePointerInfo(Ptr), false, false, 0);
7404
7405   unsigned char OperandFlags = 0;
7406   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7407   // initialexec.
7408   unsigned WrapperKind = X86ISD::Wrapper;
7409   if (model == TLSModel::LocalExec) {
7410     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7411   } else if (is64Bit) {
7412     assert(model == TLSModel::InitialExec);
7413     OperandFlags = X86II::MO_GOTTPOFF;
7414     WrapperKind = X86ISD::WrapperRIP;
7415   } else {
7416     assert(model == TLSModel::InitialExec);
7417     OperandFlags = X86II::MO_INDNTPOFF;
7418   }
7419
7420   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7421   // exec)
7422   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7423                                            GA->getValueType(0),
7424                                            GA->getOffset(), OperandFlags);
7425   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7426
7427   if (model == TLSModel::InitialExec)
7428     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7429                          MachinePointerInfo::getGOT(), false, false, 0);
7430
7431   // The address of the thread local variable is the add of the thread
7432   // pointer with the offset of the variable.
7433   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7434 }
7435
7436 SDValue
7437 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7438
7439   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7440   const GlobalValue *GV = GA->getGlobal();
7441
7442   if (Subtarget->isTargetELF()) {
7443     // TODO: implement the "local dynamic" model
7444     // TODO: implement the "initial exec"model for pic executables
7445
7446     // If GV is an alias then use the aliasee for determining
7447     // thread-localness.
7448     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7449       GV = GA->resolveAliasedGlobal(false);
7450
7451     TLSModel::Model model
7452       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7453
7454     switch (model) {
7455       case TLSModel::GeneralDynamic:
7456       case TLSModel::LocalDynamic: // not implemented
7457         if (Subtarget->is64Bit())
7458           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7459         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7460
7461       case TLSModel::InitialExec:
7462       case TLSModel::LocalExec:
7463         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7464                                    Subtarget->is64Bit());
7465     }
7466   } else if (Subtarget->isTargetDarwin()) {
7467     // Darwin only has one model of TLS.  Lower to that.
7468     unsigned char OpFlag = 0;
7469     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7470                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7471
7472     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7473     // global base reg.
7474     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7475                   !Subtarget->is64Bit();
7476     if (PIC32)
7477       OpFlag = X86II::MO_TLVP_PIC_BASE;
7478     else
7479       OpFlag = X86II::MO_TLVP;
7480     DebugLoc DL = Op.getDebugLoc();
7481     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7482                                                 GA->getValueType(0),
7483                                                 GA->getOffset(), OpFlag);
7484     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7485
7486     // With PIC32, the address is actually $g + Offset.
7487     if (PIC32)
7488       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7489                            DAG.getNode(X86ISD::GlobalBaseReg,
7490                                        DebugLoc(), getPointerTy()),
7491                            Offset);
7492
7493     // Lowering the machine isd will make sure everything is in the right
7494     // location.
7495     SDValue Chain = DAG.getEntryNode();
7496     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7497     SDValue Args[] = { Chain, Offset };
7498     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7499
7500     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7501     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7502     MFI->setAdjustsStack(true);
7503
7504     // And our return value (tls address) is in the standard call return value
7505     // location.
7506     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7507     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7508   }
7509
7510   assert(false &&
7511          "TLS not implemented for this target.");
7512
7513   llvm_unreachable("Unreachable");
7514   return SDValue();
7515 }
7516
7517
7518 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7519 /// take a 2 x i32 value to shift plus a shift amount.
7520 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7521   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7522   EVT VT = Op.getValueType();
7523   unsigned VTBits = VT.getSizeInBits();
7524   DebugLoc dl = Op.getDebugLoc();
7525   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7526   SDValue ShOpLo = Op.getOperand(0);
7527   SDValue ShOpHi = Op.getOperand(1);
7528   SDValue ShAmt  = Op.getOperand(2);
7529   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7530                                      DAG.getConstant(VTBits - 1, MVT::i8))
7531                        : DAG.getConstant(0, VT);
7532
7533   SDValue Tmp2, Tmp3;
7534   if (Op.getOpcode() == ISD::SHL_PARTS) {
7535     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7536     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7537   } else {
7538     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7539     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7540   }
7541
7542   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7543                                 DAG.getConstant(VTBits, MVT::i8));
7544   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7545                              AndNode, DAG.getConstant(0, MVT::i8));
7546
7547   SDValue Hi, Lo;
7548   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7549   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7550   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7551
7552   if (Op.getOpcode() == ISD::SHL_PARTS) {
7553     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7554     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7555   } else {
7556     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7557     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7558   }
7559
7560   SDValue Ops[2] = { Lo, Hi };
7561   return DAG.getMergeValues(Ops, 2, dl);
7562 }
7563
7564 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7565                                            SelectionDAG &DAG) const {
7566   EVT SrcVT = Op.getOperand(0).getValueType();
7567
7568   if (SrcVT.isVector())
7569     return SDValue();
7570
7571   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7572          "Unknown SINT_TO_FP to lower!");
7573
7574   // These are really Legal; return the operand so the caller accepts it as
7575   // Legal.
7576   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7577     return Op;
7578   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7579       Subtarget->is64Bit()) {
7580     return Op;
7581   }
7582
7583   DebugLoc dl = Op.getDebugLoc();
7584   unsigned Size = SrcVT.getSizeInBits()/8;
7585   MachineFunction &MF = DAG.getMachineFunction();
7586   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7587   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7588   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7589                                StackSlot,
7590                                MachinePointerInfo::getFixedStack(SSFI),
7591                                false, false, 0);
7592   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7593 }
7594
7595 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7596                                      SDValue StackSlot,
7597                                      SelectionDAG &DAG) const {
7598   // Build the FILD
7599   DebugLoc DL = Op.getDebugLoc();
7600   SDVTList Tys;
7601   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7602   if (useSSE)
7603     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7604   else
7605     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7606
7607   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7608
7609   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7610   MachineMemOperand *MMO;
7611   if (FI) {
7612     int SSFI = FI->getIndex();
7613     MMO =
7614       DAG.getMachineFunction()
7615       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7616                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7617   } else {
7618     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7619     StackSlot = StackSlot.getOperand(1);
7620   }
7621   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7622   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7623                                            X86ISD::FILD, DL,
7624                                            Tys, Ops, array_lengthof(Ops),
7625                                            SrcVT, MMO);
7626
7627   if (useSSE) {
7628     Chain = Result.getValue(1);
7629     SDValue InFlag = Result.getValue(2);
7630
7631     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7632     // shouldn't be necessary except that RFP cannot be live across
7633     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7634     MachineFunction &MF = DAG.getMachineFunction();
7635     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7636     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7637     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7638     Tys = DAG.getVTList(MVT::Other);
7639     SDValue Ops[] = {
7640       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7641     };
7642     MachineMemOperand *MMO =
7643       DAG.getMachineFunction()
7644       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7645                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7646
7647     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7648                                     Ops, array_lengthof(Ops),
7649                                     Op.getValueType(), MMO);
7650     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7651                          MachinePointerInfo::getFixedStack(SSFI),
7652                          false, false, 0);
7653   }
7654
7655   return Result;
7656 }
7657
7658 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7659 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7660                                                SelectionDAG &DAG) const {
7661   // This algorithm is not obvious. Here it is in C code, more or less:
7662   /*
7663     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7664       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7665       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7666
7667       // Copy ints to xmm registers.
7668       __m128i xh = _mm_cvtsi32_si128( hi );
7669       __m128i xl = _mm_cvtsi32_si128( lo );
7670
7671       // Combine into low half of a single xmm register.
7672       __m128i x = _mm_unpacklo_epi32( xh, xl );
7673       __m128d d;
7674       double sd;
7675
7676       // Merge in appropriate exponents to give the integer bits the right
7677       // magnitude.
7678       x = _mm_unpacklo_epi32( x, exp );
7679
7680       // Subtract away the biases to deal with the IEEE-754 double precision
7681       // implicit 1.
7682       d = _mm_sub_pd( (__m128d) x, bias );
7683
7684       // All conversions up to here are exact. The correctly rounded result is
7685       // calculated using the current rounding mode using the following
7686       // horizontal add.
7687       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7688       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7689                                 // store doesn't really need to be here (except
7690                                 // maybe to zero the other double)
7691       return sd;
7692     }
7693   */
7694
7695   DebugLoc dl = Op.getDebugLoc();
7696   LLVMContext *Context = DAG.getContext();
7697
7698   // Build some magic constants.
7699   std::vector<Constant*> CV0;
7700   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7701   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7702   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7703   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7704   Constant *C0 = ConstantVector::get(CV0);
7705   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7706
7707   std::vector<Constant*> CV1;
7708   CV1.push_back(
7709     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7710   CV1.push_back(
7711     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7712   Constant *C1 = ConstantVector::get(CV1);
7713   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7714
7715   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7716                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7717                                         Op.getOperand(0),
7718                                         DAG.getIntPtrConstant(1)));
7719   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7720                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7721                                         Op.getOperand(0),
7722                                         DAG.getIntPtrConstant(0)));
7723   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7724   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7725                               MachinePointerInfo::getConstantPool(),
7726                               false, false, 16);
7727   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7728   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7729   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7730                               MachinePointerInfo::getConstantPool(),
7731                               false, false, 16);
7732   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7733
7734   // Add the halves; easiest way is to swap them into another reg first.
7735   int ShufMask[2] = { 1, -1 };
7736   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7737                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7738   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7739   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7740                      DAG.getIntPtrConstant(0));
7741 }
7742
7743 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7744 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7745                                                SelectionDAG &DAG) const {
7746   DebugLoc dl = Op.getDebugLoc();
7747   // FP constant to bias correct the final result.
7748   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7749                                    MVT::f64);
7750
7751   // Load the 32-bit value into an XMM register.
7752   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7753                              Op.getOperand(0));
7754
7755   // Zero out the upper parts of the register.
7756   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasSSE2(), DAG);
7757
7758   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7759                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7760                      DAG.getIntPtrConstant(0));
7761
7762   // Or the load with the bias.
7763   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7764                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7765                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7766                                                    MVT::v2f64, Load)),
7767                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7768                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7769                                                    MVT::v2f64, Bias)));
7770   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7771                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7772                    DAG.getIntPtrConstant(0));
7773
7774   // Subtract the bias.
7775   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7776
7777   // Handle final rounding.
7778   EVT DestVT = Op.getValueType();
7779
7780   if (DestVT.bitsLT(MVT::f64)) {
7781     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7782                        DAG.getIntPtrConstant(0));
7783   } else if (DestVT.bitsGT(MVT::f64)) {
7784     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7785   }
7786
7787   // Handle final rounding.
7788   return Sub;
7789 }
7790
7791 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7792                                            SelectionDAG &DAG) const {
7793   SDValue N0 = Op.getOperand(0);
7794   DebugLoc dl = Op.getDebugLoc();
7795
7796   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7797   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7798   // the optimization here.
7799   if (DAG.SignBitIsZero(N0))
7800     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7801
7802   EVT SrcVT = N0.getValueType();
7803   EVT DstVT = Op.getValueType();
7804   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7805     return LowerUINT_TO_FP_i64(Op, DAG);
7806   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7807     return LowerUINT_TO_FP_i32(Op, DAG);
7808
7809   // Make a 64-bit buffer, and use it to build an FILD.
7810   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7811   if (SrcVT == MVT::i32) {
7812     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7813     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7814                                      getPointerTy(), StackSlot, WordOff);
7815     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7816                                   StackSlot, MachinePointerInfo(),
7817                                   false, false, 0);
7818     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7819                                   OffsetSlot, MachinePointerInfo(),
7820                                   false, false, 0);
7821     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7822     return Fild;
7823   }
7824
7825   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7826   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7827                                 StackSlot, MachinePointerInfo(),
7828                                false, false, 0);
7829   // For i64 source, we need to add the appropriate power of 2 if the input
7830   // was negative.  This is the same as the optimization in
7831   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7832   // we must be careful to do the computation in x87 extended precision, not
7833   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7834   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7835   MachineMemOperand *MMO =
7836     DAG.getMachineFunction()
7837     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7838                           MachineMemOperand::MOLoad, 8, 8);
7839
7840   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7841   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7842   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7843                                          MVT::i64, MMO);
7844
7845   APInt FF(32, 0x5F800000ULL);
7846
7847   // Check whether the sign bit is set.
7848   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7849                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7850                                  ISD::SETLT);
7851
7852   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7853   SDValue FudgePtr = DAG.getConstantPool(
7854                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7855                                          getPointerTy());
7856
7857   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7858   SDValue Zero = DAG.getIntPtrConstant(0);
7859   SDValue Four = DAG.getIntPtrConstant(4);
7860   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7861                                Zero, Four);
7862   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7863
7864   // Load the value out, extending it from f32 to f80.
7865   // FIXME: Avoid the extend by constructing the right constant pool?
7866   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7867                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7868                                  MVT::f32, false, false, 4);
7869   // Extend everything to 80 bits to force it to be done on x87.
7870   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7871   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7872 }
7873
7874 std::pair<SDValue,SDValue> X86TargetLowering::
7875 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7876   DebugLoc DL = Op.getDebugLoc();
7877
7878   EVT DstTy = Op.getValueType();
7879
7880   if (!IsSigned) {
7881     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7882     DstTy = MVT::i64;
7883   }
7884
7885   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7886          DstTy.getSimpleVT() >= MVT::i16 &&
7887          "Unknown FP_TO_SINT to lower!");
7888
7889   // These are really Legal.
7890   if (DstTy == MVT::i32 &&
7891       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7892     return std::make_pair(SDValue(), SDValue());
7893   if (Subtarget->is64Bit() &&
7894       DstTy == MVT::i64 &&
7895       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7896     return std::make_pair(SDValue(), SDValue());
7897
7898   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7899   // stack slot.
7900   MachineFunction &MF = DAG.getMachineFunction();
7901   unsigned MemSize = DstTy.getSizeInBits()/8;
7902   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7903   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7904
7905
7906
7907   unsigned Opc;
7908   switch (DstTy.getSimpleVT().SimpleTy) {
7909   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7910   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7911   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7912   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7913   }
7914
7915   SDValue Chain = DAG.getEntryNode();
7916   SDValue Value = Op.getOperand(0);
7917   EVT TheVT = Op.getOperand(0).getValueType();
7918   if (isScalarFPTypeInSSEReg(TheVT)) {
7919     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7920     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7921                          MachinePointerInfo::getFixedStack(SSFI),
7922                          false, false, 0);
7923     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7924     SDValue Ops[] = {
7925       Chain, StackSlot, DAG.getValueType(TheVT)
7926     };
7927
7928     MachineMemOperand *MMO =
7929       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7930                               MachineMemOperand::MOLoad, MemSize, MemSize);
7931     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7932                                     DstTy, MMO);
7933     Chain = Value.getValue(1);
7934     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7935     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7936   }
7937
7938   MachineMemOperand *MMO =
7939     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7940                             MachineMemOperand::MOStore, MemSize, MemSize);
7941
7942   // Build the FP_TO_INT*_IN_MEM
7943   SDValue Ops[] = { Chain, Value, StackSlot };
7944   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7945                                          Ops, 3, DstTy, MMO);
7946
7947   return std::make_pair(FIST, StackSlot);
7948 }
7949
7950 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7951                                            SelectionDAG &DAG) const {
7952   if (Op.getValueType().isVector())
7953     return SDValue();
7954
7955   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7956   SDValue FIST = Vals.first, StackSlot = Vals.second;
7957   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7958   if (FIST.getNode() == 0) return Op;
7959
7960   // Load the result.
7961   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7962                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7963 }
7964
7965 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7966                                            SelectionDAG &DAG) const {
7967   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7968   SDValue FIST = Vals.first, StackSlot = Vals.second;
7969   assert(FIST.getNode() && "Unexpected failure");
7970
7971   // Load the result.
7972   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7973                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7974 }
7975
7976 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7977                                      SelectionDAG &DAG) const {
7978   LLVMContext *Context = DAG.getContext();
7979   DebugLoc dl = Op.getDebugLoc();
7980   EVT VT = Op.getValueType();
7981   EVT EltVT = VT;
7982   if (VT.isVector())
7983     EltVT = VT.getVectorElementType();
7984   std::vector<Constant*> CV;
7985   if (EltVT == MVT::f64) {
7986     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7987     CV.push_back(C);
7988     CV.push_back(C);
7989   } else {
7990     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7991     CV.push_back(C);
7992     CV.push_back(C);
7993     CV.push_back(C);
7994     CV.push_back(C);
7995   }
7996   Constant *C = ConstantVector::get(CV);
7997   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7998   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7999                              MachinePointerInfo::getConstantPool(),
8000                              false, false, 16);
8001   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8002 }
8003
8004 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8005   LLVMContext *Context = DAG.getContext();
8006   DebugLoc dl = Op.getDebugLoc();
8007   EVT VT = Op.getValueType();
8008   EVT EltVT = VT;
8009   if (VT.isVector())
8010     EltVT = VT.getVectorElementType();
8011   std::vector<Constant*> CV;
8012   if (EltVT == MVT::f64) {
8013     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8014     CV.push_back(C);
8015     CV.push_back(C);
8016   } else {
8017     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8018     CV.push_back(C);
8019     CV.push_back(C);
8020     CV.push_back(C);
8021     CV.push_back(C);
8022   }
8023   Constant *C = ConstantVector::get(CV);
8024   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8025   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8026                              MachinePointerInfo::getConstantPool(),
8027                              false, false, 16);
8028   if (VT.isVector()) {
8029     return DAG.getNode(ISD::BITCAST, dl, VT,
8030                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8031                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8032                                 Op.getOperand(0)),
8033                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8034   } else {
8035     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8036   }
8037 }
8038
8039 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8040   LLVMContext *Context = DAG.getContext();
8041   SDValue Op0 = Op.getOperand(0);
8042   SDValue Op1 = Op.getOperand(1);
8043   DebugLoc dl = Op.getDebugLoc();
8044   EVT VT = Op.getValueType();
8045   EVT SrcVT = Op1.getValueType();
8046
8047   // If second operand is smaller, extend it first.
8048   if (SrcVT.bitsLT(VT)) {
8049     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8050     SrcVT = VT;
8051   }
8052   // And if it is bigger, shrink it first.
8053   if (SrcVT.bitsGT(VT)) {
8054     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8055     SrcVT = VT;
8056   }
8057
8058   // At this point the operands and the result should have the same
8059   // type, and that won't be f80 since that is not custom lowered.
8060
8061   // First get the sign bit of second operand.
8062   std::vector<Constant*> CV;
8063   if (SrcVT == MVT::f64) {
8064     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8065     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8066   } else {
8067     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8068     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8069     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8070     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8071   }
8072   Constant *C = ConstantVector::get(CV);
8073   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8074   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8075                               MachinePointerInfo::getConstantPool(),
8076                               false, false, 16);
8077   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8078
8079   // Shift sign bit right or left if the two operands have different types.
8080   if (SrcVT.bitsGT(VT)) {
8081     // Op0 is MVT::f32, Op1 is MVT::f64.
8082     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8083     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8084                           DAG.getConstant(32, MVT::i32));
8085     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8086     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8087                           DAG.getIntPtrConstant(0));
8088   }
8089
8090   // Clear first operand sign bit.
8091   CV.clear();
8092   if (VT == MVT::f64) {
8093     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8094     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8095   } else {
8096     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8097     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8098     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8099     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8100   }
8101   C = ConstantVector::get(CV);
8102   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8103   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8104                               MachinePointerInfo::getConstantPool(),
8105                               false, false, 16);
8106   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8107
8108   // Or the value with the sign bit.
8109   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8110 }
8111
8112 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8113   SDValue N0 = Op.getOperand(0);
8114   DebugLoc dl = Op.getDebugLoc();
8115   EVT VT = Op.getValueType();
8116
8117   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8118   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8119                                   DAG.getConstant(1, VT));
8120   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8121 }
8122
8123 /// Emit nodes that will be selected as "test Op0,Op0", or something
8124 /// equivalent.
8125 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8126                                     SelectionDAG &DAG) const {
8127   DebugLoc dl = Op.getDebugLoc();
8128
8129   // CF and OF aren't always set the way we want. Determine which
8130   // of these we need.
8131   bool NeedCF = false;
8132   bool NeedOF = false;
8133   switch (X86CC) {
8134   default: break;
8135   case X86::COND_A: case X86::COND_AE:
8136   case X86::COND_B: case X86::COND_BE:
8137     NeedCF = true;
8138     break;
8139   case X86::COND_G: case X86::COND_GE:
8140   case X86::COND_L: case X86::COND_LE:
8141   case X86::COND_O: case X86::COND_NO:
8142     NeedOF = true;
8143     break;
8144   }
8145
8146   // See if we can use the EFLAGS value from the operand instead of
8147   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8148   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8149   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8150     // Emit a CMP with 0, which is the TEST pattern.
8151     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8152                        DAG.getConstant(0, Op.getValueType()));
8153
8154   unsigned Opcode = 0;
8155   unsigned NumOperands = 0;
8156   switch (Op.getNode()->getOpcode()) {
8157   case ISD::ADD:
8158     // Due to an isel shortcoming, be conservative if this add is likely to be
8159     // selected as part of a load-modify-store instruction. When the root node
8160     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8161     // uses of other nodes in the match, such as the ADD in this case. This
8162     // leads to the ADD being left around and reselected, with the result being
8163     // two adds in the output.  Alas, even if none our users are stores, that
8164     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8165     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8166     // climbing the DAG back to the root, and it doesn't seem to be worth the
8167     // effort.
8168     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8169            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8170       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8171         goto default_case;
8172
8173     if (ConstantSDNode *C =
8174         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8175       // An add of one will be selected as an INC.
8176       if (C->getAPIntValue() == 1) {
8177         Opcode = X86ISD::INC;
8178         NumOperands = 1;
8179         break;
8180       }
8181
8182       // An add of negative one (subtract of one) will be selected as a DEC.
8183       if (C->getAPIntValue().isAllOnesValue()) {
8184         Opcode = X86ISD::DEC;
8185         NumOperands = 1;
8186         break;
8187       }
8188     }
8189
8190     // Otherwise use a regular EFLAGS-setting add.
8191     Opcode = X86ISD::ADD;
8192     NumOperands = 2;
8193     break;
8194   case ISD::AND: {
8195     // If the primary and result isn't used, don't bother using X86ISD::AND,
8196     // because a TEST instruction will be better.
8197     bool NonFlagUse = false;
8198     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8199            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8200       SDNode *User = *UI;
8201       unsigned UOpNo = UI.getOperandNo();
8202       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8203         // Look pass truncate.
8204         UOpNo = User->use_begin().getOperandNo();
8205         User = *User->use_begin();
8206       }
8207
8208       if (User->getOpcode() != ISD::BRCOND &&
8209           User->getOpcode() != ISD::SETCC &&
8210           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8211         NonFlagUse = true;
8212         break;
8213       }
8214     }
8215
8216     if (!NonFlagUse)
8217       break;
8218   }
8219     // FALL THROUGH
8220   case ISD::SUB:
8221   case ISD::OR:
8222   case ISD::XOR:
8223     // Due to the ISEL shortcoming noted above, be conservative if this op is
8224     // likely to be selected as part of a load-modify-store instruction.
8225     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8226            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8227       if (UI->getOpcode() == ISD::STORE)
8228         goto default_case;
8229
8230     // Otherwise use a regular EFLAGS-setting instruction.
8231     switch (Op.getNode()->getOpcode()) {
8232     default: llvm_unreachable("unexpected operator!");
8233     case ISD::SUB: Opcode = X86ISD::SUB; break;
8234     case ISD::OR:  Opcode = X86ISD::OR;  break;
8235     case ISD::XOR: Opcode = X86ISD::XOR; break;
8236     case ISD::AND: Opcode = X86ISD::AND; break;
8237     }
8238
8239     NumOperands = 2;
8240     break;
8241   case X86ISD::ADD:
8242   case X86ISD::SUB:
8243   case X86ISD::INC:
8244   case X86ISD::DEC:
8245   case X86ISD::OR:
8246   case X86ISD::XOR:
8247   case X86ISD::AND:
8248     return SDValue(Op.getNode(), 1);
8249   default:
8250   default_case:
8251     break;
8252   }
8253
8254   if (Opcode == 0)
8255     // Emit a CMP with 0, which is the TEST pattern.
8256     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8257                        DAG.getConstant(0, Op.getValueType()));
8258
8259   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8260   SmallVector<SDValue, 4> Ops;
8261   for (unsigned i = 0; i != NumOperands; ++i)
8262     Ops.push_back(Op.getOperand(i));
8263
8264   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8265   DAG.ReplaceAllUsesWith(Op, New);
8266   return SDValue(New.getNode(), 1);
8267 }
8268
8269 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8270 /// equivalent.
8271 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8272                                    SelectionDAG &DAG) const {
8273   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8274     if (C->getAPIntValue() == 0)
8275       return EmitTest(Op0, X86CC, DAG);
8276
8277   DebugLoc dl = Op0.getDebugLoc();
8278   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8279 }
8280
8281 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8282 /// if it's possible.
8283 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8284                                      DebugLoc dl, SelectionDAG &DAG) const {
8285   SDValue Op0 = And.getOperand(0);
8286   SDValue Op1 = And.getOperand(1);
8287   if (Op0.getOpcode() == ISD::TRUNCATE)
8288     Op0 = Op0.getOperand(0);
8289   if (Op1.getOpcode() == ISD::TRUNCATE)
8290     Op1 = Op1.getOperand(0);
8291
8292   SDValue LHS, RHS;
8293   if (Op1.getOpcode() == ISD::SHL)
8294     std::swap(Op0, Op1);
8295   if (Op0.getOpcode() == ISD::SHL) {
8296     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8297       if (And00C->getZExtValue() == 1) {
8298         // If we looked past a truncate, check that it's only truncating away
8299         // known zeros.
8300         unsigned BitWidth = Op0.getValueSizeInBits();
8301         unsigned AndBitWidth = And.getValueSizeInBits();
8302         if (BitWidth > AndBitWidth) {
8303           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8304           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8305           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8306             return SDValue();
8307         }
8308         LHS = Op1;
8309         RHS = Op0.getOperand(1);
8310       }
8311   } else if (Op1.getOpcode() == ISD::Constant) {
8312     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8313     SDValue AndLHS = Op0;
8314     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8315       LHS = AndLHS.getOperand(0);
8316       RHS = AndLHS.getOperand(1);
8317     }
8318   }
8319
8320   if (LHS.getNode()) {
8321     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8322     // instruction.  Since the shift amount is in-range-or-undefined, we know
8323     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8324     // the encoding for the i16 version is larger than the i32 version.
8325     // Also promote i16 to i32 for performance / code size reason.
8326     if (LHS.getValueType() == MVT::i8 ||
8327         LHS.getValueType() == MVT::i16)
8328       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8329
8330     // If the operand types disagree, extend the shift amount to match.  Since
8331     // BT ignores high bits (like shifts) we can use anyextend.
8332     if (LHS.getValueType() != RHS.getValueType())
8333       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8334
8335     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8336     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8337     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8338                        DAG.getConstant(Cond, MVT::i8), BT);
8339   }
8340
8341   return SDValue();
8342 }
8343
8344 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8345
8346   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8347
8348   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8349   SDValue Op0 = Op.getOperand(0);
8350   SDValue Op1 = Op.getOperand(1);
8351   DebugLoc dl = Op.getDebugLoc();
8352   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8353
8354   // Optimize to BT if possible.
8355   // Lower (X & (1 << N)) == 0 to BT(X, N).
8356   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8357   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8358   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8359       Op1.getOpcode() == ISD::Constant &&
8360       cast<ConstantSDNode>(Op1)->isNullValue() &&
8361       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8362     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8363     if (NewSetCC.getNode())
8364       return NewSetCC;
8365   }
8366
8367   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8368   // these.
8369   if (Op1.getOpcode() == ISD::Constant &&
8370       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8371        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8372       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8373
8374     // If the input is a setcc, then reuse the input setcc or use a new one with
8375     // the inverted condition.
8376     if (Op0.getOpcode() == X86ISD::SETCC) {
8377       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8378       bool Invert = (CC == ISD::SETNE) ^
8379         cast<ConstantSDNode>(Op1)->isNullValue();
8380       if (!Invert) return Op0;
8381
8382       CCode = X86::GetOppositeBranchCondition(CCode);
8383       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8384                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8385     }
8386   }
8387
8388   bool isFP = Op1.getValueType().isFloatingPoint();
8389   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8390   if (X86CC == X86::COND_INVALID)
8391     return SDValue();
8392
8393   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8394   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8395                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8396 }
8397
8398 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8399 // ones, and then concatenate the result back.
8400 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8401   EVT VT = Op.getValueType();
8402
8403   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8404          "Unsupported value type for operation");
8405
8406   int NumElems = VT.getVectorNumElements();
8407   DebugLoc dl = Op.getDebugLoc();
8408   SDValue CC = Op.getOperand(2);
8409   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8410   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8411
8412   // Extract the LHS vectors
8413   SDValue LHS = Op.getOperand(0);
8414   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8415   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8416
8417   // Extract the RHS vectors
8418   SDValue RHS = Op.getOperand(1);
8419   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8420   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8421
8422   // Issue the operation on the smaller types and concatenate the result back
8423   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8424   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8425   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8426                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8427                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8428 }
8429
8430
8431 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8432   SDValue Cond;
8433   SDValue Op0 = Op.getOperand(0);
8434   SDValue Op1 = Op.getOperand(1);
8435   SDValue CC = Op.getOperand(2);
8436   EVT VT = Op.getValueType();
8437   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8438   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8439   DebugLoc dl = Op.getDebugLoc();
8440
8441   if (isFP) {
8442     unsigned SSECC = 8;
8443     EVT EltVT = Op0.getValueType().getVectorElementType();
8444     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8445
8446     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8447     bool Swap = false;
8448
8449     // SSE Condition code mapping:
8450     //  0 - EQ
8451     //  1 - LT
8452     //  2 - LE
8453     //  3 - UNORD
8454     //  4 - NEQ
8455     //  5 - NLT
8456     //  6 - NLE
8457     //  7 - ORD
8458     switch (SetCCOpcode) {
8459     default: break;
8460     case ISD::SETOEQ:
8461     case ISD::SETEQ:  SSECC = 0; break;
8462     case ISD::SETOGT:
8463     case ISD::SETGT: Swap = true; // Fallthrough
8464     case ISD::SETLT:
8465     case ISD::SETOLT: SSECC = 1; break;
8466     case ISD::SETOGE:
8467     case ISD::SETGE: Swap = true; // Fallthrough
8468     case ISD::SETLE:
8469     case ISD::SETOLE: SSECC = 2; break;
8470     case ISD::SETUO:  SSECC = 3; break;
8471     case ISD::SETUNE:
8472     case ISD::SETNE:  SSECC = 4; break;
8473     case ISD::SETULE: Swap = true;
8474     case ISD::SETUGE: SSECC = 5; break;
8475     case ISD::SETULT: Swap = true;
8476     case ISD::SETUGT: SSECC = 6; break;
8477     case ISD::SETO:   SSECC = 7; break;
8478     }
8479     if (Swap)
8480       std::swap(Op0, Op1);
8481
8482     // In the two special cases we can't handle, emit two comparisons.
8483     if (SSECC == 8) {
8484       if (SetCCOpcode == ISD::SETUEQ) {
8485         SDValue UNORD, EQ;
8486         UNORD = DAG.getNode(Opc, dl, VT, Op1, Op0, DAG.getConstant(3, MVT::i8));
8487         EQ = DAG.getNode(Opc, dl, VT, Op1, Op0, DAG.getConstant(0, MVT::i8));
8488         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8489       }
8490       else if (SetCCOpcode == ISD::SETONE) {
8491         SDValue ORD, NEQ;
8492         ORD = DAG.getNode(Opc, dl, VT, Op1, Op0, DAG.getConstant(7, MVT::i8));
8493         NEQ = DAG.getNode(Opc, dl, VT, Op1, Op0, DAG.getConstant(4, MVT::i8));
8494         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8495       }
8496       llvm_unreachable("Illegal FP comparison");
8497     }
8498     // Handle all other FP comparisons here.
8499     return DAG.getNode(Opc, dl, VT, Op1, Op0, DAG.getConstant(SSECC, MVT::i8));
8500   }
8501
8502   // Break 256-bit integer vector compare into smaller ones.
8503   if (!isFP && VT.getSizeInBits() == 256)
8504     return Lower256IntVETCC(Op, DAG);
8505
8506   // We are handling one of the integer comparisons here.  Since SSE only has
8507   // GT and EQ comparisons for integer, swapping operands and multiple
8508   // operations may be required for some comparisons.
8509   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8510   bool Swap = false, Invert = false, FlipSigns = false;
8511
8512   switch (VT.getSimpleVT().SimpleTy) {
8513   default: break;
8514   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8515   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8516   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8517   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8518   }
8519
8520   switch (SetCCOpcode) {
8521   default: break;
8522   case ISD::SETNE:  Invert = true;
8523   case ISD::SETEQ:  Opc = EQOpc; break;
8524   case ISD::SETLT:  Swap = true;
8525   case ISD::SETGT:  Opc = GTOpc; break;
8526   case ISD::SETGE:  Swap = true;
8527   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8528   case ISD::SETULT: Swap = true;
8529   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8530   case ISD::SETUGE: Swap = true;
8531   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8532   }
8533   if (Swap)
8534     std::swap(Op0, Op1);
8535
8536   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8537   // bits of the inputs before performing those operations.
8538   if (FlipSigns) {
8539     EVT EltVT = VT.getVectorElementType();
8540     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8541                                       EltVT);
8542     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8543     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8544                                     SignBits.size());
8545     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8546     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8547   }
8548
8549   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8550
8551   // If the logical-not of the result is required, perform that now.
8552   if (Invert)
8553     Result = DAG.getNOT(dl, Result, VT);
8554
8555   return Result;
8556 }
8557
8558 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8559 static bool isX86LogicalCmp(SDValue Op) {
8560   unsigned Opc = Op.getNode()->getOpcode();
8561   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8562     return true;
8563   if (Op.getResNo() == 1 &&
8564       (Opc == X86ISD::ADD ||
8565        Opc == X86ISD::SUB ||
8566        Opc == X86ISD::ADC ||
8567        Opc == X86ISD::SBB ||
8568        Opc == X86ISD::SMUL ||
8569        Opc == X86ISD::UMUL ||
8570        Opc == X86ISD::INC ||
8571        Opc == X86ISD::DEC ||
8572        Opc == X86ISD::OR ||
8573        Opc == X86ISD::XOR ||
8574        Opc == X86ISD::AND))
8575     return true;
8576
8577   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8578     return true;
8579
8580   return false;
8581 }
8582
8583 static bool isZero(SDValue V) {
8584   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8585   return C && C->isNullValue();
8586 }
8587
8588 static bool isAllOnes(SDValue V) {
8589   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8590   return C && C->isAllOnesValue();
8591 }
8592
8593 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8594   bool addTest = true;
8595   SDValue Cond  = Op.getOperand(0);
8596   SDValue Op1 = Op.getOperand(1);
8597   SDValue Op2 = Op.getOperand(2);
8598   DebugLoc DL = Op.getDebugLoc();
8599   SDValue CC;
8600
8601   if (Cond.getOpcode() == ISD::SETCC) {
8602     SDValue NewCond = LowerSETCC(Cond, DAG);
8603     if (NewCond.getNode())
8604       Cond = NewCond;
8605   }
8606
8607   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8608   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8609   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8610   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8611   if (Cond.getOpcode() == X86ISD::SETCC &&
8612       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8613       isZero(Cond.getOperand(1).getOperand(1))) {
8614     SDValue Cmp = Cond.getOperand(1);
8615
8616     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8617
8618     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8619         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8620       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8621
8622       SDValue CmpOp0 = Cmp.getOperand(0);
8623       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8624                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8625
8626       SDValue Res =   // Res = 0 or -1.
8627         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8628                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8629
8630       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8631         Res = DAG.getNOT(DL, Res, Res.getValueType());
8632
8633       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8634       if (N2C == 0 || !N2C->isNullValue())
8635         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8636       return Res;
8637     }
8638   }
8639
8640   // Look past (and (setcc_carry (cmp ...)), 1).
8641   if (Cond.getOpcode() == ISD::AND &&
8642       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8643     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8644     if (C && C->getAPIntValue() == 1)
8645       Cond = Cond.getOperand(0);
8646   }
8647
8648   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8649   // setting operand in place of the X86ISD::SETCC.
8650   if (Cond.getOpcode() == X86ISD::SETCC ||
8651       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8652     CC = Cond.getOperand(0);
8653
8654     SDValue Cmp = Cond.getOperand(1);
8655     unsigned Opc = Cmp.getOpcode();
8656     EVT VT = Op.getValueType();
8657
8658     bool IllegalFPCMov = false;
8659     if (VT.isFloatingPoint() && !VT.isVector() &&
8660         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8661       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8662
8663     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8664         Opc == X86ISD::BT) { // FIXME
8665       Cond = Cmp;
8666       addTest = false;
8667     }
8668   }
8669
8670   if (addTest) {
8671     // Look pass the truncate.
8672     if (Cond.getOpcode() == ISD::TRUNCATE)
8673       Cond = Cond.getOperand(0);
8674
8675     // We know the result of AND is compared against zero. Try to match
8676     // it to BT.
8677     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8678       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8679       if (NewSetCC.getNode()) {
8680         CC = NewSetCC.getOperand(0);
8681         Cond = NewSetCC.getOperand(1);
8682         addTest = false;
8683       }
8684     }
8685   }
8686
8687   if (addTest) {
8688     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8689     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8690   }
8691
8692   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8693   // a <  b ?  0 : -1 -> RES = setcc_carry
8694   // a >= b ? -1 :  0 -> RES = setcc_carry
8695   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8696   if (Cond.getOpcode() == X86ISD::CMP) {
8697     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8698
8699     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8700         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8701       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8702                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8703       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8704         return DAG.getNOT(DL, Res, Res.getValueType());
8705       return Res;
8706     }
8707   }
8708
8709   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8710   // condition is true.
8711   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8712   SDValue Ops[] = { Op2, Op1, CC, Cond };
8713   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8714 }
8715
8716 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8717 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8718 // from the AND / OR.
8719 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8720   Opc = Op.getOpcode();
8721   if (Opc != ISD::OR && Opc != ISD::AND)
8722     return false;
8723   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8724           Op.getOperand(0).hasOneUse() &&
8725           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8726           Op.getOperand(1).hasOneUse());
8727 }
8728
8729 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8730 // 1 and that the SETCC node has a single use.
8731 static bool isXor1OfSetCC(SDValue Op) {
8732   if (Op.getOpcode() != ISD::XOR)
8733     return false;
8734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8735   if (N1C && N1C->getAPIntValue() == 1) {
8736     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8737       Op.getOperand(0).hasOneUse();
8738   }
8739   return false;
8740 }
8741
8742 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8743   bool addTest = true;
8744   SDValue Chain = Op.getOperand(0);
8745   SDValue Cond  = Op.getOperand(1);
8746   SDValue Dest  = Op.getOperand(2);
8747   DebugLoc dl = Op.getDebugLoc();
8748   SDValue CC;
8749
8750   if (Cond.getOpcode() == ISD::SETCC) {
8751     SDValue NewCond = LowerSETCC(Cond, DAG);
8752     if (NewCond.getNode())
8753       Cond = NewCond;
8754   }
8755 #if 0
8756   // FIXME: LowerXALUO doesn't handle these!!
8757   else if (Cond.getOpcode() == X86ISD::ADD  ||
8758            Cond.getOpcode() == X86ISD::SUB  ||
8759            Cond.getOpcode() == X86ISD::SMUL ||
8760            Cond.getOpcode() == X86ISD::UMUL)
8761     Cond = LowerXALUO(Cond, DAG);
8762 #endif
8763
8764   // Look pass (and (setcc_carry (cmp ...)), 1).
8765   if (Cond.getOpcode() == ISD::AND &&
8766       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8767     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8768     if (C && C->getAPIntValue() == 1)
8769       Cond = Cond.getOperand(0);
8770   }
8771
8772   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8773   // setting operand in place of the X86ISD::SETCC.
8774   if (Cond.getOpcode() == X86ISD::SETCC ||
8775       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8776     CC = Cond.getOperand(0);
8777
8778     SDValue Cmp = Cond.getOperand(1);
8779     unsigned Opc = Cmp.getOpcode();
8780     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8781     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8782       Cond = Cmp;
8783       addTest = false;
8784     } else {
8785       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8786       default: break;
8787       case X86::COND_O:
8788       case X86::COND_B:
8789         // These can only come from an arithmetic instruction with overflow,
8790         // e.g. SADDO, UADDO.
8791         Cond = Cond.getNode()->getOperand(1);
8792         addTest = false;
8793         break;
8794       }
8795     }
8796   } else {
8797     unsigned CondOpc;
8798     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8799       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8800       if (CondOpc == ISD::OR) {
8801         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8802         // two branches instead of an explicit OR instruction with a
8803         // separate test.
8804         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8805             isX86LogicalCmp(Cmp)) {
8806           CC = Cond.getOperand(0).getOperand(0);
8807           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8808                               Chain, Dest, CC, Cmp);
8809           CC = Cond.getOperand(1).getOperand(0);
8810           Cond = Cmp;
8811           addTest = false;
8812         }
8813       } else { // ISD::AND
8814         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8815         // two branches instead of an explicit AND instruction with a
8816         // separate test. However, we only do this if this block doesn't
8817         // have a fall-through edge, because this requires an explicit
8818         // jmp when the condition is false.
8819         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8820             isX86LogicalCmp(Cmp) &&
8821             Op.getNode()->hasOneUse()) {
8822           X86::CondCode CCode =
8823             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8824           CCode = X86::GetOppositeBranchCondition(CCode);
8825           CC = DAG.getConstant(CCode, MVT::i8);
8826           SDNode *User = *Op.getNode()->use_begin();
8827           // Look for an unconditional branch following this conditional branch.
8828           // We need this because we need to reverse the successors in order
8829           // to implement FCMP_OEQ.
8830           if (User->getOpcode() == ISD::BR) {
8831             SDValue FalseBB = User->getOperand(1);
8832             SDNode *NewBR =
8833               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8834             assert(NewBR == User);
8835             (void)NewBR;
8836             Dest = FalseBB;
8837
8838             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8839                                 Chain, Dest, CC, Cmp);
8840             X86::CondCode CCode =
8841               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8842             CCode = X86::GetOppositeBranchCondition(CCode);
8843             CC = DAG.getConstant(CCode, MVT::i8);
8844             Cond = Cmp;
8845             addTest = false;
8846           }
8847         }
8848       }
8849     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8850       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8851       // It should be transformed during dag combiner except when the condition
8852       // is set by a arithmetics with overflow node.
8853       X86::CondCode CCode =
8854         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8855       CCode = X86::GetOppositeBranchCondition(CCode);
8856       CC = DAG.getConstant(CCode, MVT::i8);
8857       Cond = Cond.getOperand(0).getOperand(1);
8858       addTest = false;
8859     }
8860   }
8861
8862   if (addTest) {
8863     // Look pass the truncate.
8864     if (Cond.getOpcode() == ISD::TRUNCATE)
8865       Cond = Cond.getOperand(0);
8866
8867     // We know the result of AND is compared against zero. Try to match
8868     // it to BT.
8869     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8870       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8871       if (NewSetCC.getNode()) {
8872         CC = NewSetCC.getOperand(0);
8873         Cond = NewSetCC.getOperand(1);
8874         addTest = false;
8875       }
8876     }
8877   }
8878
8879   if (addTest) {
8880     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8881     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8882   }
8883   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8884                      Chain, Dest, CC, Cond);
8885 }
8886
8887
8888 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8889 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8890 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8891 // that the guard pages used by the OS virtual memory manager are allocated in
8892 // correct sequence.
8893 SDValue
8894 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8895                                            SelectionDAG &DAG) const {
8896   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8897           EnableSegmentedStacks) &&
8898          "This should be used only on Windows targets or when segmented stacks "
8899          "are being used");
8900   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8901   DebugLoc dl = Op.getDebugLoc();
8902
8903   // Get the inputs.
8904   SDValue Chain = Op.getOperand(0);
8905   SDValue Size  = Op.getOperand(1);
8906   // FIXME: Ensure alignment here
8907
8908   bool Is64Bit = Subtarget->is64Bit();
8909   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8910
8911   if (EnableSegmentedStacks) {
8912     MachineFunction &MF = DAG.getMachineFunction();
8913     MachineRegisterInfo &MRI = MF.getRegInfo();
8914
8915     if (Is64Bit) {
8916       // The 64 bit implementation of segmented stacks needs to clobber both r10
8917       // r11. This makes it impossible to use it along with nested parameters.
8918       const Function *F = MF.getFunction();
8919
8920       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8921            I != E; I++)
8922         if (I->hasNestAttr())
8923           report_fatal_error("Cannot use segmented stacks with functions that "
8924                              "have nested arguments.");
8925     }
8926
8927     const TargetRegisterClass *AddrRegClass =
8928       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8929     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8930     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8931     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8932                                 DAG.getRegister(Vreg, SPTy));
8933     SDValue Ops1[2] = { Value, Chain };
8934     return DAG.getMergeValues(Ops1, 2, dl);
8935   } else {
8936     SDValue Flag;
8937     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8938
8939     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8940     Flag = Chain.getValue(1);
8941     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8942
8943     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8944     Flag = Chain.getValue(1);
8945
8946     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8947
8948     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8949     return DAG.getMergeValues(Ops1, 2, dl);
8950   }
8951 }
8952
8953 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8954   MachineFunction &MF = DAG.getMachineFunction();
8955   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8956
8957   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8958   DebugLoc DL = Op.getDebugLoc();
8959
8960   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8961     // vastart just stores the address of the VarArgsFrameIndex slot into the
8962     // memory location argument.
8963     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8964                                    getPointerTy());
8965     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8966                         MachinePointerInfo(SV), false, false, 0);
8967   }
8968
8969   // __va_list_tag:
8970   //   gp_offset         (0 - 6 * 8)
8971   //   fp_offset         (48 - 48 + 8 * 16)
8972   //   overflow_arg_area (point to parameters coming in memory).
8973   //   reg_save_area
8974   SmallVector<SDValue, 8> MemOps;
8975   SDValue FIN = Op.getOperand(1);
8976   // Store gp_offset
8977   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8978                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8979                                                MVT::i32),
8980                                FIN, MachinePointerInfo(SV), false, false, 0);
8981   MemOps.push_back(Store);
8982
8983   // Store fp_offset
8984   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8985                     FIN, DAG.getIntPtrConstant(4));
8986   Store = DAG.getStore(Op.getOperand(0), DL,
8987                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8988                                        MVT::i32),
8989                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8990   MemOps.push_back(Store);
8991
8992   // Store ptr to overflow_arg_area
8993   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8994                     FIN, DAG.getIntPtrConstant(4));
8995   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8996                                     getPointerTy());
8997   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8998                        MachinePointerInfo(SV, 8),
8999                        false, false, 0);
9000   MemOps.push_back(Store);
9001
9002   // Store ptr to reg_save_area.
9003   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9004                     FIN, DAG.getIntPtrConstant(8));
9005   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9006                                     getPointerTy());
9007   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9008                        MachinePointerInfo(SV, 16), false, false, 0);
9009   MemOps.push_back(Store);
9010   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9011                      &MemOps[0], MemOps.size());
9012 }
9013
9014 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9015   assert(Subtarget->is64Bit() &&
9016          "LowerVAARG only handles 64-bit va_arg!");
9017   assert((Subtarget->isTargetLinux() ||
9018           Subtarget->isTargetDarwin()) &&
9019           "Unhandled target in LowerVAARG");
9020   assert(Op.getNode()->getNumOperands() == 4);
9021   SDValue Chain = Op.getOperand(0);
9022   SDValue SrcPtr = Op.getOperand(1);
9023   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9024   unsigned Align = Op.getConstantOperandVal(3);
9025   DebugLoc dl = Op.getDebugLoc();
9026
9027   EVT ArgVT = Op.getNode()->getValueType(0);
9028   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9029   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9030   uint8_t ArgMode;
9031
9032   // Decide which area this value should be read from.
9033   // TODO: Implement the AMD64 ABI in its entirety. This simple
9034   // selection mechanism works only for the basic types.
9035   if (ArgVT == MVT::f80) {
9036     llvm_unreachable("va_arg for f80 not yet implemented");
9037   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9038     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9039   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9040     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9041   } else {
9042     llvm_unreachable("Unhandled argument type in LowerVAARG");
9043   }
9044
9045   if (ArgMode == 2) {
9046     // Sanity Check: Make sure using fp_offset makes sense.
9047     assert(!UseSoftFloat &&
9048            !(DAG.getMachineFunction()
9049                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9050            Subtarget->hasXMM());
9051   }
9052
9053   // Insert VAARG_64 node into the DAG
9054   // VAARG_64 returns two values: Variable Argument Address, Chain
9055   SmallVector<SDValue, 11> InstOps;
9056   InstOps.push_back(Chain);
9057   InstOps.push_back(SrcPtr);
9058   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9059   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9060   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9061   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9062   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9063                                           VTs, &InstOps[0], InstOps.size(),
9064                                           MVT::i64,
9065                                           MachinePointerInfo(SV),
9066                                           /*Align=*/0,
9067                                           /*Volatile=*/false,
9068                                           /*ReadMem=*/true,
9069                                           /*WriteMem=*/true);
9070   Chain = VAARG.getValue(1);
9071
9072   // Load the next argument and return it
9073   return DAG.getLoad(ArgVT, dl,
9074                      Chain,
9075                      VAARG,
9076                      MachinePointerInfo(),
9077                      false, false, 0);
9078 }
9079
9080 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9081   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9082   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9083   SDValue Chain = Op.getOperand(0);
9084   SDValue DstPtr = Op.getOperand(1);
9085   SDValue SrcPtr = Op.getOperand(2);
9086   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9087   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9088   DebugLoc DL = Op.getDebugLoc();
9089
9090   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9091                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9092                        false,
9093                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9094 }
9095
9096 SDValue
9097 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9098   DebugLoc dl = Op.getDebugLoc();
9099   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9100   switch (IntNo) {
9101   default: return SDValue();    // Don't custom lower most intrinsics.
9102   // Comparison intrinsics.
9103   case Intrinsic::x86_sse_comieq_ss:
9104   case Intrinsic::x86_sse_comilt_ss:
9105   case Intrinsic::x86_sse_comile_ss:
9106   case Intrinsic::x86_sse_comigt_ss:
9107   case Intrinsic::x86_sse_comige_ss:
9108   case Intrinsic::x86_sse_comineq_ss:
9109   case Intrinsic::x86_sse_ucomieq_ss:
9110   case Intrinsic::x86_sse_ucomilt_ss:
9111   case Intrinsic::x86_sse_ucomile_ss:
9112   case Intrinsic::x86_sse_ucomigt_ss:
9113   case Intrinsic::x86_sse_ucomige_ss:
9114   case Intrinsic::x86_sse_ucomineq_ss:
9115   case Intrinsic::x86_sse2_comieq_sd:
9116   case Intrinsic::x86_sse2_comilt_sd:
9117   case Intrinsic::x86_sse2_comile_sd:
9118   case Intrinsic::x86_sse2_comigt_sd:
9119   case Intrinsic::x86_sse2_comige_sd:
9120   case Intrinsic::x86_sse2_comineq_sd:
9121   case Intrinsic::x86_sse2_ucomieq_sd:
9122   case Intrinsic::x86_sse2_ucomilt_sd:
9123   case Intrinsic::x86_sse2_ucomile_sd:
9124   case Intrinsic::x86_sse2_ucomigt_sd:
9125   case Intrinsic::x86_sse2_ucomige_sd:
9126   case Intrinsic::x86_sse2_ucomineq_sd: {
9127     unsigned Opc = 0;
9128     ISD::CondCode CC = ISD::SETCC_INVALID;
9129     switch (IntNo) {
9130     default: break;
9131     case Intrinsic::x86_sse_comieq_ss:
9132     case Intrinsic::x86_sse2_comieq_sd:
9133       Opc = X86ISD::COMI;
9134       CC = ISD::SETEQ;
9135       break;
9136     case Intrinsic::x86_sse_comilt_ss:
9137     case Intrinsic::x86_sse2_comilt_sd:
9138       Opc = X86ISD::COMI;
9139       CC = ISD::SETLT;
9140       break;
9141     case Intrinsic::x86_sse_comile_ss:
9142     case Intrinsic::x86_sse2_comile_sd:
9143       Opc = X86ISD::COMI;
9144       CC = ISD::SETLE;
9145       break;
9146     case Intrinsic::x86_sse_comigt_ss:
9147     case Intrinsic::x86_sse2_comigt_sd:
9148       Opc = X86ISD::COMI;
9149       CC = ISD::SETGT;
9150       break;
9151     case Intrinsic::x86_sse_comige_ss:
9152     case Intrinsic::x86_sse2_comige_sd:
9153       Opc = X86ISD::COMI;
9154       CC = ISD::SETGE;
9155       break;
9156     case Intrinsic::x86_sse_comineq_ss:
9157     case Intrinsic::x86_sse2_comineq_sd:
9158       Opc = X86ISD::COMI;
9159       CC = ISD::SETNE;
9160       break;
9161     case Intrinsic::x86_sse_ucomieq_ss:
9162     case Intrinsic::x86_sse2_ucomieq_sd:
9163       Opc = X86ISD::UCOMI;
9164       CC = ISD::SETEQ;
9165       break;
9166     case Intrinsic::x86_sse_ucomilt_ss:
9167     case Intrinsic::x86_sse2_ucomilt_sd:
9168       Opc = X86ISD::UCOMI;
9169       CC = ISD::SETLT;
9170       break;
9171     case Intrinsic::x86_sse_ucomile_ss:
9172     case Intrinsic::x86_sse2_ucomile_sd:
9173       Opc = X86ISD::UCOMI;
9174       CC = ISD::SETLE;
9175       break;
9176     case Intrinsic::x86_sse_ucomigt_ss:
9177     case Intrinsic::x86_sse2_ucomigt_sd:
9178       Opc = X86ISD::UCOMI;
9179       CC = ISD::SETGT;
9180       break;
9181     case Intrinsic::x86_sse_ucomige_ss:
9182     case Intrinsic::x86_sse2_ucomige_sd:
9183       Opc = X86ISD::UCOMI;
9184       CC = ISD::SETGE;
9185       break;
9186     case Intrinsic::x86_sse_ucomineq_ss:
9187     case Intrinsic::x86_sse2_ucomineq_sd:
9188       Opc = X86ISD::UCOMI;
9189       CC = ISD::SETNE;
9190       break;
9191     }
9192
9193     SDValue LHS = Op.getOperand(1);
9194     SDValue RHS = Op.getOperand(2);
9195     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9196     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9197     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9198     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9199                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9200     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9201   }
9202   // ptest and testp intrinsics. The intrinsic these come from are designed to
9203   // return an integer value, not just an instruction so lower it to the ptest
9204   // or testp pattern and a setcc for the result.
9205   case Intrinsic::x86_sse41_ptestz:
9206   case Intrinsic::x86_sse41_ptestc:
9207   case Intrinsic::x86_sse41_ptestnzc:
9208   case Intrinsic::x86_avx_ptestz_256:
9209   case Intrinsic::x86_avx_ptestc_256:
9210   case Intrinsic::x86_avx_ptestnzc_256:
9211   case Intrinsic::x86_avx_vtestz_ps:
9212   case Intrinsic::x86_avx_vtestc_ps:
9213   case Intrinsic::x86_avx_vtestnzc_ps:
9214   case Intrinsic::x86_avx_vtestz_pd:
9215   case Intrinsic::x86_avx_vtestc_pd:
9216   case Intrinsic::x86_avx_vtestnzc_pd:
9217   case Intrinsic::x86_avx_vtestz_ps_256:
9218   case Intrinsic::x86_avx_vtestc_ps_256:
9219   case Intrinsic::x86_avx_vtestnzc_ps_256:
9220   case Intrinsic::x86_avx_vtestz_pd_256:
9221   case Intrinsic::x86_avx_vtestc_pd_256:
9222   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9223     bool IsTestPacked = false;
9224     unsigned X86CC = 0;
9225     switch (IntNo) {
9226     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9227     case Intrinsic::x86_avx_vtestz_ps:
9228     case Intrinsic::x86_avx_vtestz_pd:
9229     case Intrinsic::x86_avx_vtestz_ps_256:
9230     case Intrinsic::x86_avx_vtestz_pd_256:
9231       IsTestPacked = true; // Fallthrough
9232     case Intrinsic::x86_sse41_ptestz:
9233     case Intrinsic::x86_avx_ptestz_256:
9234       // ZF = 1
9235       X86CC = X86::COND_E;
9236       break;
9237     case Intrinsic::x86_avx_vtestc_ps:
9238     case Intrinsic::x86_avx_vtestc_pd:
9239     case Intrinsic::x86_avx_vtestc_ps_256:
9240     case Intrinsic::x86_avx_vtestc_pd_256:
9241       IsTestPacked = true; // Fallthrough
9242     case Intrinsic::x86_sse41_ptestc:
9243     case Intrinsic::x86_avx_ptestc_256:
9244       // CF = 1
9245       X86CC = X86::COND_B;
9246       break;
9247     case Intrinsic::x86_avx_vtestnzc_ps:
9248     case Intrinsic::x86_avx_vtestnzc_pd:
9249     case Intrinsic::x86_avx_vtestnzc_ps_256:
9250     case Intrinsic::x86_avx_vtestnzc_pd_256:
9251       IsTestPacked = true; // Fallthrough
9252     case Intrinsic::x86_sse41_ptestnzc:
9253     case Intrinsic::x86_avx_ptestnzc_256:
9254       // ZF and CF = 0
9255       X86CC = X86::COND_A;
9256       break;
9257     }
9258
9259     SDValue LHS = Op.getOperand(1);
9260     SDValue RHS = Op.getOperand(2);
9261     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9262     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9263     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9264     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9265     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9266   }
9267
9268   // Fix vector shift instructions where the last operand is a non-immediate
9269   // i32 value.
9270   case Intrinsic::x86_sse2_pslli_w:
9271   case Intrinsic::x86_sse2_pslli_d:
9272   case Intrinsic::x86_sse2_pslli_q:
9273   case Intrinsic::x86_sse2_psrli_w:
9274   case Intrinsic::x86_sse2_psrli_d:
9275   case Intrinsic::x86_sse2_psrli_q:
9276   case Intrinsic::x86_sse2_psrai_w:
9277   case Intrinsic::x86_sse2_psrai_d:
9278   case Intrinsic::x86_mmx_pslli_w:
9279   case Intrinsic::x86_mmx_pslli_d:
9280   case Intrinsic::x86_mmx_pslli_q:
9281   case Intrinsic::x86_mmx_psrli_w:
9282   case Intrinsic::x86_mmx_psrli_d:
9283   case Intrinsic::x86_mmx_psrli_q:
9284   case Intrinsic::x86_mmx_psrai_w:
9285   case Intrinsic::x86_mmx_psrai_d: {
9286     SDValue ShAmt = Op.getOperand(2);
9287     if (isa<ConstantSDNode>(ShAmt))
9288       return SDValue();
9289
9290     unsigned NewIntNo = 0;
9291     EVT ShAmtVT = MVT::v4i32;
9292     switch (IntNo) {
9293     case Intrinsic::x86_sse2_pslli_w:
9294       NewIntNo = Intrinsic::x86_sse2_psll_w;
9295       break;
9296     case Intrinsic::x86_sse2_pslli_d:
9297       NewIntNo = Intrinsic::x86_sse2_psll_d;
9298       break;
9299     case Intrinsic::x86_sse2_pslli_q:
9300       NewIntNo = Intrinsic::x86_sse2_psll_q;
9301       break;
9302     case Intrinsic::x86_sse2_psrli_w:
9303       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9304       break;
9305     case Intrinsic::x86_sse2_psrli_d:
9306       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9307       break;
9308     case Intrinsic::x86_sse2_psrli_q:
9309       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9310       break;
9311     case Intrinsic::x86_sse2_psrai_w:
9312       NewIntNo = Intrinsic::x86_sse2_psra_w;
9313       break;
9314     case Intrinsic::x86_sse2_psrai_d:
9315       NewIntNo = Intrinsic::x86_sse2_psra_d;
9316       break;
9317     default: {
9318       ShAmtVT = MVT::v2i32;
9319       switch (IntNo) {
9320       case Intrinsic::x86_mmx_pslli_w:
9321         NewIntNo = Intrinsic::x86_mmx_psll_w;
9322         break;
9323       case Intrinsic::x86_mmx_pslli_d:
9324         NewIntNo = Intrinsic::x86_mmx_psll_d;
9325         break;
9326       case Intrinsic::x86_mmx_pslli_q:
9327         NewIntNo = Intrinsic::x86_mmx_psll_q;
9328         break;
9329       case Intrinsic::x86_mmx_psrli_w:
9330         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9331         break;
9332       case Intrinsic::x86_mmx_psrli_d:
9333         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9334         break;
9335       case Intrinsic::x86_mmx_psrli_q:
9336         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9337         break;
9338       case Intrinsic::x86_mmx_psrai_w:
9339         NewIntNo = Intrinsic::x86_mmx_psra_w;
9340         break;
9341       case Intrinsic::x86_mmx_psrai_d:
9342         NewIntNo = Intrinsic::x86_mmx_psra_d;
9343         break;
9344       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9345       }
9346       break;
9347     }
9348     }
9349
9350     // The vector shift intrinsics with scalars uses 32b shift amounts but
9351     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9352     // to be zero.
9353     SDValue ShOps[4];
9354     ShOps[0] = ShAmt;
9355     ShOps[1] = DAG.getConstant(0, MVT::i32);
9356     if (ShAmtVT == MVT::v4i32) {
9357       ShOps[2] = DAG.getUNDEF(MVT::i32);
9358       ShOps[3] = DAG.getUNDEF(MVT::i32);
9359       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9360     } else {
9361       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9362 // FIXME this must be lowered to get rid of the invalid type.
9363     }
9364
9365     EVT VT = Op.getValueType();
9366     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9367     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9368                        DAG.getConstant(NewIntNo, MVT::i32),
9369                        Op.getOperand(1), ShAmt);
9370   }
9371   }
9372 }
9373
9374 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9375                                            SelectionDAG &DAG) const {
9376   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9377   MFI->setReturnAddressIsTaken(true);
9378
9379   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9380   DebugLoc dl = Op.getDebugLoc();
9381
9382   if (Depth > 0) {
9383     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9384     SDValue Offset =
9385       DAG.getConstant(TD->getPointerSize(),
9386                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9387     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9388                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9389                                    FrameAddr, Offset),
9390                        MachinePointerInfo(), false, false, 0);
9391   }
9392
9393   // Just load the return address.
9394   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9395   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9396                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9397 }
9398
9399 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9400   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9401   MFI->setFrameAddressIsTaken(true);
9402
9403   EVT VT = Op.getValueType();
9404   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9405   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9406   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9407   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9408   while (Depth--)
9409     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9410                             MachinePointerInfo(),
9411                             false, false, 0);
9412   return FrameAddr;
9413 }
9414
9415 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9416                                                      SelectionDAG &DAG) const {
9417   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9418 }
9419
9420 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9421   MachineFunction &MF = DAG.getMachineFunction();
9422   SDValue Chain     = Op.getOperand(0);
9423   SDValue Offset    = Op.getOperand(1);
9424   SDValue Handler   = Op.getOperand(2);
9425   DebugLoc dl       = Op.getDebugLoc();
9426
9427   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9428                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9429                                      getPointerTy());
9430   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9431
9432   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9433                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9434   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9435   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9436                        false, false, 0);
9437   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9438   MF.getRegInfo().addLiveOut(StoreAddrReg);
9439
9440   return DAG.getNode(X86ISD::EH_RETURN, dl,
9441                      MVT::Other,
9442                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9443 }
9444
9445 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9446                                                   SelectionDAG &DAG) const {
9447   return Op.getOperand(0);
9448 }
9449
9450 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9451                                                 SelectionDAG &DAG) const {
9452   SDValue Root = Op.getOperand(0);
9453   SDValue Trmp = Op.getOperand(1); // trampoline
9454   SDValue FPtr = Op.getOperand(2); // nested function
9455   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9456   DebugLoc dl  = Op.getDebugLoc();
9457
9458   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9459
9460   if (Subtarget->is64Bit()) {
9461     SDValue OutChains[6];
9462
9463     // Large code-model.
9464     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9465     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9466
9467     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9468     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9469
9470     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9471
9472     // Load the pointer to the nested function into R11.
9473     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9474     SDValue Addr = Trmp;
9475     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9476                                 Addr, MachinePointerInfo(TrmpAddr),
9477                                 false, false, 0);
9478
9479     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9480                        DAG.getConstant(2, MVT::i64));
9481     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9482                                 MachinePointerInfo(TrmpAddr, 2),
9483                                 false, false, 2);
9484
9485     // Load the 'nest' parameter value into R10.
9486     // R10 is specified in X86CallingConv.td
9487     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9488     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9489                        DAG.getConstant(10, MVT::i64));
9490     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9491                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9492                                 false, false, 0);
9493
9494     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9495                        DAG.getConstant(12, MVT::i64));
9496     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9497                                 MachinePointerInfo(TrmpAddr, 12),
9498                                 false, false, 2);
9499
9500     // Jump to the nested function.
9501     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9502     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9503                        DAG.getConstant(20, MVT::i64));
9504     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9505                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9506                                 false, false, 0);
9507
9508     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9509     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9510                        DAG.getConstant(22, MVT::i64));
9511     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9512                                 MachinePointerInfo(TrmpAddr, 22),
9513                                 false, false, 0);
9514
9515     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9516   } else {
9517     const Function *Func =
9518       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9519     CallingConv::ID CC = Func->getCallingConv();
9520     unsigned NestReg;
9521
9522     switch (CC) {
9523     default:
9524       llvm_unreachable("Unsupported calling convention");
9525     case CallingConv::C:
9526     case CallingConv::X86_StdCall: {
9527       // Pass 'nest' parameter in ECX.
9528       // Must be kept in sync with X86CallingConv.td
9529       NestReg = X86::ECX;
9530
9531       // Check that ECX wasn't needed by an 'inreg' parameter.
9532       FunctionType *FTy = Func->getFunctionType();
9533       const AttrListPtr &Attrs = Func->getAttributes();
9534
9535       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9536         unsigned InRegCount = 0;
9537         unsigned Idx = 1;
9538
9539         for (FunctionType::param_iterator I = FTy->param_begin(),
9540              E = FTy->param_end(); I != E; ++I, ++Idx)
9541           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9542             // FIXME: should only count parameters that are lowered to integers.
9543             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9544
9545         if (InRegCount > 2) {
9546           report_fatal_error("Nest register in use - reduce number of inreg"
9547                              " parameters!");
9548         }
9549       }
9550       break;
9551     }
9552     case CallingConv::X86_FastCall:
9553     case CallingConv::X86_ThisCall:
9554     case CallingConv::Fast:
9555       // Pass 'nest' parameter in EAX.
9556       // Must be kept in sync with X86CallingConv.td
9557       NestReg = X86::EAX;
9558       break;
9559     }
9560
9561     SDValue OutChains[4];
9562     SDValue Addr, Disp;
9563
9564     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9565                        DAG.getConstant(10, MVT::i32));
9566     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9567
9568     // This is storing the opcode for MOV32ri.
9569     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9570     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9571     OutChains[0] = DAG.getStore(Root, dl,
9572                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9573                                 Trmp, MachinePointerInfo(TrmpAddr),
9574                                 false, false, 0);
9575
9576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9577                        DAG.getConstant(1, MVT::i32));
9578     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9579                                 MachinePointerInfo(TrmpAddr, 1),
9580                                 false, false, 1);
9581
9582     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9583     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9584                        DAG.getConstant(5, MVT::i32));
9585     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9586                                 MachinePointerInfo(TrmpAddr, 5),
9587                                 false, false, 1);
9588
9589     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9590                        DAG.getConstant(6, MVT::i32));
9591     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9592                                 MachinePointerInfo(TrmpAddr, 6),
9593                                 false, false, 1);
9594
9595     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9596   }
9597 }
9598
9599 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9600                                             SelectionDAG &DAG) const {
9601   /*
9602    The rounding mode is in bits 11:10 of FPSR, and has the following
9603    settings:
9604      00 Round to nearest
9605      01 Round to -inf
9606      10 Round to +inf
9607      11 Round to 0
9608
9609   FLT_ROUNDS, on the other hand, expects the following:
9610     -1 Undefined
9611      0 Round to 0
9612      1 Round to nearest
9613      2 Round to +inf
9614      3 Round to -inf
9615
9616   To perform the conversion, we do:
9617     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9618   */
9619
9620   MachineFunction &MF = DAG.getMachineFunction();
9621   const TargetMachine &TM = MF.getTarget();
9622   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9623   unsigned StackAlignment = TFI.getStackAlignment();
9624   EVT VT = Op.getValueType();
9625   DebugLoc DL = Op.getDebugLoc();
9626
9627   // Save FP Control Word to stack slot
9628   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9629   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9630
9631
9632   MachineMemOperand *MMO =
9633    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9634                            MachineMemOperand::MOStore, 2, 2);
9635
9636   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9637   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9638                                           DAG.getVTList(MVT::Other),
9639                                           Ops, 2, MVT::i16, MMO);
9640
9641   // Load FP Control Word from stack slot
9642   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9643                             MachinePointerInfo(), false, false, 0);
9644
9645   // Transform as necessary
9646   SDValue CWD1 =
9647     DAG.getNode(ISD::SRL, DL, MVT::i16,
9648                 DAG.getNode(ISD::AND, DL, MVT::i16,
9649                             CWD, DAG.getConstant(0x800, MVT::i16)),
9650                 DAG.getConstant(11, MVT::i8));
9651   SDValue CWD2 =
9652     DAG.getNode(ISD::SRL, DL, MVT::i16,
9653                 DAG.getNode(ISD::AND, DL, MVT::i16,
9654                             CWD, DAG.getConstant(0x400, MVT::i16)),
9655                 DAG.getConstant(9, MVT::i8));
9656
9657   SDValue RetVal =
9658     DAG.getNode(ISD::AND, DL, MVT::i16,
9659                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9660                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9661                             DAG.getConstant(1, MVT::i16)),
9662                 DAG.getConstant(3, MVT::i16));
9663
9664
9665   return DAG.getNode((VT.getSizeInBits() < 16 ?
9666                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9667 }
9668
9669 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9670   EVT VT = Op.getValueType();
9671   EVT OpVT = VT;
9672   unsigned NumBits = VT.getSizeInBits();
9673   DebugLoc dl = Op.getDebugLoc();
9674
9675   Op = Op.getOperand(0);
9676   if (VT == MVT::i8) {
9677     // Zero extend to i32 since there is not an i8 bsr.
9678     OpVT = MVT::i32;
9679     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9680   }
9681
9682   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9683   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9684   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9685
9686   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9687   SDValue Ops[] = {
9688     Op,
9689     DAG.getConstant(NumBits+NumBits-1, OpVT),
9690     DAG.getConstant(X86::COND_E, MVT::i8),
9691     Op.getValue(1)
9692   };
9693   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9694
9695   // Finally xor with NumBits-1.
9696   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9697
9698   if (VT == MVT::i8)
9699     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9700   return Op;
9701 }
9702
9703 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9704   EVT VT = Op.getValueType();
9705   EVT OpVT = VT;
9706   unsigned NumBits = VT.getSizeInBits();
9707   DebugLoc dl = Op.getDebugLoc();
9708
9709   Op = Op.getOperand(0);
9710   if (VT == MVT::i8) {
9711     OpVT = MVT::i32;
9712     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9713   }
9714
9715   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9716   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9717   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9718
9719   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9720   SDValue Ops[] = {
9721     Op,
9722     DAG.getConstant(NumBits, OpVT),
9723     DAG.getConstant(X86::COND_E, MVT::i8),
9724     Op.getValue(1)
9725   };
9726   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9727
9728   if (VT == MVT::i8)
9729     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9730   return Op;
9731 }
9732
9733 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9734 // ones, and then concatenate the result back.
9735 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9736   EVT VT = Op.getValueType();
9737
9738   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9739          "Unsupported value type for operation");
9740
9741   int NumElems = VT.getVectorNumElements();
9742   DebugLoc dl = Op.getDebugLoc();
9743   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9744   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9745
9746   // Extract the LHS vectors
9747   SDValue LHS = Op.getOperand(0);
9748   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9749   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9750
9751   // Extract the RHS vectors
9752   SDValue RHS = Op.getOperand(1);
9753   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9754   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9755
9756   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9757   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9758
9759   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9760                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9761                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9762 }
9763
9764 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9765   assert(Op.getValueType().getSizeInBits() == 256 &&
9766          Op.getValueType().isInteger() &&
9767          "Only handle AVX 256-bit vector integer operation");
9768   return Lower256IntArith(Op, DAG);
9769 }
9770
9771 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9772   assert(Op.getValueType().getSizeInBits() == 256 &&
9773          Op.getValueType().isInteger() &&
9774          "Only handle AVX 256-bit vector integer operation");
9775   return Lower256IntArith(Op, DAG);
9776 }
9777
9778 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9779   EVT VT = Op.getValueType();
9780
9781   // Decompose 256-bit ops into smaller 128-bit ops.
9782   if (VT.getSizeInBits() == 256)
9783     return Lower256IntArith(Op, DAG);
9784
9785   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9786   DebugLoc dl = Op.getDebugLoc();
9787
9788   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9789   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9790   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9791   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9792   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9793   //
9794   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9795   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9796   //  return AloBlo + AloBhi + AhiBlo;
9797
9798   SDValue A = Op.getOperand(0);
9799   SDValue B = Op.getOperand(1);
9800
9801   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9802                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9803                        A, DAG.getConstant(32, MVT::i32));
9804   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9805                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9806                        B, DAG.getConstant(32, MVT::i32));
9807   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9808                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9809                        A, B);
9810   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9811                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9812                        A, Bhi);
9813   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9814                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9815                        Ahi, B);
9816   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9817                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9818                        AloBhi, DAG.getConstant(32, MVT::i32));
9819   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9820                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9821                        AhiBlo, DAG.getConstant(32, MVT::i32));
9822   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9823   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9824   return Res;
9825 }
9826
9827 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9828
9829   EVT VT = Op.getValueType();
9830   DebugLoc dl = Op.getDebugLoc();
9831   SDValue R = Op.getOperand(0);
9832   SDValue Amt = Op.getOperand(1);
9833   LLVMContext *Context = DAG.getContext();
9834
9835   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9836     return SDValue();
9837
9838   // Decompose 256-bit shifts into smaller 128-bit shifts.
9839   if (VT.getSizeInBits() == 256) {
9840     int NumElems = VT.getVectorNumElements();
9841     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9842     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9843
9844     // Extract the two vectors
9845     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9846     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9847                                      DAG, dl);
9848
9849     // Recreate the shift amount vectors
9850     SDValue Amt1, Amt2;
9851     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9852       // Constant shift amount
9853       SmallVector<SDValue, 4> Amt1Csts;
9854       SmallVector<SDValue, 4> Amt2Csts;
9855       for (int i = 0; i < NumElems/2; ++i)
9856         Amt1Csts.push_back(Amt->getOperand(i));
9857       for (int i = NumElems/2; i < NumElems; ++i)
9858         Amt2Csts.push_back(Amt->getOperand(i));
9859
9860       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9861                                  &Amt1Csts[0], NumElems/2);
9862       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9863                                  &Amt2Csts[0], NumElems/2);
9864     } else {
9865       // Variable shift amount
9866       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9867       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9868                                  DAG, dl);
9869     }
9870
9871     // Issue new vector shifts for the smaller types
9872     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9873     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9874
9875     // Concatenate the result back
9876     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9877   }
9878
9879   // Optimize shl/srl/sra with constant shift amount.
9880   if (isSplatVector(Amt.getNode())) {
9881     SDValue SclrAmt = Amt->getOperand(0);
9882     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9883       uint64_t ShiftAmt = C->getZExtValue();
9884
9885       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9886        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9887                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9888                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9889
9890       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9891        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9892                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9893                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9894
9895       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9896        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9897                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9898                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9899
9900       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9901        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9902                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9903                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9904
9905       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9906        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9907                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9908                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9909
9910       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9911        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9912                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9913                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9914
9915       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9916        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9917                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9918                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9919
9920       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9921        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9922                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9923                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9924     }
9925   }
9926
9927   // Lower SHL with variable shift amount.
9928   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9929     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9930                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9931                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9932
9933     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9934
9935     std::vector<Constant*> CV(4, CI);
9936     Constant *C = ConstantVector::get(CV);
9937     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9938     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9939                                  MachinePointerInfo::getConstantPool(),
9940                                  false, false, 16);
9941
9942     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9943     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9944     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9945     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9946   }
9947   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9948     // a = a << 5;
9949     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9950                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9951                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9952
9953     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9954     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9955
9956     std::vector<Constant*> CVM1(16, CM1);
9957     std::vector<Constant*> CVM2(16, CM2);
9958     Constant *C = ConstantVector::get(CVM1);
9959     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9960     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9961                             MachinePointerInfo::getConstantPool(),
9962                             false, false, 16);
9963
9964     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9965     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9966     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9967                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9968                     DAG.getConstant(4, MVT::i32));
9969     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9970     // a += a
9971     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9972
9973     C = ConstantVector::get(CVM2);
9974     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9975     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9976                     MachinePointerInfo::getConstantPool(),
9977                     false, false, 16);
9978
9979     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9980     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9981     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9982                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9983                     DAG.getConstant(2, MVT::i32));
9984     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9985     // a += a
9986     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9987
9988     // return pblendv(r, r+r, a);
9989     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
9990                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
9991     return R;
9992   }
9993   return SDValue();
9994 }
9995
9996 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9997   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9998   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9999   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10000   // has only one use.
10001   SDNode *N = Op.getNode();
10002   SDValue LHS = N->getOperand(0);
10003   SDValue RHS = N->getOperand(1);
10004   unsigned BaseOp = 0;
10005   unsigned Cond = 0;
10006   DebugLoc DL = Op.getDebugLoc();
10007   switch (Op.getOpcode()) {
10008   default: llvm_unreachable("Unknown ovf instruction!");
10009   case ISD::SADDO:
10010     // A subtract of one will be selected as a INC. Note that INC doesn't
10011     // set CF, so we can't do this for UADDO.
10012     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10013       if (C->isOne()) {
10014         BaseOp = X86ISD::INC;
10015         Cond = X86::COND_O;
10016         break;
10017       }
10018     BaseOp = X86ISD::ADD;
10019     Cond = X86::COND_O;
10020     break;
10021   case ISD::UADDO:
10022     BaseOp = X86ISD::ADD;
10023     Cond = X86::COND_B;
10024     break;
10025   case ISD::SSUBO:
10026     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10027     // set CF, so we can't do this for USUBO.
10028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10029       if (C->isOne()) {
10030         BaseOp = X86ISD::DEC;
10031         Cond = X86::COND_O;
10032         break;
10033       }
10034     BaseOp = X86ISD::SUB;
10035     Cond = X86::COND_O;
10036     break;
10037   case ISD::USUBO:
10038     BaseOp = X86ISD::SUB;
10039     Cond = X86::COND_B;
10040     break;
10041   case ISD::SMULO:
10042     BaseOp = X86ISD::SMUL;
10043     Cond = X86::COND_O;
10044     break;
10045   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10046     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10047                                  MVT::i32);
10048     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10049
10050     SDValue SetCC =
10051       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10052                   DAG.getConstant(X86::COND_O, MVT::i32),
10053                   SDValue(Sum.getNode(), 2));
10054
10055     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10056   }
10057   }
10058
10059   // Also sets EFLAGS.
10060   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10061   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10062
10063   SDValue SetCC =
10064     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10065                 DAG.getConstant(Cond, MVT::i32),
10066                 SDValue(Sum.getNode(), 1));
10067
10068   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10069 }
10070
10071 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10072   DebugLoc dl = Op.getDebugLoc();
10073   SDNode* Node = Op.getNode();
10074   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10075   EVT VT = Node->getValueType(0);
10076   if (Subtarget->hasSSE2() && VT.isVector()) {
10077     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10078                         ExtraVT.getScalarType().getSizeInBits();
10079     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10080
10081     unsigned SHLIntrinsicsID = 0;
10082     unsigned SRAIntrinsicsID = 0;
10083     switch (VT.getSimpleVT().SimpleTy) {
10084       default:
10085         return SDValue();
10086       case MVT::v2i64: {
10087         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10088         SRAIntrinsicsID = 0;
10089         break;
10090       }
10091       case MVT::v4i32: {
10092         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10093         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10094         break;
10095       }
10096       case MVT::v8i16: {
10097         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10098         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10099         break;
10100       }
10101     }
10102
10103     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10104                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10105                          Node->getOperand(0), ShAmt);
10106
10107     // In case of 1 bit sext, no need to shr
10108     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10109
10110     if (SRAIntrinsicsID) {
10111       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10112                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10113                          Tmp1, ShAmt);
10114     }
10115     return Tmp1;
10116   }
10117
10118   return SDValue();
10119 }
10120
10121
10122 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10123   DebugLoc dl = Op.getDebugLoc();
10124
10125   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10126   // There isn't any reason to disable it if the target processor supports it.
10127   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10128     SDValue Chain = Op.getOperand(0);
10129     SDValue Zero = DAG.getConstant(0, MVT::i32);
10130     SDValue Ops[] = {
10131       DAG.getRegister(X86::ESP, MVT::i32), // Base
10132       DAG.getTargetConstant(1, MVT::i8),   // Scale
10133       DAG.getRegister(0, MVT::i32),        // Index
10134       DAG.getTargetConstant(0, MVT::i32),  // Disp
10135       DAG.getRegister(0, MVT::i32),        // Segment.
10136       Zero,
10137       Chain
10138     };
10139     SDNode *Res =
10140       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10141                           array_lengthof(Ops));
10142     return SDValue(Res, 0);
10143   }
10144
10145   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10146   if (!isDev)
10147     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10148
10149   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10150   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10151   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10152   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10153
10154   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10155   if (!Op1 && !Op2 && !Op3 && Op4)
10156     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10157
10158   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10159   if (Op1 && !Op2 && !Op3 && !Op4)
10160     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10161
10162   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10163   //           (MFENCE)>;
10164   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10165 }
10166
10167 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10168                                              SelectionDAG &DAG) const {
10169   DebugLoc dl = Op.getDebugLoc();
10170   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10171     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10172   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10173     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10174
10175   // The only fence that needs an instruction is a sequentially-consistent
10176   // cross-thread fence.
10177   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10178     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10179     // no-sse2). There isn't any reason to disable it if the target processor
10180     // supports it.
10181     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10182       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10183
10184     SDValue Chain = Op.getOperand(0);
10185     SDValue Zero = DAG.getConstant(0, MVT::i32);
10186     SDValue Ops[] = {
10187       DAG.getRegister(X86::ESP, MVT::i32), // Base
10188       DAG.getTargetConstant(1, MVT::i8),   // Scale
10189       DAG.getRegister(0, MVT::i32),        // Index
10190       DAG.getTargetConstant(0, MVT::i32),  // Disp
10191       DAG.getRegister(0, MVT::i32),        // Segment.
10192       Zero,
10193       Chain
10194     };
10195     SDNode *Res =
10196       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10197                          array_lengthof(Ops));
10198     return SDValue(Res, 0);
10199   }
10200
10201   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10202   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10203 }
10204
10205
10206 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10207   EVT T = Op.getValueType();
10208   DebugLoc DL = Op.getDebugLoc();
10209   unsigned Reg = 0;
10210   unsigned size = 0;
10211   switch(T.getSimpleVT().SimpleTy) {
10212   default:
10213     assert(false && "Invalid value type!");
10214   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10215   case MVT::i16: Reg = X86::AX;  size = 2; break;
10216   case MVT::i32: Reg = X86::EAX; size = 4; break;
10217   case MVT::i64:
10218     assert(Subtarget->is64Bit() && "Node not type legal!");
10219     Reg = X86::RAX; size = 8;
10220     break;
10221   }
10222   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10223                                     Op.getOperand(2), SDValue());
10224   SDValue Ops[] = { cpIn.getValue(0),
10225                     Op.getOperand(1),
10226                     Op.getOperand(3),
10227                     DAG.getTargetConstant(size, MVT::i8),
10228                     cpIn.getValue(1) };
10229   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10230   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10231   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10232                                            Ops, 5, T, MMO);
10233   SDValue cpOut =
10234     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10235   return cpOut;
10236 }
10237
10238 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10239                                                  SelectionDAG &DAG) const {
10240   assert(Subtarget->is64Bit() && "Result not type legalized?");
10241   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10242   SDValue TheChain = Op.getOperand(0);
10243   DebugLoc dl = Op.getDebugLoc();
10244   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10245   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10246   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10247                                    rax.getValue(2));
10248   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10249                             DAG.getConstant(32, MVT::i8));
10250   SDValue Ops[] = {
10251     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10252     rdx.getValue(1)
10253   };
10254   return DAG.getMergeValues(Ops, 2, dl);
10255 }
10256
10257 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10258                                             SelectionDAG &DAG) const {
10259   EVT SrcVT = Op.getOperand(0).getValueType();
10260   EVT DstVT = Op.getValueType();
10261   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10262          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10263   assert((DstVT == MVT::i64 ||
10264           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10265          "Unexpected custom BITCAST");
10266   // i64 <=> MMX conversions are Legal.
10267   if (SrcVT==MVT::i64 && DstVT.isVector())
10268     return Op;
10269   if (DstVT==MVT::i64 && SrcVT.isVector())
10270     return Op;
10271   // MMX <=> MMX conversions are Legal.
10272   if (SrcVT.isVector() && DstVT.isVector())
10273     return Op;
10274   // All other conversions need to be expanded.
10275   return SDValue();
10276 }
10277
10278 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10279   SDNode *Node = Op.getNode();
10280   DebugLoc dl = Node->getDebugLoc();
10281   EVT T = Node->getValueType(0);
10282   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10283                               DAG.getConstant(0, T), Node->getOperand(2));
10284   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10285                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10286                        Node->getOperand(0),
10287                        Node->getOperand(1), negOp,
10288                        cast<AtomicSDNode>(Node)->getSrcValue(),
10289                        cast<AtomicSDNode>(Node)->getAlignment(),
10290                        cast<AtomicSDNode>(Node)->getOrdering(),
10291                        cast<AtomicSDNode>(Node)->getSynchScope());
10292 }
10293
10294 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10295   SDNode *Node = Op.getNode();
10296   DebugLoc dl = Node->getDebugLoc();
10297   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10298
10299   // Convert seq_cst store -> xchg
10300   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10301   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10302   //        (The only way to get a 16-byte store is cmpxchg16b)
10303   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10304   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10305       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10306     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10307                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10308                                  Node->getOperand(0),
10309                                  Node->getOperand(1), Node->getOperand(2),
10310                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10311                                  cast<AtomicSDNode>(Node)->getOrdering(),
10312                                  cast<AtomicSDNode>(Node)->getSynchScope());
10313     return Swap.getValue(1);
10314   }
10315   // Other atomic stores have a simple pattern.
10316   return Op;
10317 }
10318
10319 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10320   EVT VT = Op.getNode()->getValueType(0);
10321
10322   // Let legalize expand this if it isn't a legal type yet.
10323   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10324     return SDValue();
10325
10326   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10327
10328   unsigned Opc;
10329   bool ExtraOp = false;
10330   switch (Op.getOpcode()) {
10331   default: assert(0 && "Invalid code");
10332   case ISD::ADDC: Opc = X86ISD::ADD; break;
10333   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10334   case ISD::SUBC: Opc = X86ISD::SUB; break;
10335   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10336   }
10337
10338   if (!ExtraOp)
10339     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10340                        Op.getOperand(1));
10341   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10342                      Op.getOperand(1), Op.getOperand(2));
10343 }
10344
10345 /// LowerOperation - Provide custom lowering hooks for some operations.
10346 ///
10347 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10348   switch (Op.getOpcode()) {
10349   default: llvm_unreachable("Should not custom lower this!");
10350   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10351   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10352   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10353   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10354   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10355   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10356   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10357   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10358   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10359   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10360   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10361   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10362   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10363   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10364   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10365   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10366   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10367   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10368   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10369   case ISD::SHL_PARTS:
10370   case ISD::SRA_PARTS:
10371   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10372   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10373   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10374   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10375   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10376   case ISD::FABS:               return LowerFABS(Op, DAG);
10377   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10378   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10379   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10380   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10381   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10382   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10383   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10384   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10385   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10386   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10387   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10388   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10389   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10390   case ISD::FRAME_TO_ARGS_OFFSET:
10391                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10392   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10393   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10394   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10395   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10396   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10397   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10398   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10399   case ISD::MUL:                return LowerMUL(Op, DAG);
10400   case ISD::SRA:
10401   case ISD::SRL:
10402   case ISD::SHL:                return LowerShift(Op, DAG);
10403   case ISD::SADDO:
10404   case ISD::UADDO:
10405   case ISD::SSUBO:
10406   case ISD::USUBO:
10407   case ISD::SMULO:
10408   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10409   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10410   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10411   case ISD::ADDC:
10412   case ISD::ADDE:
10413   case ISD::SUBC:
10414   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10415   case ISD::ADD:                return LowerADD(Op, DAG);
10416   case ISD::SUB:                return LowerSUB(Op, DAG);
10417   }
10418 }
10419
10420 static void ReplaceATOMIC_LOAD(SDNode *Node,
10421                                   SmallVectorImpl<SDValue> &Results,
10422                                   SelectionDAG &DAG) {
10423   DebugLoc dl = Node->getDebugLoc();
10424   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10425
10426   // Convert wide load -> cmpxchg8b/cmpxchg16b
10427   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10428   //        (The only way to get a 16-byte load is cmpxchg16b)
10429   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10430   SDValue Zero = DAG.getConstant(0, VT);
10431   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10432                                Node->getOperand(0),
10433                                Node->getOperand(1), Zero, Zero,
10434                                cast<AtomicSDNode>(Node)->getMemOperand(),
10435                                cast<AtomicSDNode>(Node)->getOrdering(),
10436                                cast<AtomicSDNode>(Node)->getSynchScope());
10437   Results.push_back(Swap.getValue(0));
10438   Results.push_back(Swap.getValue(1));
10439 }
10440
10441 void X86TargetLowering::
10442 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10443                         SelectionDAG &DAG, unsigned NewOp) const {
10444   EVT T = Node->getValueType(0);
10445   DebugLoc dl = Node->getDebugLoc();
10446   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10447
10448   SDValue Chain = Node->getOperand(0);
10449   SDValue In1 = Node->getOperand(1);
10450   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10451                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10452   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10453                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10454   SDValue Ops[] = { Chain, In1, In2L, In2H };
10455   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10456   SDValue Result =
10457     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10458                             cast<MemSDNode>(Node)->getMemOperand());
10459   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10460   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10461   Results.push_back(Result.getValue(2));
10462 }
10463
10464 /// ReplaceNodeResults - Replace a node with an illegal result type
10465 /// with a new node built out of custom code.
10466 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10467                                            SmallVectorImpl<SDValue>&Results,
10468                                            SelectionDAG &DAG) const {
10469   DebugLoc dl = N->getDebugLoc();
10470   switch (N->getOpcode()) {
10471   default:
10472     assert(false && "Do not know how to custom type legalize this operation!");
10473     return;
10474   case ISD::SIGN_EXTEND_INREG:
10475   case ISD::ADDC:
10476   case ISD::ADDE:
10477   case ISD::SUBC:
10478   case ISD::SUBE:
10479     // We don't want to expand or promote these.
10480     return;
10481   case ISD::FP_TO_SINT: {
10482     std::pair<SDValue,SDValue> Vals =
10483         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10484     SDValue FIST = Vals.first, StackSlot = Vals.second;
10485     if (FIST.getNode() != 0) {
10486       EVT VT = N->getValueType(0);
10487       // Return a load from the stack slot.
10488       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10489                                     MachinePointerInfo(), false, false, 0));
10490     }
10491     return;
10492   }
10493   case ISD::READCYCLECOUNTER: {
10494     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10495     SDValue TheChain = N->getOperand(0);
10496     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10497     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10498                                      rd.getValue(1));
10499     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10500                                      eax.getValue(2));
10501     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10502     SDValue Ops[] = { eax, edx };
10503     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10504     Results.push_back(edx.getValue(1));
10505     return;
10506   }
10507   case ISD::ATOMIC_CMP_SWAP: {
10508     EVT T = N->getValueType(0);
10509     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10510     bool Regs64bit = T == MVT::i128;
10511     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10512     SDValue cpInL, cpInH;
10513     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10514                         DAG.getConstant(0, HalfT));
10515     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10516                         DAG.getConstant(1, HalfT));
10517     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10518                              Regs64bit ? X86::RAX : X86::EAX,
10519                              cpInL, SDValue());
10520     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10521                              Regs64bit ? X86::RDX : X86::EDX,
10522                              cpInH, cpInL.getValue(1));
10523     SDValue swapInL, swapInH;
10524     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10525                           DAG.getConstant(0, HalfT));
10526     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10527                           DAG.getConstant(1, HalfT));
10528     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10529                                Regs64bit ? X86::RBX : X86::EBX,
10530                                swapInL, cpInH.getValue(1));
10531     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10532                                Regs64bit ? X86::RCX : X86::ECX, 
10533                                swapInH, swapInL.getValue(1));
10534     SDValue Ops[] = { swapInH.getValue(0),
10535                       N->getOperand(1),
10536                       swapInH.getValue(1) };
10537     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10538     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10539     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10540                                   X86ISD::LCMPXCHG8_DAG;
10541     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10542                                              Ops, 3, T, MMO);
10543     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10544                                         Regs64bit ? X86::RAX : X86::EAX,
10545                                         HalfT, Result.getValue(1));
10546     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10547                                         Regs64bit ? X86::RDX : X86::EDX,
10548                                         HalfT, cpOutL.getValue(2));
10549     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10550     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10551     Results.push_back(cpOutH.getValue(1));
10552     return;
10553   }
10554   case ISD::ATOMIC_LOAD_ADD:
10555     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10556     return;
10557   case ISD::ATOMIC_LOAD_AND:
10558     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10559     return;
10560   case ISD::ATOMIC_LOAD_NAND:
10561     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10562     return;
10563   case ISD::ATOMIC_LOAD_OR:
10564     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10565     return;
10566   case ISD::ATOMIC_LOAD_SUB:
10567     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10568     return;
10569   case ISD::ATOMIC_LOAD_XOR:
10570     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10571     return;
10572   case ISD::ATOMIC_SWAP:
10573     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10574     return;
10575   case ISD::ATOMIC_LOAD:
10576     ReplaceATOMIC_LOAD(N, Results, DAG);
10577   }
10578 }
10579
10580 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10581   switch (Opcode) {
10582   default: return NULL;
10583   case X86ISD::BSF:                return "X86ISD::BSF";
10584   case X86ISD::BSR:                return "X86ISD::BSR";
10585   case X86ISD::SHLD:               return "X86ISD::SHLD";
10586   case X86ISD::SHRD:               return "X86ISD::SHRD";
10587   case X86ISD::FAND:               return "X86ISD::FAND";
10588   case X86ISD::FOR:                return "X86ISD::FOR";
10589   case X86ISD::FXOR:               return "X86ISD::FXOR";
10590   case X86ISD::FSRL:               return "X86ISD::FSRL";
10591   case X86ISD::FILD:               return "X86ISD::FILD";
10592   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10593   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10594   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10595   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10596   case X86ISD::FLD:                return "X86ISD::FLD";
10597   case X86ISD::FST:                return "X86ISD::FST";
10598   case X86ISD::CALL:               return "X86ISD::CALL";
10599   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10600   case X86ISD::BT:                 return "X86ISD::BT";
10601   case X86ISD::CMP:                return "X86ISD::CMP";
10602   case X86ISD::COMI:               return "X86ISD::COMI";
10603   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10604   case X86ISD::SETCC:              return "X86ISD::SETCC";
10605   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10606   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10607   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10608   case X86ISD::CMOV:               return "X86ISD::CMOV";
10609   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10610   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10611   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10612   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10613   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10614   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10615   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10616   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10617   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10618   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10619   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10620   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10621   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10622   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10623   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10624   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10625   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10626   case X86ISD::FMAX:               return "X86ISD::FMAX";
10627   case X86ISD::FMIN:               return "X86ISD::FMIN";
10628   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10629   case X86ISD::FRCP:               return "X86ISD::FRCP";
10630   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10631   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10632   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10633   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10634   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10635   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10636   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10637   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10638   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10639   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10640   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10641   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10642   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10643   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10644   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10645   case X86ISD::VSHL:               return "X86ISD::VSHL";
10646   case X86ISD::VSRL:               return "X86ISD::VSRL";
10647   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10648   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10649   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10650   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10651   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10652   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10653   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10654   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10655   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10656   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10657   case X86ISD::ADD:                return "X86ISD::ADD";
10658   case X86ISD::SUB:                return "X86ISD::SUB";
10659   case X86ISD::ADC:                return "X86ISD::ADC";
10660   case X86ISD::SBB:                return "X86ISD::SBB";
10661   case X86ISD::SMUL:               return "X86ISD::SMUL";
10662   case X86ISD::UMUL:               return "X86ISD::UMUL";
10663   case X86ISD::INC:                return "X86ISD::INC";
10664   case X86ISD::DEC:                return "X86ISD::DEC";
10665   case X86ISD::OR:                 return "X86ISD::OR";
10666   case X86ISD::XOR:                return "X86ISD::XOR";
10667   case X86ISD::AND:                return "X86ISD::AND";
10668   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10669   case X86ISD::PTEST:              return "X86ISD::PTEST";
10670   case X86ISD::TESTP:              return "X86ISD::TESTP";
10671   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10672   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10673   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10674   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10675   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10676   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10677   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10678   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10679   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10680   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10681   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10682   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10683   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10684   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10685   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10686   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10687   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10688   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10689   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10690   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10691   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10692   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10693   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10694   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10695   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10696   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10697   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10698   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10699   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10700   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10701   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10702   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10703   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10704   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10705   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10706   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10707   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10708   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10709   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10710   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10711   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10712   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10713   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10714   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10715   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10716   }
10717 }
10718
10719 // isLegalAddressingMode - Return true if the addressing mode represented
10720 // by AM is legal for this target, for a load/store of the specified type.
10721 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10722                                               Type *Ty) const {
10723   // X86 supports extremely general addressing modes.
10724   CodeModel::Model M = getTargetMachine().getCodeModel();
10725   Reloc::Model R = getTargetMachine().getRelocationModel();
10726
10727   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10728   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10729     return false;
10730
10731   if (AM.BaseGV) {
10732     unsigned GVFlags =
10733       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10734
10735     // If a reference to this global requires an extra load, we can't fold it.
10736     if (isGlobalStubReference(GVFlags))
10737       return false;
10738
10739     // If BaseGV requires a register for the PIC base, we cannot also have a
10740     // BaseReg specified.
10741     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10742       return false;
10743
10744     // If lower 4G is not available, then we must use rip-relative addressing.
10745     if ((M != CodeModel::Small || R != Reloc::Static) &&
10746         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10747       return false;
10748   }
10749
10750   switch (AM.Scale) {
10751   case 0:
10752   case 1:
10753   case 2:
10754   case 4:
10755   case 8:
10756     // These scales always work.
10757     break;
10758   case 3:
10759   case 5:
10760   case 9:
10761     // These scales are formed with basereg+scalereg.  Only accept if there is
10762     // no basereg yet.
10763     if (AM.HasBaseReg)
10764       return false;
10765     break;
10766   default:  // Other stuff never works.
10767     return false;
10768   }
10769
10770   return true;
10771 }
10772
10773
10774 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10775   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10776     return false;
10777   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10778   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10779   if (NumBits1 <= NumBits2)
10780     return false;
10781   return true;
10782 }
10783
10784 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10785   if (!VT1.isInteger() || !VT2.isInteger())
10786     return false;
10787   unsigned NumBits1 = VT1.getSizeInBits();
10788   unsigned NumBits2 = VT2.getSizeInBits();
10789   if (NumBits1 <= NumBits2)
10790     return false;
10791   return true;
10792 }
10793
10794 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10795   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10796   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10797 }
10798
10799 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10800   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10801   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10802 }
10803
10804 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10805   // i16 instructions are longer (0x66 prefix) and potentially slower.
10806   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10807 }
10808
10809 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10810 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10811 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10812 /// are assumed to be legal.
10813 bool
10814 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10815                                       EVT VT) const {
10816   // Very little shuffling can be done for 64-bit vectors right now.
10817   if (VT.getSizeInBits() == 64)
10818     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10819
10820   // FIXME: pshufb, blends, shifts.
10821   return (VT.getVectorNumElements() == 2 ||
10822           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10823           isMOVLMask(M, VT) ||
10824           isSHUFPMask(M, VT) ||
10825           isPSHUFDMask(M, VT) ||
10826           isPSHUFHWMask(M, VT) ||
10827           isPSHUFLWMask(M, VT) ||
10828           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10829           isUNPCKLMask(M, VT) ||
10830           isUNPCKHMask(M, VT) ||
10831           isUNPCKL_v_undef_Mask(M, VT) ||
10832           isUNPCKH_v_undef_Mask(M, VT));
10833 }
10834
10835 bool
10836 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10837                                           EVT VT) const {
10838   unsigned NumElts = VT.getVectorNumElements();
10839   // FIXME: This collection of masks seems suspect.
10840   if (NumElts == 2)
10841     return true;
10842   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10843     return (isMOVLMask(Mask, VT)  ||
10844             isCommutedMOVLMask(Mask, VT, true) ||
10845             isSHUFPMask(Mask, VT) ||
10846             isCommutedSHUFPMask(Mask, VT));
10847   }
10848   return false;
10849 }
10850
10851 //===----------------------------------------------------------------------===//
10852 //                           X86 Scheduler Hooks
10853 //===----------------------------------------------------------------------===//
10854
10855 // private utility function
10856 MachineBasicBlock *
10857 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10858                                                        MachineBasicBlock *MBB,
10859                                                        unsigned regOpc,
10860                                                        unsigned immOpc,
10861                                                        unsigned LoadOpc,
10862                                                        unsigned CXchgOpc,
10863                                                        unsigned notOpc,
10864                                                        unsigned EAXreg,
10865                                                        TargetRegisterClass *RC,
10866                                                        bool invSrc) const {
10867   // For the atomic bitwise operator, we generate
10868   //   thisMBB:
10869   //   newMBB:
10870   //     ld  t1 = [bitinstr.addr]
10871   //     op  t2 = t1, [bitinstr.val]
10872   //     mov EAX = t1
10873   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10874   //     bz  newMBB
10875   //     fallthrough -->nextMBB
10876   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10877   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10878   MachineFunction::iterator MBBIter = MBB;
10879   ++MBBIter;
10880
10881   /// First build the CFG
10882   MachineFunction *F = MBB->getParent();
10883   MachineBasicBlock *thisMBB = MBB;
10884   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10885   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10886   F->insert(MBBIter, newMBB);
10887   F->insert(MBBIter, nextMBB);
10888
10889   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10890   nextMBB->splice(nextMBB->begin(), thisMBB,
10891                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10892                   thisMBB->end());
10893   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10894
10895   // Update thisMBB to fall through to newMBB
10896   thisMBB->addSuccessor(newMBB);
10897
10898   // newMBB jumps to itself and fall through to nextMBB
10899   newMBB->addSuccessor(nextMBB);
10900   newMBB->addSuccessor(newMBB);
10901
10902   // Insert instructions into newMBB based on incoming instruction
10903   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10904          "unexpected number of operands");
10905   DebugLoc dl = bInstr->getDebugLoc();
10906   MachineOperand& destOper = bInstr->getOperand(0);
10907   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10908   int numArgs = bInstr->getNumOperands() - 1;
10909   for (int i=0; i < numArgs; ++i)
10910     argOpers[i] = &bInstr->getOperand(i+1);
10911
10912   // x86 address has 4 operands: base, index, scale, and displacement
10913   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10914   int valArgIndx = lastAddrIndx + 1;
10915
10916   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10917   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10918   for (int i=0; i <= lastAddrIndx; ++i)
10919     (*MIB).addOperand(*argOpers[i]);
10920
10921   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10922   if (invSrc) {
10923     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10924   }
10925   else
10926     tt = t1;
10927
10928   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10929   assert((argOpers[valArgIndx]->isReg() ||
10930           argOpers[valArgIndx]->isImm()) &&
10931          "invalid operand");
10932   if (argOpers[valArgIndx]->isReg())
10933     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10934   else
10935     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10936   MIB.addReg(tt);
10937   (*MIB).addOperand(*argOpers[valArgIndx]);
10938
10939   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10940   MIB.addReg(t1);
10941
10942   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10943   for (int i=0; i <= lastAddrIndx; ++i)
10944     (*MIB).addOperand(*argOpers[i]);
10945   MIB.addReg(t2);
10946   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10947   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10948                     bInstr->memoperands_end());
10949
10950   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10951   MIB.addReg(EAXreg);
10952
10953   // insert branch
10954   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10955
10956   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10957   return nextMBB;
10958 }
10959
10960 // private utility function:  64 bit atomics on 32 bit host.
10961 MachineBasicBlock *
10962 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10963                                                        MachineBasicBlock *MBB,
10964                                                        unsigned regOpcL,
10965                                                        unsigned regOpcH,
10966                                                        unsigned immOpcL,
10967                                                        unsigned immOpcH,
10968                                                        bool invSrc) const {
10969   // For the atomic bitwise operator, we generate
10970   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10971   //     ld t1,t2 = [bitinstr.addr]
10972   //   newMBB:
10973   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10974   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10975   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10976   //     mov ECX, EBX <- t5, t6
10977   //     mov EAX, EDX <- t1, t2
10978   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10979   //     mov t3, t4 <- EAX, EDX
10980   //     bz  newMBB
10981   //     result in out1, out2
10982   //     fallthrough -->nextMBB
10983
10984   const TargetRegisterClass *RC = X86::GR32RegisterClass;
10985   const unsigned LoadOpc = X86::MOV32rm;
10986   const unsigned NotOpc = X86::NOT32r;
10987   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10988   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10989   MachineFunction::iterator MBBIter = MBB;
10990   ++MBBIter;
10991
10992   /// First build the CFG
10993   MachineFunction *F = MBB->getParent();
10994   MachineBasicBlock *thisMBB = MBB;
10995   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10996   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10997   F->insert(MBBIter, newMBB);
10998   F->insert(MBBIter, nextMBB);
10999
11000   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11001   nextMBB->splice(nextMBB->begin(), thisMBB,
11002                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11003                   thisMBB->end());
11004   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11005
11006   // Update thisMBB to fall through to newMBB
11007   thisMBB->addSuccessor(newMBB);
11008
11009   // newMBB jumps to itself and fall through to nextMBB
11010   newMBB->addSuccessor(nextMBB);
11011   newMBB->addSuccessor(newMBB);
11012
11013   DebugLoc dl = bInstr->getDebugLoc();
11014   // Insert instructions into newMBB based on incoming instruction
11015   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11016   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11017          "unexpected number of operands");
11018   MachineOperand& dest1Oper = bInstr->getOperand(0);
11019   MachineOperand& dest2Oper = bInstr->getOperand(1);
11020   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11021   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11022     argOpers[i] = &bInstr->getOperand(i+2);
11023
11024     // We use some of the operands multiple times, so conservatively just
11025     // clear any kill flags that might be present.
11026     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11027       argOpers[i]->setIsKill(false);
11028   }
11029
11030   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11031   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11032
11033   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11034   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11035   for (int i=0; i <= lastAddrIndx; ++i)
11036     (*MIB).addOperand(*argOpers[i]);
11037   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11038   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11039   // add 4 to displacement.
11040   for (int i=0; i <= lastAddrIndx-2; ++i)
11041     (*MIB).addOperand(*argOpers[i]);
11042   MachineOperand newOp3 = *(argOpers[3]);
11043   if (newOp3.isImm())
11044     newOp3.setImm(newOp3.getImm()+4);
11045   else
11046     newOp3.setOffset(newOp3.getOffset()+4);
11047   (*MIB).addOperand(newOp3);
11048   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11049
11050   // t3/4 are defined later, at the bottom of the loop
11051   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11052   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11053   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11054     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11055   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11056     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11057
11058   // The subsequent operations should be using the destination registers of
11059   //the PHI instructions.
11060   if (invSrc) {
11061     t1 = F->getRegInfo().createVirtualRegister(RC);
11062     t2 = F->getRegInfo().createVirtualRegister(RC);
11063     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11064     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11065   } else {
11066     t1 = dest1Oper.getReg();
11067     t2 = dest2Oper.getReg();
11068   }
11069
11070   int valArgIndx = lastAddrIndx + 1;
11071   assert((argOpers[valArgIndx]->isReg() ||
11072           argOpers[valArgIndx]->isImm()) &&
11073          "invalid operand");
11074   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11075   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11076   if (argOpers[valArgIndx]->isReg())
11077     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11078   else
11079     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11080   if (regOpcL != X86::MOV32rr)
11081     MIB.addReg(t1);
11082   (*MIB).addOperand(*argOpers[valArgIndx]);
11083   assert(argOpers[valArgIndx + 1]->isReg() ==
11084          argOpers[valArgIndx]->isReg());
11085   assert(argOpers[valArgIndx + 1]->isImm() ==
11086          argOpers[valArgIndx]->isImm());
11087   if (argOpers[valArgIndx + 1]->isReg())
11088     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11089   else
11090     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11091   if (regOpcH != X86::MOV32rr)
11092     MIB.addReg(t2);
11093   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11094
11095   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11096   MIB.addReg(t1);
11097   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11098   MIB.addReg(t2);
11099
11100   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11101   MIB.addReg(t5);
11102   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11103   MIB.addReg(t6);
11104
11105   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11106   for (int i=0; i <= lastAddrIndx; ++i)
11107     (*MIB).addOperand(*argOpers[i]);
11108
11109   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11110   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11111                     bInstr->memoperands_end());
11112
11113   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11114   MIB.addReg(X86::EAX);
11115   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11116   MIB.addReg(X86::EDX);
11117
11118   // insert branch
11119   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11120
11121   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11122   return nextMBB;
11123 }
11124
11125 // private utility function
11126 MachineBasicBlock *
11127 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11128                                                       MachineBasicBlock *MBB,
11129                                                       unsigned cmovOpc) const {
11130   // For the atomic min/max operator, we generate
11131   //   thisMBB:
11132   //   newMBB:
11133   //     ld t1 = [min/max.addr]
11134   //     mov t2 = [min/max.val]
11135   //     cmp  t1, t2
11136   //     cmov[cond] t2 = t1
11137   //     mov EAX = t1
11138   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11139   //     bz   newMBB
11140   //     fallthrough -->nextMBB
11141   //
11142   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11143   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11144   MachineFunction::iterator MBBIter = MBB;
11145   ++MBBIter;
11146
11147   /// First build the CFG
11148   MachineFunction *F = MBB->getParent();
11149   MachineBasicBlock *thisMBB = MBB;
11150   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11151   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11152   F->insert(MBBIter, newMBB);
11153   F->insert(MBBIter, nextMBB);
11154
11155   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11156   nextMBB->splice(nextMBB->begin(), thisMBB,
11157                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11158                   thisMBB->end());
11159   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11160
11161   // Update thisMBB to fall through to newMBB
11162   thisMBB->addSuccessor(newMBB);
11163
11164   // newMBB jumps to newMBB and fall through to nextMBB
11165   newMBB->addSuccessor(nextMBB);
11166   newMBB->addSuccessor(newMBB);
11167
11168   DebugLoc dl = mInstr->getDebugLoc();
11169   // Insert instructions into newMBB based on incoming instruction
11170   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11171          "unexpected number of operands");
11172   MachineOperand& destOper = mInstr->getOperand(0);
11173   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11174   int numArgs = mInstr->getNumOperands() - 1;
11175   for (int i=0; i < numArgs; ++i)
11176     argOpers[i] = &mInstr->getOperand(i+1);
11177
11178   // x86 address has 4 operands: base, index, scale, and displacement
11179   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11180   int valArgIndx = lastAddrIndx + 1;
11181
11182   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11183   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11184   for (int i=0; i <= lastAddrIndx; ++i)
11185     (*MIB).addOperand(*argOpers[i]);
11186
11187   // We only support register and immediate values
11188   assert((argOpers[valArgIndx]->isReg() ||
11189           argOpers[valArgIndx]->isImm()) &&
11190          "invalid operand");
11191
11192   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11193   if (argOpers[valArgIndx]->isReg())
11194     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11195   else
11196     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11197   (*MIB).addOperand(*argOpers[valArgIndx]);
11198
11199   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11200   MIB.addReg(t1);
11201
11202   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11203   MIB.addReg(t1);
11204   MIB.addReg(t2);
11205
11206   // Generate movc
11207   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11208   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11209   MIB.addReg(t2);
11210   MIB.addReg(t1);
11211
11212   // Cmp and exchange if none has modified the memory location
11213   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11214   for (int i=0; i <= lastAddrIndx; ++i)
11215     (*MIB).addOperand(*argOpers[i]);
11216   MIB.addReg(t3);
11217   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11218   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11219                     mInstr->memoperands_end());
11220
11221   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11222   MIB.addReg(X86::EAX);
11223
11224   // insert branch
11225   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11226
11227   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11228   return nextMBB;
11229 }
11230
11231 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11232 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11233 // in the .td file.
11234 MachineBasicBlock *
11235 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11236                             unsigned numArgs, bool memArg) const {
11237   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11238          "Target must have SSE4.2 or AVX features enabled");
11239
11240   DebugLoc dl = MI->getDebugLoc();
11241   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11242   unsigned Opc;
11243   if (!Subtarget->hasAVX()) {
11244     if (memArg)
11245       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11246     else
11247       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11248   } else {
11249     if (memArg)
11250       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11251     else
11252       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11253   }
11254
11255   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11256   for (unsigned i = 0; i < numArgs; ++i) {
11257     MachineOperand &Op = MI->getOperand(i+1);
11258     if (!(Op.isReg() && Op.isImplicit()))
11259       MIB.addOperand(Op);
11260   }
11261   BuildMI(*BB, MI, dl,
11262     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11263              MI->getOperand(0).getReg())
11264     .addReg(X86::XMM0);
11265
11266   MI->eraseFromParent();
11267   return BB;
11268 }
11269
11270 MachineBasicBlock *
11271 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11272   DebugLoc dl = MI->getDebugLoc();
11273   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11274
11275   // Address into RAX/EAX, other two args into ECX, EDX.
11276   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11277   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11278   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11279   for (int i = 0; i < X86::AddrNumOperands; ++i)
11280     MIB.addOperand(MI->getOperand(i));
11281
11282   unsigned ValOps = X86::AddrNumOperands;
11283   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11284     .addReg(MI->getOperand(ValOps).getReg());
11285   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11286     .addReg(MI->getOperand(ValOps+1).getReg());
11287
11288   // The instruction doesn't actually take any operands though.
11289   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11290
11291   MI->eraseFromParent(); // The pseudo is gone now.
11292   return BB;
11293 }
11294
11295 MachineBasicBlock *
11296 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11297   DebugLoc dl = MI->getDebugLoc();
11298   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11299
11300   // First arg in ECX, the second in EAX.
11301   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11302     .addReg(MI->getOperand(0).getReg());
11303   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11304     .addReg(MI->getOperand(1).getReg());
11305
11306   // The instruction doesn't actually take any operands though.
11307   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11308
11309   MI->eraseFromParent(); // The pseudo is gone now.
11310   return BB;
11311 }
11312
11313 MachineBasicBlock *
11314 X86TargetLowering::EmitVAARG64WithCustomInserter(
11315                    MachineInstr *MI,
11316                    MachineBasicBlock *MBB) const {
11317   // Emit va_arg instruction on X86-64.
11318
11319   // Operands to this pseudo-instruction:
11320   // 0  ) Output        : destination address (reg)
11321   // 1-5) Input         : va_list address (addr, i64mem)
11322   // 6  ) ArgSize       : Size (in bytes) of vararg type
11323   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11324   // 8  ) Align         : Alignment of type
11325   // 9  ) EFLAGS (implicit-def)
11326
11327   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11328   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11329
11330   unsigned DestReg = MI->getOperand(0).getReg();
11331   MachineOperand &Base = MI->getOperand(1);
11332   MachineOperand &Scale = MI->getOperand(2);
11333   MachineOperand &Index = MI->getOperand(3);
11334   MachineOperand &Disp = MI->getOperand(4);
11335   MachineOperand &Segment = MI->getOperand(5);
11336   unsigned ArgSize = MI->getOperand(6).getImm();
11337   unsigned ArgMode = MI->getOperand(7).getImm();
11338   unsigned Align = MI->getOperand(8).getImm();
11339
11340   // Memory Reference
11341   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11342   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11343   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11344
11345   // Machine Information
11346   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11347   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11348   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11349   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11350   DebugLoc DL = MI->getDebugLoc();
11351
11352   // struct va_list {
11353   //   i32   gp_offset
11354   //   i32   fp_offset
11355   //   i64   overflow_area (address)
11356   //   i64   reg_save_area (address)
11357   // }
11358   // sizeof(va_list) = 24
11359   // alignment(va_list) = 8
11360
11361   unsigned TotalNumIntRegs = 6;
11362   unsigned TotalNumXMMRegs = 8;
11363   bool UseGPOffset = (ArgMode == 1);
11364   bool UseFPOffset = (ArgMode == 2);
11365   unsigned MaxOffset = TotalNumIntRegs * 8 +
11366                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11367
11368   /* Align ArgSize to a multiple of 8 */
11369   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11370   bool NeedsAlign = (Align > 8);
11371
11372   MachineBasicBlock *thisMBB = MBB;
11373   MachineBasicBlock *overflowMBB;
11374   MachineBasicBlock *offsetMBB;
11375   MachineBasicBlock *endMBB;
11376
11377   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11378   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11379   unsigned OffsetReg = 0;
11380
11381   if (!UseGPOffset && !UseFPOffset) {
11382     // If we only pull from the overflow region, we don't create a branch.
11383     // We don't need to alter control flow.
11384     OffsetDestReg = 0; // unused
11385     OverflowDestReg = DestReg;
11386
11387     offsetMBB = NULL;
11388     overflowMBB = thisMBB;
11389     endMBB = thisMBB;
11390   } else {
11391     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11392     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11393     // If not, pull from overflow_area. (branch to overflowMBB)
11394     //
11395     //       thisMBB
11396     //         |     .
11397     //         |        .
11398     //     offsetMBB   overflowMBB
11399     //         |        .
11400     //         |     .
11401     //        endMBB
11402
11403     // Registers for the PHI in endMBB
11404     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11405     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11406
11407     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11408     MachineFunction *MF = MBB->getParent();
11409     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11410     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11411     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11412
11413     MachineFunction::iterator MBBIter = MBB;
11414     ++MBBIter;
11415
11416     // Insert the new basic blocks
11417     MF->insert(MBBIter, offsetMBB);
11418     MF->insert(MBBIter, overflowMBB);
11419     MF->insert(MBBIter, endMBB);
11420
11421     // Transfer the remainder of MBB and its successor edges to endMBB.
11422     endMBB->splice(endMBB->begin(), thisMBB,
11423                     llvm::next(MachineBasicBlock::iterator(MI)),
11424                     thisMBB->end());
11425     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11426
11427     // Make offsetMBB and overflowMBB successors of thisMBB
11428     thisMBB->addSuccessor(offsetMBB);
11429     thisMBB->addSuccessor(overflowMBB);
11430
11431     // endMBB is a successor of both offsetMBB and overflowMBB
11432     offsetMBB->addSuccessor(endMBB);
11433     overflowMBB->addSuccessor(endMBB);
11434
11435     // Load the offset value into a register
11436     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11437     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11438       .addOperand(Base)
11439       .addOperand(Scale)
11440       .addOperand(Index)
11441       .addDisp(Disp, UseFPOffset ? 4 : 0)
11442       .addOperand(Segment)
11443       .setMemRefs(MMOBegin, MMOEnd);
11444
11445     // Check if there is enough room left to pull this argument.
11446     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11447       .addReg(OffsetReg)
11448       .addImm(MaxOffset + 8 - ArgSizeA8);
11449
11450     // Branch to "overflowMBB" if offset >= max
11451     // Fall through to "offsetMBB" otherwise
11452     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11453       .addMBB(overflowMBB);
11454   }
11455
11456   // In offsetMBB, emit code to use the reg_save_area.
11457   if (offsetMBB) {
11458     assert(OffsetReg != 0);
11459
11460     // Read the reg_save_area address.
11461     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11462     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11463       .addOperand(Base)
11464       .addOperand(Scale)
11465       .addOperand(Index)
11466       .addDisp(Disp, 16)
11467       .addOperand(Segment)
11468       .setMemRefs(MMOBegin, MMOEnd);
11469
11470     // Zero-extend the offset
11471     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11472       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11473         .addImm(0)
11474         .addReg(OffsetReg)
11475         .addImm(X86::sub_32bit);
11476
11477     // Add the offset to the reg_save_area to get the final address.
11478     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11479       .addReg(OffsetReg64)
11480       .addReg(RegSaveReg);
11481
11482     // Compute the offset for the next argument
11483     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11484     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11485       .addReg(OffsetReg)
11486       .addImm(UseFPOffset ? 16 : 8);
11487
11488     // Store it back into the va_list.
11489     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11490       .addOperand(Base)
11491       .addOperand(Scale)
11492       .addOperand(Index)
11493       .addDisp(Disp, UseFPOffset ? 4 : 0)
11494       .addOperand(Segment)
11495       .addReg(NextOffsetReg)
11496       .setMemRefs(MMOBegin, MMOEnd);
11497
11498     // Jump to endMBB
11499     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11500       .addMBB(endMBB);
11501   }
11502
11503   //
11504   // Emit code to use overflow area
11505   //
11506
11507   // Load the overflow_area address into a register.
11508   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11509   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11510     .addOperand(Base)
11511     .addOperand(Scale)
11512     .addOperand(Index)
11513     .addDisp(Disp, 8)
11514     .addOperand(Segment)
11515     .setMemRefs(MMOBegin, MMOEnd);
11516
11517   // If we need to align it, do so. Otherwise, just copy the address
11518   // to OverflowDestReg.
11519   if (NeedsAlign) {
11520     // Align the overflow address
11521     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11522     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11523
11524     // aligned_addr = (addr + (align-1)) & ~(align-1)
11525     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11526       .addReg(OverflowAddrReg)
11527       .addImm(Align-1);
11528
11529     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11530       .addReg(TmpReg)
11531       .addImm(~(uint64_t)(Align-1));
11532   } else {
11533     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11534       .addReg(OverflowAddrReg);
11535   }
11536
11537   // Compute the next overflow address after this argument.
11538   // (the overflow address should be kept 8-byte aligned)
11539   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11540   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11541     .addReg(OverflowDestReg)
11542     .addImm(ArgSizeA8);
11543
11544   // Store the new overflow address.
11545   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11546     .addOperand(Base)
11547     .addOperand(Scale)
11548     .addOperand(Index)
11549     .addDisp(Disp, 8)
11550     .addOperand(Segment)
11551     .addReg(NextAddrReg)
11552     .setMemRefs(MMOBegin, MMOEnd);
11553
11554   // If we branched, emit the PHI to the front of endMBB.
11555   if (offsetMBB) {
11556     BuildMI(*endMBB, endMBB->begin(), DL,
11557             TII->get(X86::PHI), DestReg)
11558       .addReg(OffsetDestReg).addMBB(offsetMBB)
11559       .addReg(OverflowDestReg).addMBB(overflowMBB);
11560   }
11561
11562   // Erase the pseudo instruction
11563   MI->eraseFromParent();
11564
11565   return endMBB;
11566 }
11567
11568 MachineBasicBlock *
11569 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11570                                                  MachineInstr *MI,
11571                                                  MachineBasicBlock *MBB) const {
11572   // Emit code to save XMM registers to the stack. The ABI says that the
11573   // number of registers to save is given in %al, so it's theoretically
11574   // possible to do an indirect jump trick to avoid saving all of them,
11575   // however this code takes a simpler approach and just executes all
11576   // of the stores if %al is non-zero. It's less code, and it's probably
11577   // easier on the hardware branch predictor, and stores aren't all that
11578   // expensive anyway.
11579
11580   // Create the new basic blocks. One block contains all the XMM stores,
11581   // and one block is the final destination regardless of whether any
11582   // stores were performed.
11583   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11584   MachineFunction *F = MBB->getParent();
11585   MachineFunction::iterator MBBIter = MBB;
11586   ++MBBIter;
11587   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11588   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11589   F->insert(MBBIter, XMMSaveMBB);
11590   F->insert(MBBIter, EndMBB);
11591
11592   // Transfer the remainder of MBB and its successor edges to EndMBB.
11593   EndMBB->splice(EndMBB->begin(), MBB,
11594                  llvm::next(MachineBasicBlock::iterator(MI)),
11595                  MBB->end());
11596   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11597
11598   // The original block will now fall through to the XMM save block.
11599   MBB->addSuccessor(XMMSaveMBB);
11600   // The XMMSaveMBB will fall through to the end block.
11601   XMMSaveMBB->addSuccessor(EndMBB);
11602
11603   // Now add the instructions.
11604   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11605   DebugLoc DL = MI->getDebugLoc();
11606
11607   unsigned CountReg = MI->getOperand(0).getReg();
11608   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11609   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11610
11611   if (!Subtarget->isTargetWin64()) {
11612     // If %al is 0, branch around the XMM save block.
11613     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11614     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11615     MBB->addSuccessor(EndMBB);
11616   }
11617
11618   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11619   // In the XMM save block, save all the XMM argument registers.
11620   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11621     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11622     MachineMemOperand *MMO =
11623       F->getMachineMemOperand(
11624           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11625         MachineMemOperand::MOStore,
11626         /*Size=*/16, /*Align=*/16);
11627     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11628       .addFrameIndex(RegSaveFrameIndex)
11629       .addImm(/*Scale=*/1)
11630       .addReg(/*IndexReg=*/0)
11631       .addImm(/*Disp=*/Offset)
11632       .addReg(/*Segment=*/0)
11633       .addReg(MI->getOperand(i).getReg())
11634       .addMemOperand(MMO);
11635   }
11636
11637   MI->eraseFromParent();   // The pseudo instruction is gone now.
11638
11639   return EndMBB;
11640 }
11641
11642 MachineBasicBlock *
11643 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11644                                      MachineBasicBlock *BB) const {
11645   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11646   DebugLoc DL = MI->getDebugLoc();
11647
11648   // To "insert" a SELECT_CC instruction, we actually have to insert the
11649   // diamond control-flow pattern.  The incoming instruction knows the
11650   // destination vreg to set, the condition code register to branch on, the
11651   // true/false values to select between, and a branch opcode to use.
11652   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11653   MachineFunction::iterator It = BB;
11654   ++It;
11655
11656   //  thisMBB:
11657   //  ...
11658   //   TrueVal = ...
11659   //   cmpTY ccX, r1, r2
11660   //   bCC copy1MBB
11661   //   fallthrough --> copy0MBB
11662   MachineBasicBlock *thisMBB = BB;
11663   MachineFunction *F = BB->getParent();
11664   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11665   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11666   F->insert(It, copy0MBB);
11667   F->insert(It, sinkMBB);
11668
11669   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11670   // live into the sink and copy blocks.
11671   if (!MI->killsRegister(X86::EFLAGS)) {
11672     copy0MBB->addLiveIn(X86::EFLAGS);
11673     sinkMBB->addLiveIn(X86::EFLAGS);
11674   }
11675
11676   // Transfer the remainder of BB and its successor edges to sinkMBB.
11677   sinkMBB->splice(sinkMBB->begin(), BB,
11678                   llvm::next(MachineBasicBlock::iterator(MI)),
11679                   BB->end());
11680   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11681
11682   // Add the true and fallthrough blocks as its successors.
11683   BB->addSuccessor(copy0MBB);
11684   BB->addSuccessor(sinkMBB);
11685
11686   // Create the conditional branch instruction.
11687   unsigned Opc =
11688     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11689   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11690
11691   //  copy0MBB:
11692   //   %FalseValue = ...
11693   //   # fallthrough to sinkMBB
11694   copy0MBB->addSuccessor(sinkMBB);
11695
11696   //  sinkMBB:
11697   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11698   //  ...
11699   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11700           TII->get(X86::PHI), MI->getOperand(0).getReg())
11701     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11702     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11703
11704   MI->eraseFromParent();   // The pseudo instruction is gone now.
11705   return sinkMBB;
11706 }
11707
11708 MachineBasicBlock *
11709 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11710                                         bool Is64Bit) const {
11711   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11712   DebugLoc DL = MI->getDebugLoc();
11713   MachineFunction *MF = BB->getParent();
11714   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11715
11716   assert(EnableSegmentedStacks);
11717
11718   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11719   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11720
11721   // BB:
11722   //  ... [Till the alloca]
11723   // If stacklet is not large enough, jump to mallocMBB
11724   //
11725   // bumpMBB:
11726   //  Allocate by subtracting from RSP
11727   //  Jump to continueMBB
11728   //
11729   // mallocMBB:
11730   //  Allocate by call to runtime
11731   //
11732   // continueMBB:
11733   //  ...
11734   //  [rest of original BB]
11735   //
11736
11737   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11738   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11739   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11740
11741   MachineRegisterInfo &MRI = MF->getRegInfo();
11742   const TargetRegisterClass *AddrRegClass =
11743     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11744
11745   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11746     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11747     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11748     sizeVReg = MI->getOperand(1).getReg(),
11749     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11750
11751   MachineFunction::iterator MBBIter = BB;
11752   ++MBBIter;
11753
11754   MF->insert(MBBIter, bumpMBB);
11755   MF->insert(MBBIter, mallocMBB);
11756   MF->insert(MBBIter, continueMBB);
11757
11758   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11759                       (MachineBasicBlock::iterator(MI)), BB->end());
11760   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11761
11762   // Add code to the main basic block to check if the stack limit has been hit,
11763   // and if so, jump to mallocMBB otherwise to bumpMBB.
11764   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11765   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11766     .addReg(tmpSPVReg).addReg(sizeVReg);
11767   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11768     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11769     .addReg(tmpSPVReg);
11770   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11771
11772   // bumpMBB simply decreases the stack pointer, since we know the current
11773   // stacklet has enough space.
11774   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11775     .addReg(tmpSPVReg);
11776   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11777     .addReg(tmpSPVReg);
11778   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11779
11780   // Calls into a routine in libgcc to allocate more space from the heap.
11781   if (Is64Bit) {
11782     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11783       .addReg(sizeVReg);
11784     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11785     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11786   } else {
11787     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11788       .addImm(12);
11789     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11790     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11791       .addExternalSymbol("__morestack_allocate_stack_space");
11792   }
11793
11794   if (!Is64Bit)
11795     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11796       .addImm(16);
11797
11798   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11799     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11800   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11801
11802   // Set up the CFG correctly.
11803   BB->addSuccessor(bumpMBB);
11804   BB->addSuccessor(mallocMBB);
11805   mallocMBB->addSuccessor(continueMBB);
11806   bumpMBB->addSuccessor(continueMBB);
11807
11808   // Take care of the PHI nodes.
11809   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11810           MI->getOperand(0).getReg())
11811     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11812     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11813
11814   // Delete the original pseudo instruction.
11815   MI->eraseFromParent();
11816
11817   // And we're done.
11818   return continueMBB;
11819 }
11820
11821 MachineBasicBlock *
11822 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11823                                           MachineBasicBlock *BB) const {
11824   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11825   DebugLoc DL = MI->getDebugLoc();
11826
11827   assert(!Subtarget->isTargetEnvMacho());
11828
11829   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11830   // non-trivial part is impdef of ESP.
11831
11832   if (Subtarget->isTargetWin64()) {
11833     if (Subtarget->isTargetCygMing()) {
11834       // ___chkstk(Mingw64):
11835       // Clobbers R10, R11, RAX and EFLAGS.
11836       // Updates RSP.
11837       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11838         .addExternalSymbol("___chkstk")
11839         .addReg(X86::RAX, RegState::Implicit)
11840         .addReg(X86::RSP, RegState::Implicit)
11841         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11842         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11843         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11844     } else {
11845       // __chkstk(MSVCRT): does not update stack pointer.
11846       // Clobbers R10, R11 and EFLAGS.
11847       // FIXME: RAX(allocated size) might be reused and not killed.
11848       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11849         .addExternalSymbol("__chkstk")
11850         .addReg(X86::RAX, RegState::Implicit)
11851         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11852       // RAX has the offset to subtracted from RSP.
11853       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11854         .addReg(X86::RSP)
11855         .addReg(X86::RAX);
11856     }
11857   } else {
11858     const char *StackProbeSymbol =
11859       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11860
11861     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11862       .addExternalSymbol(StackProbeSymbol)
11863       .addReg(X86::EAX, RegState::Implicit)
11864       .addReg(X86::ESP, RegState::Implicit)
11865       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11866       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11867       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11868   }
11869
11870   MI->eraseFromParent();   // The pseudo instruction is gone now.
11871   return BB;
11872 }
11873
11874 MachineBasicBlock *
11875 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11876                                       MachineBasicBlock *BB) const {
11877   // This is pretty easy.  We're taking the value that we received from
11878   // our load from the relocation, sticking it in either RDI (x86-64)
11879   // or EAX and doing an indirect call.  The return value will then
11880   // be in the normal return register.
11881   const X86InstrInfo *TII
11882     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11883   DebugLoc DL = MI->getDebugLoc();
11884   MachineFunction *F = BB->getParent();
11885
11886   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11887   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11888
11889   if (Subtarget->is64Bit()) {
11890     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11891                                       TII->get(X86::MOV64rm), X86::RDI)
11892     .addReg(X86::RIP)
11893     .addImm(0).addReg(0)
11894     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11895                       MI->getOperand(3).getTargetFlags())
11896     .addReg(0);
11897     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11898     addDirectMem(MIB, X86::RDI);
11899   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11900     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11901                                       TII->get(X86::MOV32rm), X86::EAX)
11902     .addReg(0)
11903     .addImm(0).addReg(0)
11904     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11905                       MI->getOperand(3).getTargetFlags())
11906     .addReg(0);
11907     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11908     addDirectMem(MIB, X86::EAX);
11909   } else {
11910     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11911                                       TII->get(X86::MOV32rm), X86::EAX)
11912     .addReg(TII->getGlobalBaseReg(F))
11913     .addImm(0).addReg(0)
11914     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11915                       MI->getOperand(3).getTargetFlags())
11916     .addReg(0);
11917     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11918     addDirectMem(MIB, X86::EAX);
11919   }
11920
11921   MI->eraseFromParent(); // The pseudo instruction is gone now.
11922   return BB;
11923 }
11924
11925 MachineBasicBlock *
11926 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11927                                                MachineBasicBlock *BB) const {
11928   switch (MI->getOpcode()) {
11929   default: assert(false && "Unexpected instr type to insert");
11930   case X86::TAILJMPd64:
11931   case X86::TAILJMPr64:
11932   case X86::TAILJMPm64:
11933     assert(!"TAILJMP64 would not be touched here.");
11934   case X86::TCRETURNdi64:
11935   case X86::TCRETURNri64:
11936   case X86::TCRETURNmi64:
11937     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11938     // On AMD64, additional defs should be added before register allocation.
11939     if (!Subtarget->isTargetWin64()) {
11940       MI->addRegisterDefined(X86::RSI);
11941       MI->addRegisterDefined(X86::RDI);
11942       MI->addRegisterDefined(X86::XMM6);
11943       MI->addRegisterDefined(X86::XMM7);
11944       MI->addRegisterDefined(X86::XMM8);
11945       MI->addRegisterDefined(X86::XMM9);
11946       MI->addRegisterDefined(X86::XMM10);
11947       MI->addRegisterDefined(X86::XMM11);
11948       MI->addRegisterDefined(X86::XMM12);
11949       MI->addRegisterDefined(X86::XMM13);
11950       MI->addRegisterDefined(X86::XMM14);
11951       MI->addRegisterDefined(X86::XMM15);
11952     }
11953     return BB;
11954   case X86::WIN_ALLOCA:
11955     return EmitLoweredWinAlloca(MI, BB);
11956   case X86::SEG_ALLOCA_32:
11957     return EmitLoweredSegAlloca(MI, BB, false);
11958   case X86::SEG_ALLOCA_64:
11959     return EmitLoweredSegAlloca(MI, BB, true);
11960   case X86::TLSCall_32:
11961   case X86::TLSCall_64:
11962     return EmitLoweredTLSCall(MI, BB);
11963   case X86::CMOV_GR8:
11964   case X86::CMOV_FR32:
11965   case X86::CMOV_FR64:
11966   case X86::CMOV_V4F32:
11967   case X86::CMOV_V2F64:
11968   case X86::CMOV_V2I64:
11969   case X86::CMOV_V8F32:
11970   case X86::CMOV_V4F64:
11971   case X86::CMOV_V4I64:
11972   case X86::CMOV_GR16:
11973   case X86::CMOV_GR32:
11974   case X86::CMOV_RFP32:
11975   case X86::CMOV_RFP64:
11976   case X86::CMOV_RFP80:
11977     return EmitLoweredSelect(MI, BB);
11978
11979   case X86::FP32_TO_INT16_IN_MEM:
11980   case X86::FP32_TO_INT32_IN_MEM:
11981   case X86::FP32_TO_INT64_IN_MEM:
11982   case X86::FP64_TO_INT16_IN_MEM:
11983   case X86::FP64_TO_INT32_IN_MEM:
11984   case X86::FP64_TO_INT64_IN_MEM:
11985   case X86::FP80_TO_INT16_IN_MEM:
11986   case X86::FP80_TO_INT32_IN_MEM:
11987   case X86::FP80_TO_INT64_IN_MEM: {
11988     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11989     DebugLoc DL = MI->getDebugLoc();
11990
11991     // Change the floating point control register to use "round towards zero"
11992     // mode when truncating to an integer value.
11993     MachineFunction *F = BB->getParent();
11994     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11995     addFrameReference(BuildMI(*BB, MI, DL,
11996                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
11997
11998     // Load the old value of the high byte of the control word...
11999     unsigned OldCW =
12000       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12001     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12002                       CWFrameIdx);
12003
12004     // Set the high part to be round to zero...
12005     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12006       .addImm(0xC7F);
12007
12008     // Reload the modified control word now...
12009     addFrameReference(BuildMI(*BB, MI, DL,
12010                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12011
12012     // Restore the memory image of control word to original value
12013     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12014       .addReg(OldCW);
12015
12016     // Get the X86 opcode to use.
12017     unsigned Opc;
12018     switch (MI->getOpcode()) {
12019     default: llvm_unreachable("illegal opcode!");
12020     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12021     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12022     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12023     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12024     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12025     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12026     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12027     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12028     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12029     }
12030
12031     X86AddressMode AM;
12032     MachineOperand &Op = MI->getOperand(0);
12033     if (Op.isReg()) {
12034       AM.BaseType = X86AddressMode::RegBase;
12035       AM.Base.Reg = Op.getReg();
12036     } else {
12037       AM.BaseType = X86AddressMode::FrameIndexBase;
12038       AM.Base.FrameIndex = Op.getIndex();
12039     }
12040     Op = MI->getOperand(1);
12041     if (Op.isImm())
12042       AM.Scale = Op.getImm();
12043     Op = MI->getOperand(2);
12044     if (Op.isImm())
12045       AM.IndexReg = Op.getImm();
12046     Op = MI->getOperand(3);
12047     if (Op.isGlobal()) {
12048       AM.GV = Op.getGlobal();
12049     } else {
12050       AM.Disp = Op.getImm();
12051     }
12052     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12053                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12054
12055     // Reload the original control word now.
12056     addFrameReference(BuildMI(*BB, MI, DL,
12057                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12058
12059     MI->eraseFromParent();   // The pseudo instruction is gone now.
12060     return BB;
12061   }
12062     // String/text processing lowering.
12063   case X86::PCMPISTRM128REG:
12064   case X86::VPCMPISTRM128REG:
12065     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12066   case X86::PCMPISTRM128MEM:
12067   case X86::VPCMPISTRM128MEM:
12068     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12069   case X86::PCMPESTRM128REG:
12070   case X86::VPCMPESTRM128REG:
12071     return EmitPCMP(MI, BB, 5, false /* in mem */);
12072   case X86::PCMPESTRM128MEM:
12073   case X86::VPCMPESTRM128MEM:
12074     return EmitPCMP(MI, BB, 5, true /* in mem */);
12075
12076     // Thread synchronization.
12077   case X86::MONITOR:
12078     return EmitMonitor(MI, BB);
12079   case X86::MWAIT:
12080     return EmitMwait(MI, BB);
12081
12082     // Atomic Lowering.
12083   case X86::ATOMAND32:
12084     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12085                                                X86::AND32ri, X86::MOV32rm,
12086                                                X86::LCMPXCHG32,
12087                                                X86::NOT32r, X86::EAX,
12088                                                X86::GR32RegisterClass);
12089   case X86::ATOMOR32:
12090     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12091                                                X86::OR32ri, X86::MOV32rm,
12092                                                X86::LCMPXCHG32,
12093                                                X86::NOT32r, X86::EAX,
12094                                                X86::GR32RegisterClass);
12095   case X86::ATOMXOR32:
12096     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12097                                                X86::XOR32ri, X86::MOV32rm,
12098                                                X86::LCMPXCHG32,
12099                                                X86::NOT32r, X86::EAX,
12100                                                X86::GR32RegisterClass);
12101   case X86::ATOMNAND32:
12102     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12103                                                X86::AND32ri, X86::MOV32rm,
12104                                                X86::LCMPXCHG32,
12105                                                X86::NOT32r, X86::EAX,
12106                                                X86::GR32RegisterClass, true);
12107   case X86::ATOMMIN32:
12108     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12109   case X86::ATOMMAX32:
12110     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12111   case X86::ATOMUMIN32:
12112     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12113   case X86::ATOMUMAX32:
12114     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12115
12116   case X86::ATOMAND16:
12117     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12118                                                X86::AND16ri, X86::MOV16rm,
12119                                                X86::LCMPXCHG16,
12120                                                X86::NOT16r, X86::AX,
12121                                                X86::GR16RegisterClass);
12122   case X86::ATOMOR16:
12123     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12124                                                X86::OR16ri, X86::MOV16rm,
12125                                                X86::LCMPXCHG16,
12126                                                X86::NOT16r, X86::AX,
12127                                                X86::GR16RegisterClass);
12128   case X86::ATOMXOR16:
12129     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12130                                                X86::XOR16ri, X86::MOV16rm,
12131                                                X86::LCMPXCHG16,
12132                                                X86::NOT16r, X86::AX,
12133                                                X86::GR16RegisterClass);
12134   case X86::ATOMNAND16:
12135     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12136                                                X86::AND16ri, X86::MOV16rm,
12137                                                X86::LCMPXCHG16,
12138                                                X86::NOT16r, X86::AX,
12139                                                X86::GR16RegisterClass, true);
12140   case X86::ATOMMIN16:
12141     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12142   case X86::ATOMMAX16:
12143     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12144   case X86::ATOMUMIN16:
12145     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12146   case X86::ATOMUMAX16:
12147     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12148
12149   case X86::ATOMAND8:
12150     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12151                                                X86::AND8ri, X86::MOV8rm,
12152                                                X86::LCMPXCHG8,
12153                                                X86::NOT8r, X86::AL,
12154                                                X86::GR8RegisterClass);
12155   case X86::ATOMOR8:
12156     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12157                                                X86::OR8ri, X86::MOV8rm,
12158                                                X86::LCMPXCHG8,
12159                                                X86::NOT8r, X86::AL,
12160                                                X86::GR8RegisterClass);
12161   case X86::ATOMXOR8:
12162     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12163                                                X86::XOR8ri, X86::MOV8rm,
12164                                                X86::LCMPXCHG8,
12165                                                X86::NOT8r, X86::AL,
12166                                                X86::GR8RegisterClass);
12167   case X86::ATOMNAND8:
12168     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12169                                                X86::AND8ri, X86::MOV8rm,
12170                                                X86::LCMPXCHG8,
12171                                                X86::NOT8r, X86::AL,
12172                                                X86::GR8RegisterClass, true);
12173   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12174   // This group is for 64-bit host.
12175   case X86::ATOMAND64:
12176     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12177                                                X86::AND64ri32, X86::MOV64rm,
12178                                                X86::LCMPXCHG64,
12179                                                X86::NOT64r, X86::RAX,
12180                                                X86::GR64RegisterClass);
12181   case X86::ATOMOR64:
12182     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12183                                                X86::OR64ri32, X86::MOV64rm,
12184                                                X86::LCMPXCHG64,
12185                                                X86::NOT64r, X86::RAX,
12186                                                X86::GR64RegisterClass);
12187   case X86::ATOMXOR64:
12188     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12189                                                X86::XOR64ri32, X86::MOV64rm,
12190                                                X86::LCMPXCHG64,
12191                                                X86::NOT64r, X86::RAX,
12192                                                X86::GR64RegisterClass);
12193   case X86::ATOMNAND64:
12194     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12195                                                X86::AND64ri32, X86::MOV64rm,
12196                                                X86::LCMPXCHG64,
12197                                                X86::NOT64r, X86::RAX,
12198                                                X86::GR64RegisterClass, true);
12199   case X86::ATOMMIN64:
12200     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12201   case X86::ATOMMAX64:
12202     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12203   case X86::ATOMUMIN64:
12204     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12205   case X86::ATOMUMAX64:
12206     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12207
12208   // This group does 64-bit operations on a 32-bit host.
12209   case X86::ATOMAND6432:
12210     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12211                                                X86::AND32rr, X86::AND32rr,
12212                                                X86::AND32ri, X86::AND32ri,
12213                                                false);
12214   case X86::ATOMOR6432:
12215     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12216                                                X86::OR32rr, X86::OR32rr,
12217                                                X86::OR32ri, X86::OR32ri,
12218                                                false);
12219   case X86::ATOMXOR6432:
12220     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12221                                                X86::XOR32rr, X86::XOR32rr,
12222                                                X86::XOR32ri, X86::XOR32ri,
12223                                                false);
12224   case X86::ATOMNAND6432:
12225     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12226                                                X86::AND32rr, X86::AND32rr,
12227                                                X86::AND32ri, X86::AND32ri,
12228                                                true);
12229   case X86::ATOMADD6432:
12230     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12231                                                X86::ADD32rr, X86::ADC32rr,
12232                                                X86::ADD32ri, X86::ADC32ri,
12233                                                false);
12234   case X86::ATOMSUB6432:
12235     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12236                                                X86::SUB32rr, X86::SBB32rr,
12237                                                X86::SUB32ri, X86::SBB32ri,
12238                                                false);
12239   case X86::ATOMSWAP6432:
12240     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12241                                                X86::MOV32rr, X86::MOV32rr,
12242                                                X86::MOV32ri, X86::MOV32ri,
12243                                                false);
12244   case X86::VASTART_SAVE_XMM_REGS:
12245     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12246
12247   case X86::VAARG_64:
12248     return EmitVAARG64WithCustomInserter(MI, BB);
12249   }
12250 }
12251
12252 //===----------------------------------------------------------------------===//
12253 //                           X86 Optimization Hooks
12254 //===----------------------------------------------------------------------===//
12255
12256 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12257                                                        const APInt &Mask,
12258                                                        APInt &KnownZero,
12259                                                        APInt &KnownOne,
12260                                                        const SelectionDAG &DAG,
12261                                                        unsigned Depth) const {
12262   unsigned Opc = Op.getOpcode();
12263   assert((Opc >= ISD::BUILTIN_OP_END ||
12264           Opc == ISD::INTRINSIC_WO_CHAIN ||
12265           Opc == ISD::INTRINSIC_W_CHAIN ||
12266           Opc == ISD::INTRINSIC_VOID) &&
12267          "Should use MaskedValueIsZero if you don't know whether Op"
12268          " is a target node!");
12269
12270   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12271   switch (Opc) {
12272   default: break;
12273   case X86ISD::ADD:
12274   case X86ISD::SUB:
12275   case X86ISD::ADC:
12276   case X86ISD::SBB:
12277   case X86ISD::SMUL:
12278   case X86ISD::UMUL:
12279   case X86ISD::INC:
12280   case X86ISD::DEC:
12281   case X86ISD::OR:
12282   case X86ISD::XOR:
12283   case X86ISD::AND:
12284     // These nodes' second result is a boolean.
12285     if (Op.getResNo() == 0)
12286       break;
12287     // Fallthrough
12288   case X86ISD::SETCC:
12289     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12290                                        Mask.getBitWidth() - 1);
12291     break;
12292   }
12293 }
12294
12295 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12296                                                          unsigned Depth) const {
12297   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12298   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12299     return Op.getValueType().getScalarType().getSizeInBits();
12300
12301   // Fallback case.
12302   return 1;
12303 }
12304
12305 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12306 /// node is a GlobalAddress + offset.
12307 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12308                                        const GlobalValue* &GA,
12309                                        int64_t &Offset) const {
12310   if (N->getOpcode() == X86ISD::Wrapper) {
12311     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12312       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12313       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12314       return true;
12315     }
12316   }
12317   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12318 }
12319
12320 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12321 /// same as extracting the high 128-bit part of 256-bit vector and then
12322 /// inserting the result into the low part of a new 256-bit vector
12323 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12324   EVT VT = SVOp->getValueType(0);
12325   int NumElems = VT.getVectorNumElements();
12326
12327   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12328   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12329     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12330         SVOp->getMaskElt(j) >= 0)
12331       return false;
12332
12333   return true;
12334 }
12335
12336 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12337 /// same as extracting the low 128-bit part of 256-bit vector and then
12338 /// inserting the result into the high part of a new 256-bit vector
12339 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12340   EVT VT = SVOp->getValueType(0);
12341   int NumElems = VT.getVectorNumElements();
12342
12343   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12344   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12345     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12346         SVOp->getMaskElt(j) >= 0)
12347       return false;
12348
12349   return true;
12350 }
12351
12352 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12353 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12354                                         TargetLowering::DAGCombinerInfo &DCI) {
12355   DebugLoc dl = N->getDebugLoc();
12356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12357   SDValue V1 = SVOp->getOperand(0);
12358   SDValue V2 = SVOp->getOperand(1);
12359   EVT VT = SVOp->getValueType(0);
12360   int NumElems = VT.getVectorNumElements();
12361
12362   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12363       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12364     //
12365     //                   0,0,0,...
12366     //                      |
12367     //    V      UNDEF    BUILD_VECTOR    UNDEF
12368     //     \      /           \           /
12369     //  CONCAT_VECTOR         CONCAT_VECTOR
12370     //         \                  /
12371     //          \                /
12372     //          RESULT: V + zero extended
12373     //
12374     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12375         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12376         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12377       return SDValue();
12378
12379     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12380       return SDValue();
12381
12382     // To match the shuffle mask, the first half of the mask should
12383     // be exactly the first vector, and all the rest a splat with the
12384     // first element of the second one.
12385     for (int i = 0; i < NumElems/2; ++i)
12386       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12387           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12388         return SDValue();
12389
12390     // Emit a zeroed vector and insert the desired subvector on its
12391     // first half.
12392     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
12393     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12394                          DAG.getConstant(0, MVT::i32), DAG, dl);
12395     return DCI.CombineTo(N, InsV);
12396   }
12397
12398   //===--------------------------------------------------------------------===//
12399   // Combine some shuffles into subvector extracts and inserts:
12400   //
12401
12402   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12403   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12404     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12405                                     DAG, dl);
12406     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12407                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12408     return DCI.CombineTo(N, InsV);
12409   }
12410
12411   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12412   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12413     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12414     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12415                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12416     return DCI.CombineTo(N, InsV);
12417   }
12418
12419   return SDValue();
12420 }
12421
12422 /// PerformShuffleCombine - Performs several different shuffle combines.
12423 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12424                                      TargetLowering::DAGCombinerInfo &DCI,
12425                                      const X86Subtarget *Subtarget) {
12426   DebugLoc dl = N->getDebugLoc();
12427   EVT VT = N->getValueType(0);
12428
12429   // Don't create instructions with illegal types after legalize types has run.
12430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12431   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12432     return SDValue();
12433
12434   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12435   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12436       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12437     return PerformShuffleCombine256(N, DAG, DCI);
12438
12439   // Only handle 128 wide vector from here on.
12440   if (VT.getSizeInBits() != 128)
12441     return SDValue();
12442
12443   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12444   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12445   // consecutive, non-overlapping, and in the right order.
12446   SmallVector<SDValue, 16> Elts;
12447   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12448     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12449
12450   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12451 }
12452
12453 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12454 /// generation and convert it from being a bunch of shuffles and extracts
12455 /// to a simple store and scalar loads to extract the elements.
12456 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12457                                                 const TargetLowering &TLI) {
12458   SDValue InputVector = N->getOperand(0);
12459
12460   // Only operate on vectors of 4 elements, where the alternative shuffling
12461   // gets to be more expensive.
12462   if (InputVector.getValueType() != MVT::v4i32)
12463     return SDValue();
12464
12465   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12466   // single use which is a sign-extend or zero-extend, and all elements are
12467   // used.
12468   SmallVector<SDNode *, 4> Uses;
12469   unsigned ExtractedElements = 0;
12470   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12471        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12472     if (UI.getUse().getResNo() != InputVector.getResNo())
12473       return SDValue();
12474
12475     SDNode *Extract = *UI;
12476     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12477       return SDValue();
12478
12479     if (Extract->getValueType(0) != MVT::i32)
12480       return SDValue();
12481     if (!Extract->hasOneUse())
12482       return SDValue();
12483     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12484         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12485       return SDValue();
12486     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12487       return SDValue();
12488
12489     // Record which element was extracted.
12490     ExtractedElements |=
12491       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12492
12493     Uses.push_back(Extract);
12494   }
12495
12496   // If not all the elements were used, this may not be worthwhile.
12497   if (ExtractedElements != 15)
12498     return SDValue();
12499
12500   // Ok, we've now decided to do the transformation.
12501   DebugLoc dl = InputVector.getDebugLoc();
12502
12503   // Store the value to a temporary stack slot.
12504   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12505   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12506                             MachinePointerInfo(), false, false, 0);
12507
12508   // Replace each use (extract) with a load of the appropriate element.
12509   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12510        UE = Uses.end(); UI != UE; ++UI) {
12511     SDNode *Extract = *UI;
12512
12513     // cOMpute the element's address.
12514     SDValue Idx = Extract->getOperand(1);
12515     unsigned EltSize =
12516         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12517     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12518     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12519
12520     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12521                                      StackPtr, OffsetVal);
12522
12523     // Load the scalar.
12524     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12525                                      ScalarAddr, MachinePointerInfo(),
12526                                      false, false, 0);
12527
12528     // Replace the exact with the load.
12529     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12530   }
12531
12532   // The replacement was made in place; don't return anything.
12533   return SDValue();
12534 }
12535
12536 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12537 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12538                                     const X86Subtarget *Subtarget) {
12539   DebugLoc DL = N->getDebugLoc();
12540   SDValue Cond = N->getOperand(0);
12541   // Get the LHS/RHS of the select.
12542   SDValue LHS = N->getOperand(1);
12543   SDValue RHS = N->getOperand(2);
12544
12545   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12546   // instructions match the semantics of the common C idiom x<y?x:y but not
12547   // x<=y?x:y, because of how they handle negative zero (which can be
12548   // ignored in unsafe-math mode).
12549   if (Subtarget->hasSSE2() &&
12550       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12551       Cond.getOpcode() == ISD::SETCC) {
12552     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12553
12554     unsigned Opcode = 0;
12555     // Check for x CC y ? x : y.
12556     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12557         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12558       switch (CC) {
12559       default: break;
12560       case ISD::SETULT:
12561         // Converting this to a min would handle NaNs incorrectly, and swapping
12562         // the operands would cause it to handle comparisons between positive
12563         // and negative zero incorrectly.
12564         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12565           if (!UnsafeFPMath &&
12566               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12567             break;
12568           std::swap(LHS, RHS);
12569         }
12570         Opcode = X86ISD::FMIN;
12571         break;
12572       case ISD::SETOLE:
12573         // Converting this to a min would handle comparisons between positive
12574         // and negative zero incorrectly.
12575         if (!UnsafeFPMath &&
12576             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12577           break;
12578         Opcode = X86ISD::FMIN;
12579         break;
12580       case ISD::SETULE:
12581         // Converting this to a min would handle both negative zeros and NaNs
12582         // incorrectly, but we can swap the operands to fix both.
12583         std::swap(LHS, RHS);
12584       case ISD::SETOLT:
12585       case ISD::SETLT:
12586       case ISD::SETLE:
12587         Opcode = X86ISD::FMIN;
12588         break;
12589
12590       case ISD::SETOGE:
12591         // Converting this to a max would handle comparisons between positive
12592         // and negative zero incorrectly.
12593         if (!UnsafeFPMath &&
12594             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12595           break;
12596         Opcode = X86ISD::FMAX;
12597         break;
12598       case ISD::SETUGT:
12599         // Converting this to a max would handle NaNs incorrectly, and swapping
12600         // the operands would cause it to handle comparisons between positive
12601         // and negative zero incorrectly.
12602         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12603           if (!UnsafeFPMath &&
12604               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12605             break;
12606           std::swap(LHS, RHS);
12607         }
12608         Opcode = X86ISD::FMAX;
12609         break;
12610       case ISD::SETUGE:
12611         // Converting this to a max would handle both negative zeros and NaNs
12612         // incorrectly, but we can swap the operands to fix both.
12613         std::swap(LHS, RHS);
12614       case ISD::SETOGT:
12615       case ISD::SETGT:
12616       case ISD::SETGE:
12617         Opcode = X86ISD::FMAX;
12618         break;
12619       }
12620     // Check for x CC y ? y : x -- a min/max with reversed arms.
12621     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12622                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12623       switch (CC) {
12624       default: break;
12625       case ISD::SETOGE:
12626         // Converting this to a min would handle comparisons between positive
12627         // and negative zero incorrectly, and swapping the operands would
12628         // cause it to handle NaNs incorrectly.
12629         if (!UnsafeFPMath &&
12630             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12631           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12632             break;
12633           std::swap(LHS, RHS);
12634         }
12635         Opcode = X86ISD::FMIN;
12636         break;
12637       case ISD::SETUGT:
12638         // Converting this to a min would handle NaNs incorrectly.
12639         if (!UnsafeFPMath &&
12640             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12641           break;
12642         Opcode = X86ISD::FMIN;
12643         break;
12644       case ISD::SETUGE:
12645         // Converting this to a min would handle both negative zeros and NaNs
12646         // incorrectly, but we can swap the operands to fix both.
12647         std::swap(LHS, RHS);
12648       case ISD::SETOGT:
12649       case ISD::SETGT:
12650       case ISD::SETGE:
12651         Opcode = X86ISD::FMIN;
12652         break;
12653
12654       case ISD::SETULT:
12655         // Converting this to a max would handle NaNs incorrectly.
12656         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12657           break;
12658         Opcode = X86ISD::FMAX;
12659         break;
12660       case ISD::SETOLE:
12661         // Converting this to a max would handle comparisons between positive
12662         // and negative zero incorrectly, and swapping the operands would
12663         // cause it to handle NaNs incorrectly.
12664         if (!UnsafeFPMath &&
12665             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12666           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12667             break;
12668           std::swap(LHS, RHS);
12669         }
12670         Opcode = X86ISD::FMAX;
12671         break;
12672       case ISD::SETULE:
12673         // Converting this to a max would handle both negative zeros and NaNs
12674         // incorrectly, but we can swap the operands to fix both.
12675         std::swap(LHS, RHS);
12676       case ISD::SETOLT:
12677       case ISD::SETLT:
12678       case ISD::SETLE:
12679         Opcode = X86ISD::FMAX;
12680         break;
12681       }
12682     }
12683
12684     if (Opcode)
12685       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12686   }
12687
12688   // If this is a select between two integer constants, try to do some
12689   // optimizations.
12690   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12691     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12692       // Don't do this for crazy integer types.
12693       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12694         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12695         // so that TrueC (the true value) is larger than FalseC.
12696         bool NeedsCondInvert = false;
12697
12698         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12699             // Efficiently invertible.
12700             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12701              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12702               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12703           NeedsCondInvert = true;
12704           std::swap(TrueC, FalseC);
12705         }
12706
12707         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12708         if (FalseC->getAPIntValue() == 0 &&
12709             TrueC->getAPIntValue().isPowerOf2()) {
12710           if (NeedsCondInvert) // Invert the condition if needed.
12711             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12712                                DAG.getConstant(1, Cond.getValueType()));
12713
12714           // Zero extend the condition if needed.
12715           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12716
12717           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12718           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12719                              DAG.getConstant(ShAmt, MVT::i8));
12720         }
12721
12722         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12723         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12724           if (NeedsCondInvert) // Invert the condition if needed.
12725             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12726                                DAG.getConstant(1, Cond.getValueType()));
12727
12728           // Zero extend the condition if needed.
12729           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12730                              FalseC->getValueType(0), Cond);
12731           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12732                              SDValue(FalseC, 0));
12733         }
12734
12735         // Optimize cases that will turn into an LEA instruction.  This requires
12736         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12737         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12738           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12739           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12740
12741           bool isFastMultiplier = false;
12742           if (Diff < 10) {
12743             switch ((unsigned char)Diff) {
12744               default: break;
12745               case 1:  // result = add base, cond
12746               case 2:  // result = lea base(    , cond*2)
12747               case 3:  // result = lea base(cond, cond*2)
12748               case 4:  // result = lea base(    , cond*4)
12749               case 5:  // result = lea base(cond, cond*4)
12750               case 8:  // result = lea base(    , cond*8)
12751               case 9:  // result = lea base(cond, cond*8)
12752                 isFastMultiplier = true;
12753                 break;
12754             }
12755           }
12756
12757           if (isFastMultiplier) {
12758             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12759             if (NeedsCondInvert) // Invert the condition if needed.
12760               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12761                                  DAG.getConstant(1, Cond.getValueType()));
12762
12763             // Zero extend the condition if needed.
12764             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12765                                Cond);
12766             // Scale the condition by the difference.
12767             if (Diff != 1)
12768               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12769                                  DAG.getConstant(Diff, Cond.getValueType()));
12770
12771             // Add the base if non-zero.
12772             if (FalseC->getAPIntValue() != 0)
12773               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12774                                  SDValue(FalseC, 0));
12775             return Cond;
12776           }
12777         }
12778       }
12779   }
12780
12781   return SDValue();
12782 }
12783
12784 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12785 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12786                                   TargetLowering::DAGCombinerInfo &DCI) {
12787   DebugLoc DL = N->getDebugLoc();
12788
12789   // If the flag operand isn't dead, don't touch this CMOV.
12790   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12791     return SDValue();
12792
12793   SDValue FalseOp = N->getOperand(0);
12794   SDValue TrueOp = N->getOperand(1);
12795   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12796   SDValue Cond = N->getOperand(3);
12797   if (CC == X86::COND_E || CC == X86::COND_NE) {
12798     switch (Cond.getOpcode()) {
12799     default: break;
12800     case X86ISD::BSR:
12801     case X86ISD::BSF:
12802       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12803       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12804         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12805     }
12806   }
12807
12808   // If this is a select between two integer constants, try to do some
12809   // optimizations.  Note that the operands are ordered the opposite of SELECT
12810   // operands.
12811   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12812     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12813       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12814       // larger than FalseC (the false value).
12815       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12816         CC = X86::GetOppositeBranchCondition(CC);
12817         std::swap(TrueC, FalseC);
12818       }
12819
12820       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12821       // This is efficient for any integer data type (including i8/i16) and
12822       // shift amount.
12823       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12824         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12825                            DAG.getConstant(CC, MVT::i8), Cond);
12826
12827         // Zero extend the condition if needed.
12828         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12829
12830         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12831         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12832                            DAG.getConstant(ShAmt, MVT::i8));
12833         if (N->getNumValues() == 2)  // Dead flag value?
12834           return DCI.CombineTo(N, Cond, SDValue());
12835         return Cond;
12836       }
12837
12838       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12839       // for any integer data type, including i8/i16.
12840       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12841         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12842                            DAG.getConstant(CC, MVT::i8), Cond);
12843
12844         // Zero extend the condition if needed.
12845         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12846                            FalseC->getValueType(0), Cond);
12847         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12848                            SDValue(FalseC, 0));
12849
12850         if (N->getNumValues() == 2)  // Dead flag value?
12851           return DCI.CombineTo(N, Cond, SDValue());
12852         return Cond;
12853       }
12854
12855       // Optimize cases that will turn into an LEA instruction.  This requires
12856       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12857       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12858         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12859         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12860
12861         bool isFastMultiplier = false;
12862         if (Diff < 10) {
12863           switch ((unsigned char)Diff) {
12864           default: break;
12865           case 1:  // result = add base, cond
12866           case 2:  // result = lea base(    , cond*2)
12867           case 3:  // result = lea base(cond, cond*2)
12868           case 4:  // result = lea base(    , cond*4)
12869           case 5:  // result = lea base(cond, cond*4)
12870           case 8:  // result = lea base(    , cond*8)
12871           case 9:  // result = lea base(cond, cond*8)
12872             isFastMultiplier = true;
12873             break;
12874           }
12875         }
12876
12877         if (isFastMultiplier) {
12878           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12879           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12880                              DAG.getConstant(CC, MVT::i8), Cond);
12881           // Zero extend the condition if needed.
12882           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12883                              Cond);
12884           // Scale the condition by the difference.
12885           if (Diff != 1)
12886             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12887                                DAG.getConstant(Diff, Cond.getValueType()));
12888
12889           // Add the base if non-zero.
12890           if (FalseC->getAPIntValue() != 0)
12891             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12892                                SDValue(FalseC, 0));
12893           if (N->getNumValues() == 2)  // Dead flag value?
12894             return DCI.CombineTo(N, Cond, SDValue());
12895           return Cond;
12896         }
12897       }
12898     }
12899   }
12900   return SDValue();
12901 }
12902
12903
12904 /// PerformMulCombine - Optimize a single multiply with constant into two
12905 /// in order to implement it with two cheaper instructions, e.g.
12906 /// LEA + SHL, LEA + LEA.
12907 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12908                                  TargetLowering::DAGCombinerInfo &DCI) {
12909   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12910     return SDValue();
12911
12912   EVT VT = N->getValueType(0);
12913   if (VT != MVT::i64)
12914     return SDValue();
12915
12916   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12917   if (!C)
12918     return SDValue();
12919   uint64_t MulAmt = C->getZExtValue();
12920   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12921     return SDValue();
12922
12923   uint64_t MulAmt1 = 0;
12924   uint64_t MulAmt2 = 0;
12925   if ((MulAmt % 9) == 0) {
12926     MulAmt1 = 9;
12927     MulAmt2 = MulAmt / 9;
12928   } else if ((MulAmt % 5) == 0) {
12929     MulAmt1 = 5;
12930     MulAmt2 = MulAmt / 5;
12931   } else if ((MulAmt % 3) == 0) {
12932     MulAmt1 = 3;
12933     MulAmt2 = MulAmt / 3;
12934   }
12935   if (MulAmt2 &&
12936       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12937     DebugLoc DL = N->getDebugLoc();
12938
12939     if (isPowerOf2_64(MulAmt2) &&
12940         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12941       // If second multiplifer is pow2, issue it first. We want the multiply by
12942       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12943       // is an add.
12944       std::swap(MulAmt1, MulAmt2);
12945
12946     SDValue NewMul;
12947     if (isPowerOf2_64(MulAmt1))
12948       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12949                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12950     else
12951       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12952                            DAG.getConstant(MulAmt1, VT));
12953
12954     if (isPowerOf2_64(MulAmt2))
12955       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12956                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12957     else
12958       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12959                            DAG.getConstant(MulAmt2, VT));
12960
12961     // Do not add new nodes to DAG combiner worklist.
12962     DCI.CombineTo(N, NewMul, false);
12963   }
12964   return SDValue();
12965 }
12966
12967 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12968   SDValue N0 = N->getOperand(0);
12969   SDValue N1 = N->getOperand(1);
12970   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12971   EVT VT = N0.getValueType();
12972
12973   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12974   // since the result of setcc_c is all zero's or all ones.
12975   if (N1C && N0.getOpcode() == ISD::AND &&
12976       N0.getOperand(1).getOpcode() == ISD::Constant) {
12977     SDValue N00 = N0.getOperand(0);
12978     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12979         ((N00.getOpcode() == ISD::ANY_EXTEND ||
12980           N00.getOpcode() == ISD::ZERO_EXTEND) &&
12981          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12982       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12983       APInt ShAmt = N1C->getAPIntValue();
12984       Mask = Mask.shl(ShAmt);
12985       if (Mask != 0)
12986         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12987                            N00, DAG.getConstant(Mask, VT));
12988     }
12989   }
12990
12991   return SDValue();
12992 }
12993
12994 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12995 ///                       when possible.
12996 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12997                                    const X86Subtarget *Subtarget) {
12998   EVT VT = N->getValueType(0);
12999   if (!VT.isVector() && VT.isInteger() &&
13000       N->getOpcode() == ISD::SHL)
13001     return PerformSHLCombine(N, DAG);
13002
13003   // On X86 with SSE2 support, we can transform this to a vector shift if
13004   // all elements are shifted by the same amount.  We can't do this in legalize
13005   // because the a constant vector is typically transformed to a constant pool
13006   // so we have no knowledge of the shift amount.
13007   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
13008     return SDValue();
13009
13010   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13011     return SDValue();
13012
13013   SDValue ShAmtOp = N->getOperand(1);
13014   EVT EltVT = VT.getVectorElementType();
13015   DebugLoc DL = N->getDebugLoc();
13016   SDValue BaseShAmt = SDValue();
13017   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13018     unsigned NumElts = VT.getVectorNumElements();
13019     unsigned i = 0;
13020     for (; i != NumElts; ++i) {
13021       SDValue Arg = ShAmtOp.getOperand(i);
13022       if (Arg.getOpcode() == ISD::UNDEF) continue;
13023       BaseShAmt = Arg;
13024       break;
13025     }
13026     for (; i != NumElts; ++i) {
13027       SDValue Arg = ShAmtOp.getOperand(i);
13028       if (Arg.getOpcode() == ISD::UNDEF) continue;
13029       if (Arg != BaseShAmt) {
13030         return SDValue();
13031       }
13032     }
13033   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13034              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13035     SDValue InVec = ShAmtOp.getOperand(0);
13036     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13037       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13038       unsigned i = 0;
13039       for (; i != NumElts; ++i) {
13040         SDValue Arg = InVec.getOperand(i);
13041         if (Arg.getOpcode() == ISD::UNDEF) continue;
13042         BaseShAmt = Arg;
13043         break;
13044       }
13045     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13046        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13047          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13048          if (C->getZExtValue() == SplatIdx)
13049            BaseShAmt = InVec.getOperand(1);
13050        }
13051     }
13052     if (BaseShAmt.getNode() == 0)
13053       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13054                               DAG.getIntPtrConstant(0));
13055   } else
13056     return SDValue();
13057
13058   // The shift amount is an i32.
13059   if (EltVT.bitsGT(MVT::i32))
13060     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13061   else if (EltVT.bitsLT(MVT::i32))
13062     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13063
13064   // The shift amount is identical so we can do a vector shift.
13065   SDValue  ValOp = N->getOperand(0);
13066   switch (N->getOpcode()) {
13067   default:
13068     llvm_unreachable("Unknown shift opcode!");
13069     break;
13070   case ISD::SHL:
13071     if (VT == MVT::v2i64)
13072       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13073                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13074                          ValOp, BaseShAmt);
13075     if (VT == MVT::v4i32)
13076       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13077                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13078                          ValOp, BaseShAmt);
13079     if (VT == MVT::v8i16)
13080       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13081                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13082                          ValOp, BaseShAmt);
13083     break;
13084   case ISD::SRA:
13085     if (VT == MVT::v4i32)
13086       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13087                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13088                          ValOp, BaseShAmt);
13089     if (VT == MVT::v8i16)
13090       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13091                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13092                          ValOp, BaseShAmt);
13093     break;
13094   case ISD::SRL:
13095     if (VT == MVT::v2i64)
13096       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13097                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13098                          ValOp, BaseShAmt);
13099     if (VT == MVT::v4i32)
13100       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13101                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13102                          ValOp, BaseShAmt);
13103     if (VT ==  MVT::v8i16)
13104       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13105                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13106                          ValOp, BaseShAmt);
13107     break;
13108   }
13109   return SDValue();
13110 }
13111
13112
13113 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13114 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13115 // and friends.  Likewise for OR -> CMPNEQSS.
13116 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13117                             TargetLowering::DAGCombinerInfo &DCI,
13118                             const X86Subtarget *Subtarget) {
13119   unsigned opcode;
13120
13121   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13122   // we're requiring SSE2 for both.
13123   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13124     SDValue N0 = N->getOperand(0);
13125     SDValue N1 = N->getOperand(1);
13126     SDValue CMP0 = N0->getOperand(1);
13127     SDValue CMP1 = N1->getOperand(1);
13128     DebugLoc DL = N->getDebugLoc();
13129
13130     // The SETCCs should both refer to the same CMP.
13131     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13132       return SDValue();
13133
13134     SDValue CMP00 = CMP0->getOperand(0);
13135     SDValue CMP01 = CMP0->getOperand(1);
13136     EVT     VT    = CMP00.getValueType();
13137
13138     if (VT == MVT::f32 || VT == MVT::f64) {
13139       bool ExpectingFlags = false;
13140       // Check for any users that want flags:
13141       for (SDNode::use_iterator UI = N->use_begin(),
13142              UE = N->use_end();
13143            !ExpectingFlags && UI != UE; ++UI)
13144         switch (UI->getOpcode()) {
13145         default:
13146         case ISD::BR_CC:
13147         case ISD::BRCOND:
13148         case ISD::SELECT:
13149           ExpectingFlags = true;
13150           break;
13151         case ISD::CopyToReg:
13152         case ISD::SIGN_EXTEND:
13153         case ISD::ZERO_EXTEND:
13154         case ISD::ANY_EXTEND:
13155           break;
13156         }
13157
13158       if (!ExpectingFlags) {
13159         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13160         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13161
13162         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13163           X86::CondCode tmp = cc0;
13164           cc0 = cc1;
13165           cc1 = tmp;
13166         }
13167
13168         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13169             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13170           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13171           X86ISD::NodeType NTOperator = is64BitFP ?
13172             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13173           // FIXME: need symbolic constants for these magic numbers.
13174           // See X86ATTInstPrinter.cpp:printSSECC().
13175           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13176           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13177                                               DAG.getConstant(x86cc, MVT::i8));
13178           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13179                                               OnesOrZeroesF);
13180           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13181                                       DAG.getConstant(1, MVT::i32));
13182           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13183           return OneBitOfTruth;
13184         }
13185       }
13186     }
13187   }
13188   return SDValue();
13189 }
13190
13191 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13192 /// so it can be folded inside ANDNP.
13193 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13194   EVT VT = N->getValueType(0);
13195
13196   // Match direct AllOnes for 128 and 256-bit vectors
13197   if (ISD::isBuildVectorAllOnes(N))
13198     return true;
13199
13200   // Look through a bit convert.
13201   if (N->getOpcode() == ISD::BITCAST)
13202     N = N->getOperand(0).getNode();
13203
13204   // Sometimes the operand may come from a insert_subvector building a 256-bit
13205   // allones vector
13206   if (VT.getSizeInBits() == 256 &&
13207       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13208     SDValue V1 = N->getOperand(0);
13209     SDValue V2 = N->getOperand(1);
13210
13211     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13212         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13213         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13214         ISD::isBuildVectorAllOnes(V2.getNode()))
13215       return true;
13216   }
13217
13218   return false;
13219 }
13220
13221 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13222                                  TargetLowering::DAGCombinerInfo &DCI,
13223                                  const X86Subtarget *Subtarget) {
13224   if (DCI.isBeforeLegalizeOps())
13225     return SDValue();
13226
13227   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13228   if (R.getNode())
13229     return R;
13230
13231   // Want to form ANDNP nodes:
13232   // 1) In the hopes of then easily combining them with OR and AND nodes
13233   //    to form PBLEND/PSIGN.
13234   // 2) To match ANDN packed intrinsics
13235   EVT VT = N->getValueType(0);
13236   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13237     return SDValue();
13238
13239   SDValue N0 = N->getOperand(0);
13240   SDValue N1 = N->getOperand(1);
13241   DebugLoc DL = N->getDebugLoc();
13242
13243   // Check LHS for vnot
13244   if (N0.getOpcode() == ISD::XOR &&
13245       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13246       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13247     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13248
13249   // Check RHS for vnot
13250   if (N1.getOpcode() == ISD::XOR &&
13251       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13252       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13253     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13254
13255   return SDValue();
13256 }
13257
13258 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13259                                 TargetLowering::DAGCombinerInfo &DCI,
13260                                 const X86Subtarget *Subtarget) {
13261   if (DCI.isBeforeLegalizeOps())
13262     return SDValue();
13263
13264   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13265   if (R.getNode())
13266     return R;
13267
13268   EVT VT = N->getValueType(0);
13269   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13270     return SDValue();
13271
13272   SDValue N0 = N->getOperand(0);
13273   SDValue N1 = N->getOperand(1);
13274
13275   // look for psign/blend
13276   if (Subtarget->hasSSSE3()) {
13277     if (VT == MVT::v2i64) {
13278       // Canonicalize pandn to RHS
13279       if (N0.getOpcode() == X86ISD::ANDNP)
13280         std::swap(N0, N1);
13281       // or (and (m, x), (pandn m, y))
13282       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13283         SDValue Mask = N1.getOperand(0);
13284         SDValue X    = N1.getOperand(1);
13285         SDValue Y;
13286         if (N0.getOperand(0) == Mask)
13287           Y = N0.getOperand(1);
13288         if (N0.getOperand(1) == Mask)
13289           Y = N0.getOperand(0);
13290
13291         // Check to see if the mask appeared in both the AND and ANDNP and
13292         if (!Y.getNode())
13293           return SDValue();
13294
13295         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13296         if (Mask.getOpcode() != ISD::BITCAST ||
13297             X.getOpcode() != ISD::BITCAST ||
13298             Y.getOpcode() != ISD::BITCAST)
13299           return SDValue();
13300
13301         // Look through mask bitcast.
13302         Mask = Mask.getOperand(0);
13303         EVT MaskVT = Mask.getValueType();
13304
13305         // Validate that the Mask operand is a vector sra node.  The sra node
13306         // will be an intrinsic.
13307         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13308           return SDValue();
13309
13310         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13311         // there is no psrai.b
13312         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13313         case Intrinsic::x86_sse2_psrai_w:
13314         case Intrinsic::x86_sse2_psrai_d:
13315           break;
13316         default: return SDValue();
13317         }
13318
13319         // Check that the SRA is all signbits.
13320         SDValue SraC = Mask.getOperand(2);
13321         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13322         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13323         if ((SraAmt + 1) != EltBits)
13324           return SDValue();
13325
13326         DebugLoc DL = N->getDebugLoc();
13327
13328         // Now we know we at least have a plendvb with the mask val.  See if
13329         // we can form a psignb/w/d.
13330         // psign = x.type == y.type == mask.type && y = sub(0, x);
13331         X = X.getOperand(0);
13332         Y = Y.getOperand(0);
13333         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13334             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13335             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13336           unsigned Opc = 0;
13337           switch (EltBits) {
13338           case 8: Opc = X86ISD::PSIGNB; break;
13339           case 16: Opc = X86ISD::PSIGNW; break;
13340           case 32: Opc = X86ISD::PSIGND; break;
13341           default: break;
13342           }
13343           if (Opc) {
13344             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13345             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13346           }
13347         }
13348         // PBLENDVB only available on SSE 4.1
13349         if (!Subtarget->hasSSE41())
13350           return SDValue();
13351
13352         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13353         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13354         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13355         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13356         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13357       }
13358     }
13359   }
13360
13361   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13362   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13363     std::swap(N0, N1);
13364   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13365     return SDValue();
13366   if (!N0.hasOneUse() || !N1.hasOneUse())
13367     return SDValue();
13368
13369   SDValue ShAmt0 = N0.getOperand(1);
13370   if (ShAmt0.getValueType() != MVT::i8)
13371     return SDValue();
13372   SDValue ShAmt1 = N1.getOperand(1);
13373   if (ShAmt1.getValueType() != MVT::i8)
13374     return SDValue();
13375   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13376     ShAmt0 = ShAmt0.getOperand(0);
13377   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13378     ShAmt1 = ShAmt1.getOperand(0);
13379
13380   DebugLoc DL = N->getDebugLoc();
13381   unsigned Opc = X86ISD::SHLD;
13382   SDValue Op0 = N0.getOperand(0);
13383   SDValue Op1 = N1.getOperand(0);
13384   if (ShAmt0.getOpcode() == ISD::SUB) {
13385     Opc = X86ISD::SHRD;
13386     std::swap(Op0, Op1);
13387     std::swap(ShAmt0, ShAmt1);
13388   }
13389
13390   unsigned Bits = VT.getSizeInBits();
13391   if (ShAmt1.getOpcode() == ISD::SUB) {
13392     SDValue Sum = ShAmt1.getOperand(0);
13393     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13394       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13395       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13396         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13397       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13398         return DAG.getNode(Opc, DL, VT,
13399                            Op0, Op1,
13400                            DAG.getNode(ISD::TRUNCATE, DL,
13401                                        MVT::i8, ShAmt0));
13402     }
13403   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13404     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13405     if (ShAmt0C &&
13406         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13407       return DAG.getNode(Opc, DL, VT,
13408                          N0.getOperand(0), N1.getOperand(0),
13409                          DAG.getNode(ISD::TRUNCATE, DL,
13410                                        MVT::i8, ShAmt0));
13411   }
13412
13413   return SDValue();
13414 }
13415
13416 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13417 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13418                                    const X86Subtarget *Subtarget) {
13419   StoreSDNode *St = cast<StoreSDNode>(N);
13420   EVT VT = St->getValue().getValueType();
13421   EVT StVT = St->getMemoryVT();
13422   DebugLoc dl = St->getDebugLoc();
13423   SDValue StoredVal = St->getOperand(1);
13424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13425
13426   // If we are saving a concatination of two XMM registers, perform two stores.
13427   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13428   // 128-bit ones. If in the future the cost becomes only one memory access the
13429   // first version would be better.
13430   if (VT.getSizeInBits() == 256 &&
13431     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13432     StoredVal.getNumOperands() == 2) {
13433
13434     SDValue Value0 = StoredVal.getOperand(0);
13435     SDValue Value1 = StoredVal.getOperand(1);
13436
13437     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13438     SDValue Ptr0 = St->getBasePtr();
13439     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13440
13441     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13442                                 St->getPointerInfo(), St->isVolatile(),
13443                                 St->isNonTemporal(), St->getAlignment());
13444     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13445                                 St->getPointerInfo(), St->isVolatile(),
13446                                 St->isNonTemporal(), St->getAlignment());
13447     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13448   }
13449
13450   // Optimize trunc store (of multiple scalars) to shuffle and store.
13451   // First, pack all of the elements in one place. Next, store to memory
13452   // in fewer chunks.
13453   if (St->isTruncatingStore() && VT.isVector()) {
13454     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13455     unsigned NumElems = VT.getVectorNumElements();
13456     assert(StVT != VT && "Cannot truncate to the same type");
13457     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13458     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13459
13460     // From, To sizes and ElemCount must be pow of two
13461     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13462     // We are going to use the original vector elt for storing.
13463     // accumulated smaller vector elements must be a multiple of bigger size.
13464     if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13465     unsigned SizeRatio  = FromSz / ToSz;
13466
13467     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13468
13469     // Create a type on which we perform the shuffle
13470     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13471             StVT.getScalarType(), NumElems*SizeRatio);
13472
13473     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13474
13475     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13476     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13477     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13478
13479     // Can't shuffle using an illegal type
13480     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13481
13482     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13483                                 DAG.getUNDEF(WideVec.getValueType()),
13484                                 ShuffleVec.data());
13485     // At this point all of the data is stored at the bottom of the
13486     // register. We now need to save it to mem.
13487
13488     // Find the largest store unit
13489     MVT StoreType = MVT::i8;
13490     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13491          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13492       MVT Tp = (MVT::SimpleValueType)tp;
13493       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13494         StoreType = Tp;
13495     }
13496
13497     // Bitcast the original vector into a vector of store-size units
13498     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13499             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13500     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13501     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13502     SmallVector<SDValue, 8> Chains;
13503     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13504                                         TLI.getPointerTy());
13505     SDValue Ptr = St->getBasePtr();
13506
13507     // Perform one or more big stores into memory.
13508     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13509       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13510                                    StoreType, ShuffWide,
13511                                    DAG.getIntPtrConstant(i));
13512       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13513                                 St->getPointerInfo(), St->isVolatile(),
13514                                 St->isNonTemporal(), St->getAlignment());
13515       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13516       Chains.push_back(Ch);
13517     }
13518
13519     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13520                                Chains.size());
13521   }
13522
13523
13524   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13525   // the FP state in cases where an emms may be missing.
13526   // A preferable solution to the general problem is to figure out the right
13527   // places to insert EMMS.  This qualifies as a quick hack.
13528
13529   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13530   if (VT.getSizeInBits() != 64)
13531     return SDValue();
13532
13533   const Function *F = DAG.getMachineFunction().getFunction();
13534   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13535   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13536     && Subtarget->hasSSE2();
13537   if ((VT.isVector() ||
13538        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13539       isa<LoadSDNode>(St->getValue()) &&
13540       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13541       St->getChain().hasOneUse() && !St->isVolatile()) {
13542     SDNode* LdVal = St->getValue().getNode();
13543     LoadSDNode *Ld = 0;
13544     int TokenFactorIndex = -1;
13545     SmallVector<SDValue, 8> Ops;
13546     SDNode* ChainVal = St->getChain().getNode();
13547     // Must be a store of a load.  We currently handle two cases:  the load
13548     // is a direct child, and it's under an intervening TokenFactor.  It is
13549     // possible to dig deeper under nested TokenFactors.
13550     if (ChainVal == LdVal)
13551       Ld = cast<LoadSDNode>(St->getChain());
13552     else if (St->getValue().hasOneUse() &&
13553              ChainVal->getOpcode() == ISD::TokenFactor) {
13554       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13555         if (ChainVal->getOperand(i).getNode() == LdVal) {
13556           TokenFactorIndex = i;
13557           Ld = cast<LoadSDNode>(St->getValue());
13558         } else
13559           Ops.push_back(ChainVal->getOperand(i));
13560       }
13561     }
13562
13563     if (!Ld || !ISD::isNormalLoad(Ld))
13564       return SDValue();
13565
13566     // If this is not the MMX case, i.e. we are just turning i64 load/store
13567     // into f64 load/store, avoid the transformation if there are multiple
13568     // uses of the loaded value.
13569     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13570       return SDValue();
13571
13572     DebugLoc LdDL = Ld->getDebugLoc();
13573     DebugLoc StDL = N->getDebugLoc();
13574     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13575     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13576     // pair instead.
13577     if (Subtarget->is64Bit() || F64IsLegal) {
13578       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13579       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13580                                   Ld->getPointerInfo(), Ld->isVolatile(),
13581                                   Ld->isNonTemporal(), Ld->getAlignment());
13582       SDValue NewChain = NewLd.getValue(1);
13583       if (TokenFactorIndex != -1) {
13584         Ops.push_back(NewChain);
13585         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13586                                Ops.size());
13587       }
13588       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13589                           St->getPointerInfo(),
13590                           St->isVolatile(), St->isNonTemporal(),
13591                           St->getAlignment());
13592     }
13593
13594     // Otherwise, lower to two pairs of 32-bit loads / stores.
13595     SDValue LoAddr = Ld->getBasePtr();
13596     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13597                                  DAG.getConstant(4, MVT::i32));
13598
13599     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13600                                Ld->getPointerInfo(),
13601                                Ld->isVolatile(), Ld->isNonTemporal(),
13602                                Ld->getAlignment());
13603     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13604                                Ld->getPointerInfo().getWithOffset(4),
13605                                Ld->isVolatile(), Ld->isNonTemporal(),
13606                                MinAlign(Ld->getAlignment(), 4));
13607
13608     SDValue NewChain = LoLd.getValue(1);
13609     if (TokenFactorIndex != -1) {
13610       Ops.push_back(LoLd);
13611       Ops.push_back(HiLd);
13612       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13613                              Ops.size());
13614     }
13615
13616     LoAddr = St->getBasePtr();
13617     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13618                          DAG.getConstant(4, MVT::i32));
13619
13620     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13621                                 St->getPointerInfo(),
13622                                 St->isVolatile(), St->isNonTemporal(),
13623                                 St->getAlignment());
13624     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13625                                 St->getPointerInfo().getWithOffset(4),
13626                                 St->isVolatile(),
13627                                 St->isNonTemporal(),
13628                                 MinAlign(St->getAlignment(), 4));
13629     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13630   }
13631   return SDValue();
13632 }
13633
13634 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13635 /// X86ISD::FXOR nodes.
13636 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13637   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13638   // F[X]OR(0.0, x) -> x
13639   // F[X]OR(x, 0.0) -> x
13640   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13641     if (C->getValueAPF().isPosZero())
13642       return N->getOperand(1);
13643   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13644     if (C->getValueAPF().isPosZero())
13645       return N->getOperand(0);
13646   return SDValue();
13647 }
13648
13649 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13650 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13651   // FAND(0.0, x) -> 0.0
13652   // FAND(x, 0.0) -> 0.0
13653   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13654     if (C->getValueAPF().isPosZero())
13655       return N->getOperand(0);
13656   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13657     if (C->getValueAPF().isPosZero())
13658       return N->getOperand(1);
13659   return SDValue();
13660 }
13661
13662 static SDValue PerformBTCombine(SDNode *N,
13663                                 SelectionDAG &DAG,
13664                                 TargetLowering::DAGCombinerInfo &DCI) {
13665   // BT ignores high bits in the bit index operand.
13666   SDValue Op1 = N->getOperand(1);
13667   if (Op1.hasOneUse()) {
13668     unsigned BitWidth = Op1.getValueSizeInBits();
13669     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13670     APInt KnownZero, KnownOne;
13671     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13672                                           !DCI.isBeforeLegalizeOps());
13673     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13674     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13675         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13676       DCI.CommitTargetLoweringOpt(TLO);
13677   }
13678   return SDValue();
13679 }
13680
13681 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13682   SDValue Op = N->getOperand(0);
13683   if (Op.getOpcode() == ISD::BITCAST)
13684     Op = Op.getOperand(0);
13685   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13686   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13687       VT.getVectorElementType().getSizeInBits() ==
13688       OpVT.getVectorElementType().getSizeInBits()) {
13689     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13690   }
13691   return SDValue();
13692 }
13693
13694 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13695   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13696   //           (and (i32 x86isd::setcc_carry), 1)
13697   // This eliminates the zext. This transformation is necessary because
13698   // ISD::SETCC is always legalized to i8.
13699   DebugLoc dl = N->getDebugLoc();
13700   SDValue N0 = N->getOperand(0);
13701   EVT VT = N->getValueType(0);
13702   if (N0.getOpcode() == ISD::AND &&
13703       N0.hasOneUse() &&
13704       N0.getOperand(0).hasOneUse()) {
13705     SDValue N00 = N0.getOperand(0);
13706     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13707       return SDValue();
13708     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13709     if (!C || C->getZExtValue() != 1)
13710       return SDValue();
13711     return DAG.getNode(ISD::AND, dl, VT,
13712                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13713                                    N00.getOperand(0), N00.getOperand(1)),
13714                        DAG.getConstant(1, VT));
13715   }
13716
13717   return SDValue();
13718 }
13719
13720 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13721 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13722   unsigned X86CC = N->getConstantOperandVal(0);
13723   SDValue EFLAG = N->getOperand(1);
13724   DebugLoc DL = N->getDebugLoc();
13725
13726   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13727   // a zext and produces an all-ones bit which is more useful than 0/1 in some
13728   // cases.
13729   if (X86CC == X86::COND_B)
13730     return DAG.getNode(ISD::AND, DL, MVT::i8,
13731                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13732                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
13733                        DAG.getConstant(1, MVT::i8));
13734
13735   return SDValue();
13736 }
13737
13738 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13739                                         const X86TargetLowering *XTLI) {
13740   SDValue Op0 = N->getOperand(0);
13741   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13742   // a 32-bit target where SSE doesn't support i64->FP operations.
13743   if (Op0.getOpcode() == ISD::LOAD) {
13744     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13745     EVT VT = Ld->getValueType(0);
13746     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13747         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13748         !XTLI->getSubtarget()->is64Bit() &&
13749         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13750       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13751                                           Ld->getChain(), Op0, DAG);
13752       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13753       return FILDChain;
13754     }
13755   }
13756   return SDValue();
13757 }
13758
13759 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13760 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13761                                  X86TargetLowering::DAGCombinerInfo &DCI) {
13762   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13763   // the result is either zero or one (depending on the input carry bit).
13764   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13765   if (X86::isZeroNode(N->getOperand(0)) &&
13766       X86::isZeroNode(N->getOperand(1)) &&
13767       // We don't have a good way to replace an EFLAGS use, so only do this when
13768       // dead right now.
13769       SDValue(N, 1).use_empty()) {
13770     DebugLoc DL = N->getDebugLoc();
13771     EVT VT = N->getValueType(0);
13772     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13773     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13774                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13775                                            DAG.getConstant(X86::COND_B,MVT::i8),
13776                                            N->getOperand(2)),
13777                                DAG.getConstant(1, VT));
13778     return DCI.CombineTo(N, Res1, CarryOut);
13779   }
13780
13781   return SDValue();
13782 }
13783
13784 // fold (add Y, (sete  X, 0)) -> adc  0, Y
13785 //      (add Y, (setne X, 0)) -> sbb -1, Y
13786 //      (sub (sete  X, 0), Y) -> sbb  0, Y
13787 //      (sub (setne X, 0), Y) -> adc -1, Y
13788 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13789   DebugLoc DL = N->getDebugLoc();
13790
13791   // Look through ZExts.
13792   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13793   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13794     return SDValue();
13795
13796   SDValue SetCC = Ext.getOperand(0);
13797   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13798     return SDValue();
13799
13800   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13801   if (CC != X86::COND_E && CC != X86::COND_NE)
13802     return SDValue();
13803
13804   SDValue Cmp = SetCC.getOperand(1);
13805   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13806       !X86::isZeroNode(Cmp.getOperand(1)) ||
13807       !Cmp.getOperand(0).getValueType().isInteger())
13808     return SDValue();
13809
13810   SDValue CmpOp0 = Cmp.getOperand(0);
13811   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13812                                DAG.getConstant(1, CmpOp0.getValueType()));
13813
13814   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13815   if (CC == X86::COND_NE)
13816     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13817                        DL, OtherVal.getValueType(), OtherVal,
13818                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13819   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13820                      DL, OtherVal.getValueType(), OtherVal,
13821                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13822 }
13823
13824 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13825   SDValue Op0 = N->getOperand(0);
13826   SDValue Op1 = N->getOperand(1);
13827
13828   // X86 can't encode an immediate LHS of a sub. See if we can push the
13829   // negation into a preceding instruction.
13830   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13831     // If the RHS of the sub is a XOR with one use and a constant, invert the
13832     // immediate. Then add one to the LHS of the sub so we can turn
13833     // X-Y -> X+~Y+1, saving one register.
13834     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13835         isa<ConstantSDNode>(Op1.getOperand(1))) {
13836       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13837       EVT VT = Op0.getValueType();
13838       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13839                                    Op1.getOperand(0),
13840                                    DAG.getConstant(~XorC, VT));
13841       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13842                          DAG.getConstant(C->getAPIntValue()+1, VT));
13843     }
13844   }
13845
13846   return OptimizeConditionalInDecrement(N, DAG);
13847 }
13848
13849 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13850                                              DAGCombinerInfo &DCI) const {
13851   SelectionDAG &DAG = DCI.DAG;
13852   switch (N->getOpcode()) {
13853   default: break;
13854   case ISD::EXTRACT_VECTOR_ELT:
13855     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13856   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
13857   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
13858   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
13859   case ISD::SUB:            return PerformSubCombine(N, DAG);
13860   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
13861   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
13862   case ISD::SHL:
13863   case ISD::SRA:
13864   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
13865   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
13866   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
13867   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
13868   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
13869   case X86ISD::FXOR:
13870   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
13871   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
13872   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
13873   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
13874   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
13875   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
13876   case X86ISD::SHUFPS:      // Handle all target specific shuffles
13877   case X86ISD::SHUFPD:
13878   case X86ISD::PALIGN:
13879   case X86ISD::PUNPCKHBW:
13880   case X86ISD::PUNPCKHWD:
13881   case X86ISD::PUNPCKHDQ:
13882   case X86ISD::PUNPCKHQDQ:
13883   case X86ISD::UNPCKHPS:
13884   case X86ISD::UNPCKHPD:
13885   case X86ISD::VUNPCKHPSY:
13886   case X86ISD::VUNPCKHPDY:
13887   case X86ISD::PUNPCKLBW:
13888   case X86ISD::PUNPCKLWD:
13889   case X86ISD::PUNPCKLDQ:
13890   case X86ISD::PUNPCKLQDQ:
13891   case X86ISD::UNPCKLPS:
13892   case X86ISD::UNPCKLPD:
13893   case X86ISD::VUNPCKLPSY:
13894   case X86ISD::VUNPCKLPDY:
13895   case X86ISD::MOVHLPS:
13896   case X86ISD::MOVLHPS:
13897   case X86ISD::PSHUFD:
13898   case X86ISD::PSHUFHW:
13899   case X86ISD::PSHUFLW:
13900   case X86ISD::MOVSS:
13901   case X86ISD::MOVSD:
13902   case X86ISD::VPERMILPS:
13903   case X86ISD::VPERMILPSY:
13904   case X86ISD::VPERMILPD:
13905   case X86ISD::VPERMILPDY:
13906   case X86ISD::VPERM2F128:
13907   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13908   }
13909
13910   return SDValue();
13911 }
13912
13913 /// isTypeDesirableForOp - Return true if the target has native support for
13914 /// the specified value type and it is 'desirable' to use the type for the
13915 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13916 /// instruction encodings are longer and some i16 instructions are slow.
13917 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13918   if (!isTypeLegal(VT))
13919     return false;
13920   if (VT != MVT::i16)
13921     return true;
13922
13923   switch (Opc) {
13924   default:
13925     return true;
13926   case ISD::LOAD:
13927   case ISD::SIGN_EXTEND:
13928   case ISD::ZERO_EXTEND:
13929   case ISD::ANY_EXTEND:
13930   case ISD::SHL:
13931   case ISD::SRL:
13932   case ISD::SUB:
13933   case ISD::ADD:
13934   case ISD::MUL:
13935   case ISD::AND:
13936   case ISD::OR:
13937   case ISD::XOR:
13938     return false;
13939   }
13940 }
13941
13942 /// IsDesirableToPromoteOp - This method query the target whether it is
13943 /// beneficial for dag combiner to promote the specified node. If true, it
13944 /// should return the desired promotion type by reference.
13945 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13946   EVT VT = Op.getValueType();
13947   if (VT != MVT::i16)
13948     return false;
13949
13950   bool Promote = false;
13951   bool Commute = false;
13952   switch (Op.getOpcode()) {
13953   default: break;
13954   case ISD::LOAD: {
13955     LoadSDNode *LD = cast<LoadSDNode>(Op);
13956     // If the non-extending load has a single use and it's not live out, then it
13957     // might be folded.
13958     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13959                                                      Op.hasOneUse()*/) {
13960       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13961              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13962         // The only case where we'd want to promote LOAD (rather then it being
13963         // promoted as an operand is when it's only use is liveout.
13964         if (UI->getOpcode() != ISD::CopyToReg)
13965           return false;
13966       }
13967     }
13968     Promote = true;
13969     break;
13970   }
13971   case ISD::SIGN_EXTEND:
13972   case ISD::ZERO_EXTEND:
13973   case ISD::ANY_EXTEND:
13974     Promote = true;
13975     break;
13976   case ISD::SHL:
13977   case ISD::SRL: {
13978     SDValue N0 = Op.getOperand(0);
13979     // Look out for (store (shl (load), x)).
13980     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13981       return false;
13982     Promote = true;
13983     break;
13984   }
13985   case ISD::ADD:
13986   case ISD::MUL:
13987   case ISD::AND:
13988   case ISD::OR:
13989   case ISD::XOR:
13990     Commute = true;
13991     // fallthrough
13992   case ISD::SUB: {
13993     SDValue N0 = Op.getOperand(0);
13994     SDValue N1 = Op.getOperand(1);
13995     if (!Commute && MayFoldLoad(N1))
13996       return false;
13997     // Avoid disabling potential load folding opportunities.
13998     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13999       return false;
14000     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14001       return false;
14002     Promote = true;
14003   }
14004   }
14005
14006   PVT = MVT::i32;
14007   return Promote;
14008 }
14009
14010 //===----------------------------------------------------------------------===//
14011 //                           X86 Inline Assembly Support
14012 //===----------------------------------------------------------------------===//
14013
14014 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14015   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14016
14017   std::string AsmStr = IA->getAsmString();
14018
14019   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14020   SmallVector<StringRef, 4> AsmPieces;
14021   SplitString(AsmStr, AsmPieces, ";\n");
14022
14023   switch (AsmPieces.size()) {
14024   default: return false;
14025   case 1:
14026     AsmStr = AsmPieces[0];
14027     AsmPieces.clear();
14028     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14029
14030     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14031     // we will turn this bswap into something that will be lowered to logical ops
14032     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14033     // so don't worry about this.
14034     // bswap $0
14035     if (AsmPieces.size() == 2 &&
14036         (AsmPieces[0] == "bswap" ||
14037          AsmPieces[0] == "bswapq" ||
14038          AsmPieces[0] == "bswapl") &&
14039         (AsmPieces[1] == "$0" ||
14040          AsmPieces[1] == "${0:q}")) {
14041       // No need to check constraints, nothing other than the equivalent of
14042       // "=r,0" would be valid here.
14043       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14044       if (!Ty || Ty->getBitWidth() % 16 != 0)
14045         return false;
14046       return IntrinsicLowering::LowerToByteSwap(CI);
14047     }
14048     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14049     if (CI->getType()->isIntegerTy(16) &&
14050         AsmPieces.size() == 3 &&
14051         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14052         AsmPieces[1] == "$$8," &&
14053         AsmPieces[2] == "${0:w}" &&
14054         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14055       AsmPieces.clear();
14056       const std::string &ConstraintsStr = IA->getConstraintString();
14057       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14058       std::sort(AsmPieces.begin(), AsmPieces.end());
14059       if (AsmPieces.size() == 4 &&
14060           AsmPieces[0] == "~{cc}" &&
14061           AsmPieces[1] == "~{dirflag}" &&
14062           AsmPieces[2] == "~{flags}" &&
14063           AsmPieces[3] == "~{fpsr}") {
14064         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14065         if (!Ty || Ty->getBitWidth() % 16 != 0)
14066           return false;
14067         return IntrinsicLowering::LowerToByteSwap(CI);
14068       }
14069     }
14070     break;
14071   case 3:
14072     if (CI->getType()->isIntegerTy(32) &&
14073         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14074       SmallVector<StringRef, 4> Words;
14075       SplitString(AsmPieces[0], Words, " \t,");
14076       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14077           Words[2] == "${0:w}") {
14078         Words.clear();
14079         SplitString(AsmPieces[1], Words, " \t,");
14080         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14081             Words[2] == "$0") {
14082           Words.clear();
14083           SplitString(AsmPieces[2], Words, " \t,");
14084           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14085               Words[2] == "${0:w}") {
14086             AsmPieces.clear();
14087             const std::string &ConstraintsStr = IA->getConstraintString();
14088             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14089             std::sort(AsmPieces.begin(), AsmPieces.end());
14090             if (AsmPieces.size() == 4 &&
14091                 AsmPieces[0] == "~{cc}" &&
14092                 AsmPieces[1] == "~{dirflag}" &&
14093                 AsmPieces[2] == "~{flags}" &&
14094                 AsmPieces[3] == "~{fpsr}") {
14095               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14096               if (!Ty || Ty->getBitWidth() % 16 != 0)
14097                 return false;
14098               return IntrinsicLowering::LowerToByteSwap(CI);
14099             }
14100           }
14101         }
14102       }
14103     }
14104
14105     if (CI->getType()->isIntegerTy(64)) {
14106       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14107       if (Constraints.size() >= 2 &&
14108           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14109           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14110         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14111         SmallVector<StringRef, 4> Words;
14112         SplitString(AsmPieces[0], Words, " \t");
14113         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14114           Words.clear();
14115           SplitString(AsmPieces[1], Words, " \t");
14116           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14117             Words.clear();
14118             SplitString(AsmPieces[2], Words, " \t,");
14119             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14120                 Words[2] == "%edx") {
14121               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14122               if (!Ty || Ty->getBitWidth() % 16 != 0)
14123                 return false;
14124               return IntrinsicLowering::LowerToByteSwap(CI);
14125             }
14126           }
14127         }
14128       }
14129     }
14130     break;
14131   }
14132   return false;
14133 }
14134
14135
14136
14137 /// getConstraintType - Given a constraint letter, return the type of
14138 /// constraint it is for this target.
14139 X86TargetLowering::ConstraintType
14140 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14141   if (Constraint.size() == 1) {
14142     switch (Constraint[0]) {
14143     case 'R':
14144     case 'q':
14145     case 'Q':
14146     case 'f':
14147     case 't':
14148     case 'u':
14149     case 'y':
14150     case 'x':
14151     case 'Y':
14152     case 'l':
14153       return C_RegisterClass;
14154     case 'a':
14155     case 'b':
14156     case 'c':
14157     case 'd':
14158     case 'S':
14159     case 'D':
14160     case 'A':
14161       return C_Register;
14162     case 'I':
14163     case 'J':
14164     case 'K':
14165     case 'L':
14166     case 'M':
14167     case 'N':
14168     case 'G':
14169     case 'C':
14170     case 'e':
14171     case 'Z':
14172       return C_Other;
14173     default:
14174       break;
14175     }
14176   }
14177   return TargetLowering::getConstraintType(Constraint);
14178 }
14179
14180 /// Examine constraint type and operand type and determine a weight value.
14181 /// This object must already have been set up with the operand type
14182 /// and the current alternative constraint selected.
14183 TargetLowering::ConstraintWeight
14184   X86TargetLowering::getSingleConstraintMatchWeight(
14185     AsmOperandInfo &info, const char *constraint) const {
14186   ConstraintWeight weight = CW_Invalid;
14187   Value *CallOperandVal = info.CallOperandVal;
14188     // If we don't have a value, we can't do a match,
14189     // but allow it at the lowest weight.
14190   if (CallOperandVal == NULL)
14191     return CW_Default;
14192   Type *type = CallOperandVal->getType();
14193   // Look at the constraint type.
14194   switch (*constraint) {
14195   default:
14196     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14197   case 'R':
14198   case 'q':
14199   case 'Q':
14200   case 'a':
14201   case 'b':
14202   case 'c':
14203   case 'd':
14204   case 'S':
14205   case 'D':
14206   case 'A':
14207     if (CallOperandVal->getType()->isIntegerTy())
14208       weight = CW_SpecificReg;
14209     break;
14210   case 'f':
14211   case 't':
14212   case 'u':
14213       if (type->isFloatingPointTy())
14214         weight = CW_SpecificReg;
14215       break;
14216   case 'y':
14217       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14218         weight = CW_SpecificReg;
14219       break;
14220   case 'x':
14221   case 'Y':
14222     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14223       weight = CW_Register;
14224     break;
14225   case 'I':
14226     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14227       if (C->getZExtValue() <= 31)
14228         weight = CW_Constant;
14229     }
14230     break;
14231   case 'J':
14232     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14233       if (C->getZExtValue() <= 63)
14234         weight = CW_Constant;
14235     }
14236     break;
14237   case 'K':
14238     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14239       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14240         weight = CW_Constant;
14241     }
14242     break;
14243   case 'L':
14244     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14245       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14246         weight = CW_Constant;
14247     }
14248     break;
14249   case 'M':
14250     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14251       if (C->getZExtValue() <= 3)
14252         weight = CW_Constant;
14253     }
14254     break;
14255   case 'N':
14256     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14257       if (C->getZExtValue() <= 0xff)
14258         weight = CW_Constant;
14259     }
14260     break;
14261   case 'G':
14262   case 'C':
14263     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14264       weight = CW_Constant;
14265     }
14266     break;
14267   case 'e':
14268     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14269       if ((C->getSExtValue() >= -0x80000000LL) &&
14270           (C->getSExtValue() <= 0x7fffffffLL))
14271         weight = CW_Constant;
14272     }
14273     break;
14274   case 'Z':
14275     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14276       if (C->getZExtValue() <= 0xffffffff)
14277         weight = CW_Constant;
14278     }
14279     break;
14280   }
14281   return weight;
14282 }
14283
14284 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14285 /// with another that has more specific requirements based on the type of the
14286 /// corresponding operand.
14287 const char *X86TargetLowering::
14288 LowerXConstraint(EVT ConstraintVT) const {
14289   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14290   // 'f' like normal targets.
14291   if (ConstraintVT.isFloatingPoint()) {
14292     if (Subtarget->hasXMMInt())
14293       return "Y";
14294     if (Subtarget->hasXMM())
14295       return "x";
14296   }
14297
14298   return TargetLowering::LowerXConstraint(ConstraintVT);
14299 }
14300
14301 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14302 /// vector.  If it is invalid, don't add anything to Ops.
14303 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14304                                                      std::string &Constraint,
14305                                                      std::vector<SDValue>&Ops,
14306                                                      SelectionDAG &DAG) const {
14307   SDValue Result(0, 0);
14308
14309   // Only support length 1 constraints for now.
14310   if (Constraint.length() > 1) return;
14311
14312   char ConstraintLetter = Constraint[0];
14313   switch (ConstraintLetter) {
14314   default: break;
14315   case 'I':
14316     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14317       if (C->getZExtValue() <= 31) {
14318         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14319         break;
14320       }
14321     }
14322     return;
14323   case 'J':
14324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14325       if (C->getZExtValue() <= 63) {
14326         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14327         break;
14328       }
14329     }
14330     return;
14331   case 'K':
14332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14333       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14334         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14335         break;
14336       }
14337     }
14338     return;
14339   case 'N':
14340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14341       if (C->getZExtValue() <= 255) {
14342         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14343         break;
14344       }
14345     }
14346     return;
14347   case 'e': {
14348     // 32-bit signed value
14349     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14350       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14351                                            C->getSExtValue())) {
14352         // Widen to 64 bits here to get it sign extended.
14353         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14354         break;
14355       }
14356     // FIXME gcc accepts some relocatable values here too, but only in certain
14357     // memory models; it's complicated.
14358     }
14359     return;
14360   }
14361   case 'Z': {
14362     // 32-bit unsigned value
14363     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14364       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14365                                            C->getZExtValue())) {
14366         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14367         break;
14368       }
14369     }
14370     // FIXME gcc accepts some relocatable values here too, but only in certain
14371     // memory models; it's complicated.
14372     return;
14373   }
14374   case 'i': {
14375     // Literal immediates are always ok.
14376     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14377       // Widen to 64 bits here to get it sign extended.
14378       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14379       break;
14380     }
14381
14382     // In any sort of PIC mode addresses need to be computed at runtime by
14383     // adding in a register or some sort of table lookup.  These can't
14384     // be used as immediates.
14385     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14386       return;
14387
14388     // If we are in non-pic codegen mode, we allow the address of a global (with
14389     // an optional displacement) to be used with 'i'.
14390     GlobalAddressSDNode *GA = 0;
14391     int64_t Offset = 0;
14392
14393     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14394     while (1) {
14395       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14396         Offset += GA->getOffset();
14397         break;
14398       } else if (Op.getOpcode() == ISD::ADD) {
14399         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14400           Offset += C->getZExtValue();
14401           Op = Op.getOperand(0);
14402           continue;
14403         }
14404       } else if (Op.getOpcode() == ISD::SUB) {
14405         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14406           Offset += -C->getZExtValue();
14407           Op = Op.getOperand(0);
14408           continue;
14409         }
14410       }
14411
14412       // Otherwise, this isn't something we can handle, reject it.
14413       return;
14414     }
14415
14416     const GlobalValue *GV = GA->getGlobal();
14417     // If we require an extra load to get this address, as in PIC mode, we
14418     // can't accept it.
14419     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14420                                                         getTargetMachine())))
14421       return;
14422
14423     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14424                                         GA->getValueType(0), Offset);
14425     break;
14426   }
14427   }
14428
14429   if (Result.getNode()) {
14430     Ops.push_back(Result);
14431     return;
14432   }
14433   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14434 }
14435
14436 std::pair<unsigned, const TargetRegisterClass*>
14437 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14438                                                 EVT VT) const {
14439   // First, see if this is a constraint that directly corresponds to an LLVM
14440   // register class.
14441   if (Constraint.size() == 1) {
14442     // GCC Constraint Letters
14443     switch (Constraint[0]) {
14444     default: break;
14445       // TODO: Slight differences here in allocation order and leaving
14446       // RIP in the class. Do they matter any more here than they do
14447       // in the normal allocation?
14448     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14449       if (Subtarget->is64Bit()) {
14450         if (VT == MVT::i32 || VT == MVT::f32)
14451           return std::make_pair(0U, X86::GR32RegisterClass);
14452         else if (VT == MVT::i16)
14453           return std::make_pair(0U, X86::GR16RegisterClass);
14454         else if (VT == MVT::i8 || VT == MVT::i1)
14455           return std::make_pair(0U, X86::GR8RegisterClass);
14456         else if (VT == MVT::i64 || VT == MVT::f64)
14457           return std::make_pair(0U, X86::GR64RegisterClass);
14458         break;
14459       }
14460       // 32-bit fallthrough
14461     case 'Q':   // Q_REGS
14462       if (VT == MVT::i32 || VT == MVT::f32)
14463         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14464       else if (VT == MVT::i16)
14465         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14466       else if (VT == MVT::i8 || VT == MVT::i1)
14467         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14468       else if (VT == MVT::i64)
14469         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14470       break;
14471     case 'r':   // GENERAL_REGS
14472     case 'l':   // INDEX_REGS
14473       if (VT == MVT::i8 || VT == MVT::i1)
14474         return std::make_pair(0U, X86::GR8RegisterClass);
14475       if (VT == MVT::i16)
14476         return std::make_pair(0U, X86::GR16RegisterClass);
14477       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14478         return std::make_pair(0U, X86::GR32RegisterClass);
14479       return std::make_pair(0U, X86::GR64RegisterClass);
14480     case 'R':   // LEGACY_REGS
14481       if (VT == MVT::i8 || VT == MVT::i1)
14482         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14483       if (VT == MVT::i16)
14484         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14485       if (VT == MVT::i32 || !Subtarget->is64Bit())
14486         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14487       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14488     case 'f':  // FP Stack registers.
14489       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14490       // value to the correct fpstack register class.
14491       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14492         return std::make_pair(0U, X86::RFP32RegisterClass);
14493       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14494         return std::make_pair(0U, X86::RFP64RegisterClass);
14495       return std::make_pair(0U, X86::RFP80RegisterClass);
14496     case 'y':   // MMX_REGS if MMX allowed.
14497       if (!Subtarget->hasMMX()) break;
14498       return std::make_pair(0U, X86::VR64RegisterClass);
14499     case 'Y':   // SSE_REGS if SSE2 allowed
14500       if (!Subtarget->hasXMMInt()) break;
14501       // FALL THROUGH.
14502     case 'x':   // SSE_REGS if SSE1 allowed
14503       if (!Subtarget->hasXMM()) break;
14504
14505       switch (VT.getSimpleVT().SimpleTy) {
14506       default: break;
14507       // Scalar SSE types.
14508       case MVT::f32:
14509       case MVT::i32:
14510         return std::make_pair(0U, X86::FR32RegisterClass);
14511       case MVT::f64:
14512       case MVT::i64:
14513         return std::make_pair(0U, X86::FR64RegisterClass);
14514       // Vector types.
14515       case MVT::v16i8:
14516       case MVT::v8i16:
14517       case MVT::v4i32:
14518       case MVT::v2i64:
14519       case MVT::v4f32:
14520       case MVT::v2f64:
14521         return std::make_pair(0U, X86::VR128RegisterClass);
14522       }
14523       break;
14524     }
14525   }
14526
14527   // Use the default implementation in TargetLowering to convert the register
14528   // constraint into a member of a register class.
14529   std::pair<unsigned, const TargetRegisterClass*> Res;
14530   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14531
14532   // Not found as a standard register?
14533   if (Res.second == 0) {
14534     // Map st(0) -> st(7) -> ST0
14535     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14536         tolower(Constraint[1]) == 's' &&
14537         tolower(Constraint[2]) == 't' &&
14538         Constraint[3] == '(' &&
14539         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14540         Constraint[5] == ')' &&
14541         Constraint[6] == '}') {
14542
14543       Res.first = X86::ST0+Constraint[4]-'0';
14544       Res.second = X86::RFP80RegisterClass;
14545       return Res;
14546     }
14547
14548     // GCC allows "st(0)" to be called just plain "st".
14549     if (StringRef("{st}").equals_lower(Constraint)) {
14550       Res.first = X86::ST0;
14551       Res.second = X86::RFP80RegisterClass;
14552       return Res;
14553     }
14554
14555     // flags -> EFLAGS
14556     if (StringRef("{flags}").equals_lower(Constraint)) {
14557       Res.first = X86::EFLAGS;
14558       Res.second = X86::CCRRegisterClass;
14559       return Res;
14560     }
14561
14562     // 'A' means EAX + EDX.
14563     if (Constraint == "A") {
14564       Res.first = X86::EAX;
14565       Res.second = X86::GR32_ADRegisterClass;
14566       return Res;
14567     }
14568     return Res;
14569   }
14570
14571   // Otherwise, check to see if this is a register class of the wrong value
14572   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14573   // turn into {ax},{dx}.
14574   if (Res.second->hasType(VT))
14575     return Res;   // Correct type already, nothing to do.
14576
14577   // All of the single-register GCC register classes map their values onto
14578   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14579   // really want an 8-bit or 32-bit register, map to the appropriate register
14580   // class and return the appropriate register.
14581   if (Res.second == X86::GR16RegisterClass) {
14582     if (VT == MVT::i8) {
14583       unsigned DestReg = 0;
14584       switch (Res.first) {
14585       default: break;
14586       case X86::AX: DestReg = X86::AL; break;
14587       case X86::DX: DestReg = X86::DL; break;
14588       case X86::CX: DestReg = X86::CL; break;
14589       case X86::BX: DestReg = X86::BL; break;
14590       }
14591       if (DestReg) {
14592         Res.first = DestReg;
14593         Res.second = X86::GR8RegisterClass;
14594       }
14595     } else if (VT == MVT::i32) {
14596       unsigned DestReg = 0;
14597       switch (Res.first) {
14598       default: break;
14599       case X86::AX: DestReg = X86::EAX; break;
14600       case X86::DX: DestReg = X86::EDX; break;
14601       case X86::CX: DestReg = X86::ECX; break;
14602       case X86::BX: DestReg = X86::EBX; break;
14603       case X86::SI: DestReg = X86::ESI; break;
14604       case X86::DI: DestReg = X86::EDI; break;
14605       case X86::BP: DestReg = X86::EBP; break;
14606       case X86::SP: DestReg = X86::ESP; break;
14607       }
14608       if (DestReg) {
14609         Res.first = DestReg;
14610         Res.second = X86::GR32RegisterClass;
14611       }
14612     } else if (VT == MVT::i64) {
14613       unsigned DestReg = 0;
14614       switch (Res.first) {
14615       default: break;
14616       case X86::AX: DestReg = X86::RAX; break;
14617       case X86::DX: DestReg = X86::RDX; break;
14618       case X86::CX: DestReg = X86::RCX; break;
14619       case X86::BX: DestReg = X86::RBX; break;
14620       case X86::SI: DestReg = X86::RSI; break;
14621       case X86::DI: DestReg = X86::RDI; break;
14622       case X86::BP: DestReg = X86::RBP; break;
14623       case X86::SP: DestReg = X86::RSP; break;
14624       }
14625       if (DestReg) {
14626         Res.first = DestReg;
14627         Res.second = X86::GR64RegisterClass;
14628       }
14629     }
14630   } else if (Res.second == X86::FR32RegisterClass ||
14631              Res.second == X86::FR64RegisterClass ||
14632              Res.second == X86::VR128RegisterClass) {
14633     // Handle references to XMM physical registers that got mapped into the
14634     // wrong class.  This can happen with constraints like {xmm0} where the
14635     // target independent register mapper will just pick the first match it can
14636     // find, ignoring the required type.
14637     if (VT == MVT::f32)
14638       Res.second = X86::FR32RegisterClass;
14639     else if (VT == MVT::f64)
14640       Res.second = X86::FR64RegisterClass;
14641     else if (X86::VR128RegisterClass->hasType(VT))
14642       Res.second = X86::VR128RegisterClass;
14643   }
14644
14645   return Res;
14646 }