Revert r137114
[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 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference.  Idx is an index in the 128 bits we
77 /// want.  It need not be aligned to a 128-bit bounday.  That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
80                                    SDValue Idx,
81                                    SelectionDAG &DAG,
82                                    DebugLoc dl) {
83   EVT VT = Vec.getValueType();
84   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85   EVT ElVT = VT.getVectorElementType();
86   int Factor = VT.getSizeInBits()/128;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94   if (isa<ConstantSDNode>(Idx)) {
95     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98     // we can match to VEXTRACTF128.
99     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101     // This is the index of the first element of the 128-bit chunk
102     // we want.
103     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                  * ElemsPerChunk);
105
106     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                  VecIdx);
109
110     return Result;
111   }
112
113   return SDValue();
114 }
115
116 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference.  Idx is an index in the 128 bits
119 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
122                                   SDValue Vec,
123                                   SDValue Idx,
124                                   SelectionDAG &DAG,
125                                   DebugLoc dl) {
126   if (isa<ConstantSDNode>(Idx)) {
127     EVT VT = Vec.getValueType();
128     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130     EVT ElVT = VT.getVectorElementType();
131     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132     EVT ResultVT = Result.getValueType();
133
134     // Insert the relevant 128 bits.
135     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137     // This is the index of the first element of the 128-bit chunk
138     // we want.
139     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                  * ElemsPerChunk);
141
142     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                          VecIdx);
145     return Result;
146   }
147
148   return SDValue();
149 }
150
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153   bool is64Bit = Subtarget->is64Bit();
154
155   if (Subtarget->isTargetEnvMacho()) {
156     if (is64Bit)
157       return new X8664_MachoTargetObjectFile();
158     return new TargetLoweringObjectFileMachO();
159   }
160
161   if (Subtarget->isTargetELF())
162     return new TargetLoweringObjectFileELF();
163   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164     return new TargetLoweringObjectFileCOFF();
165   llvm_unreachable("unknown subtarget type");
166 }
167
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169   : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<X86Subtarget>();
171   X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
172   X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
173   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175   RegInfo = TM.getRegisterInfo();
176   TD = getTargetData();
177
178   // Set up the TargetLowering object.
179   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181   // X86 is weird, it always uses i8 for shift amounts and setcc results.
182   setBooleanContents(ZeroOrOneBooleanContent);
183
184   // For 64-bit since we have so many registers use the ILP scheduler, for
185   // 32-bit code use the register pressure specific scheduling.
186   if (Subtarget->is64Bit())
187     setSchedulingPreference(Sched::ILP);
188   else
189     setSchedulingPreference(Sched::RegPressure);
190   setStackPointerRegisterToSaveRestore(X86StackPtr);
191
192   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
193     // Setup Windows compiler runtime calls.
194     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
195     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
196     setLibcallName(RTLIB::SREM_I64, "_allrem");
197     setLibcallName(RTLIB::UREM_I64, "_aullrem");
198     setLibcallName(RTLIB::MUL_I64, "_allmul");
199     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
200     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
201     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
202     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
203     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
207     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
225   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
226   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
257   } else if (!UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!UseSoftFloat) {
315     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
316       // Expand FP_TO_UINT into a select.
317       // FIXME: We would like to use a Custom expander here eventually to do
318       // the optimal thing for SSE vs. the default expansion in the legalizer.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320     else
321       // With SSE3 we can use fisttpll to convert to a signed i64; without
322       // SSE, we're stuck with a fistpll.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324   }
325
326   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
327   if (!X86ScalarSSEf64) {
328     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
329     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
330     if (Subtarget->is64Bit()) {
331       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
332       // Without SSE, i64->f64 goes through memory.
333       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
334     }
335   }
336
337   // Scalar integer divide and remainder are lowered to use operations that
338   // produce two results, to match the available instructions. This exposes
339   // the two-result form to trivial CSE, which is able to combine x/y and x%y
340   // into a single instruction.
341   //
342   // Scalar integer multiply-high is also lowered to use two-result
343   // operations, to match the available instructions. However, plain multiply
344   // (low) operations are left as Legal, as there are single-result
345   // instructions for this in x86. Using the two-result multiply instructions
346   // when both high and low results are needed must be arranged by dagcombine.
347   for (unsigned i = 0, e = 4; i != e; ++i) {
348     MVT VT = IntVTs[i];
349     setOperationAction(ISD::MULHS, VT, Expand);
350     setOperationAction(ISD::MULHU, VT, Expand);
351     setOperationAction(ISD::SDIV, VT, Expand);
352     setOperationAction(ISD::UDIV, VT, Expand);
353     setOperationAction(ISD::SREM, VT, Expand);
354     setOperationAction(ISD::UREM, VT, Expand);
355
356     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
357     setOperationAction(ISD::ADDC, VT, Custom);
358     setOperationAction(ISD::ADDE, VT, Custom);
359     setOperationAction(ISD::SUBC, VT, Custom);
360     setOperationAction(ISD::SUBE, VT, Custom);
361   }
362
363   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
364   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
365   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
366   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
367   if (Subtarget->is64Bit())
368     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
369   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
370   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
371   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
372   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
373   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
374   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
375   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
376   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
377
378   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
379   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
380   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
381   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
382   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
383   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
384   if (Subtarget->is64Bit()) {
385     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
386     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
387   }
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
401
402   // These should be promoted to a larger select which is supported.
403   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
404   // X86 wants to expand cmov itself.
405   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
406   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
417   if (Subtarget->is64Bit()) {
418     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
419     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
420   }
421   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
422
423   // Darwin ABI issue.
424   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
425   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
426   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
427   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
428   if (Subtarget->is64Bit())
429     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
431   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
434     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
435     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
436     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
437     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
438   }
439   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
441   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
442   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
443   if (Subtarget->is64Bit()) {
444     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
445     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
446     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
447   }
448
449   if (Subtarget->hasXMM())
450     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
451
452   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
453   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
454
455   // On X86 and X86-64, atomic operations are lowered to locked instructions.
456   // Locked instructions, in turn, have implicit fence semantics (all memory
457   // operations are flushed before issuing the locked instruction, and they
458   // are not buffered), so we can fold away the common pattern of
459   // fence-atomic-fence.
460   setShouldFoldAtomicFences(true);
461
462   // Expand certain atomics
463   for (unsigned i = 0, e = 4; i != e; ++i) {
464     MVT VT = IntVTs[i];
465     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
466     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467   }
468
469   if (!Subtarget->is64Bit()) {
470     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
471     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
472     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
473     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
474     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
475     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
476     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
477   }
478
479   // FIXME - use subtarget debug flags
480   if (!Subtarget->isTargetDarwin() &&
481       !Subtarget->isTargetELF() &&
482       !Subtarget->isTargetCygMing()) {
483     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
484   }
485
486   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
487   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
488   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
489   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
490   if (Subtarget->is64Bit()) {
491     setExceptionPointerRegister(X86::RAX);
492     setExceptionSelectorRegister(X86::RDX);
493   } else {
494     setExceptionPointerRegister(X86::EAX);
495     setExceptionSelectorRegister(X86::EDX);
496   }
497   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
498   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
499
500   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
501
502   setOperationAction(ISD::TRAP, MVT::Other, Legal);
503
504   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
506   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
507   if (Subtarget->is64Bit()) {
508     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
509     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
510   } else {
511     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
512     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
513   }
514
515   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
516   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
517   setOperationAction(ISD::DYNAMIC_STACKALLOC,
518                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
519                      (Subtarget->isTargetCOFF()
520                       && !Subtarget->isTargetEnvMacho()
521                       ? Custom : Expand));
522
523   if (!UseSoftFloat && X86ScalarSSEf64) {
524     // f32 and f64 use SSE.
525     // Set up the FP register classes.
526     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
527     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
528
529     // Use ANDPD to simulate FABS.
530     setOperationAction(ISD::FABS , MVT::f64, Custom);
531     setOperationAction(ISD::FABS , MVT::f32, Custom);
532
533     // Use XORP to simulate FNEG.
534     setOperationAction(ISD::FNEG , MVT::f64, Custom);
535     setOperationAction(ISD::FNEG , MVT::f32, Custom);
536
537     // Use ANDPD and ORPD to simulate FCOPYSIGN.
538     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
539     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
540
541     // Lower this to FGETSIGNx86 plus an AND.
542     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
543     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
544
545     // We don't support sin/cos/fmod
546     setOperationAction(ISD::FSIN , MVT::f64, Expand);
547     setOperationAction(ISD::FCOS , MVT::f64, Expand);
548     setOperationAction(ISD::FSIN , MVT::f32, Expand);
549     setOperationAction(ISD::FCOS , MVT::f32, Expand);
550
551     // Expand FP immediates into loads from the stack, except for the special
552     // cases we handle.
553     addLegalFPImmediate(APFloat(+0.0)); // xorpd
554     addLegalFPImmediate(APFloat(+0.0f)); // xorps
555   } else if (!UseSoftFloat && X86ScalarSSEf32) {
556     // Use SSE for f32, x87 for f64.
557     // Set up the FP register classes.
558     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
559     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
560
561     // Use ANDPS to simulate FABS.
562     setOperationAction(ISD::FABS , MVT::f32, Custom);
563
564     // Use XORP to simulate FNEG.
565     setOperationAction(ISD::FNEG , MVT::f32, Custom);
566
567     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
568
569     // Use ANDPS and ORPS to simulate FCOPYSIGN.
570     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
571     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572
573     // We don't support sin/cos/fmod
574     setOperationAction(ISD::FSIN , MVT::f32, Expand);
575     setOperationAction(ISD::FCOS , MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!UnsafeFPMath) {
585       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
586       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
587     }
588   } else if (!UseSoftFloat) {
589     // f32 and f64 in x87.
590     // Set up the FP register classes.
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
593
594     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
595     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
598
599     if (!UnsafeFPMath) {
600       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
601       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
602     }
603     addLegalFPImmediate(APFloat(+0.0)); // FLD0
604     addLegalFPImmediate(APFloat(+1.0)); // FLD1
605     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
611   }
612
613   // We don't support FMA.
614   setOperationAction(ISD::FMA, MVT::f64, Expand);
615   setOperationAction(ISD::FMA, MVT::f32, Expand);
616
617   // Long double always uses X87.
618   if (!UseSoftFloat) {
619     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
620     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
622     {
623       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
624       addLegalFPImmediate(TmpFlt);  // FLD0
625       TmpFlt.changeSign();
626       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
627
628       bool ignored;
629       APFloat TmpFlt2(+1.0);
630       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
631                       &ignored);
632       addLegalFPImmediate(TmpFlt2);  // FLD1
633       TmpFlt2.changeSign();
634       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
635     }
636
637     if (!UnsafeFPMath) {
638       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
639       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
640     }
641
642     setOperationAction(ISD::FMA, MVT::f80, Expand);
643   }
644
645   // Always use a library call for pow.
646   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
647   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
648   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
649
650   setOperationAction(ISD::FLOG, MVT::f80, Expand);
651   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
652   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
653   setOperationAction(ISD::FEXP, MVT::f80, Expand);
654   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
655
656   // First set operation action for all vector types to either promote
657   // (for widening) or expand (for scalarization). Then we will selectively
658   // turn on ones that can be effectively codegen'd.
659   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
660        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
661     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
662     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
663     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
664     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
665     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
666     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
667     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
668     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
669     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
670     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
671     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
672     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
673     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
674     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
675     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
676     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
677     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
678     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
679     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
680     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
681     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
711     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
715     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
716          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
717       setTruncStoreAction((MVT::SimpleValueType)VT,
718                           (MVT::SimpleValueType)InnerVT, Expand);
719     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
720     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
721     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
722   }
723
724   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
725   // with -msoft-float, disable use of MMX as well.
726   if (!UseSoftFloat && Subtarget->hasMMX()) {
727     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
728     // No operations on x86mmx supported, everything uses intrinsics.
729   }
730
731   // MMX-sized vectors (other than x86mmx) are expected to be expanded
732   // into smaller operations.
733   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
734   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
735   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
736   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
737   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
738   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
739   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
740   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
741   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
742   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
743   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
744   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
745   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
746   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
747   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
748   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
749   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
750   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
751   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
752   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
753   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
754   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
755   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
756   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
757   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
758   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
759   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
760   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
761   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
762
763   if (!UseSoftFloat && Subtarget->hasXMM()) {
764     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
765
766     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
767     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
768     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
769     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
770     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
771     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
772     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
773     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
774     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
775     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
776     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
777     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
778   }
779
780   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
781     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
782
783     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
784     // registers cannot be used even for integer operations.
785     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
786     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
787     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
788     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
789
790     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
791     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
792     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
793     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
794     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
795     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
796     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
797     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
798     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
799     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
800     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
801     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
802     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
803     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
804     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
805     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
806
807     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
808     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
809     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
810     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
811
812     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
813     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
814     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
815     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
816     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
817
818     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
819     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
820     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
821     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
822     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
823
824     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
825     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
826       EVT VT = (MVT::SimpleValueType)i;
827       // Do not attempt to custom lower non-power-of-2 vectors
828       if (!isPowerOf2_32(VT.getVectorNumElements()))
829         continue;
830       // Do not attempt to custom lower non-128-bit vectors
831       if (!VT.is128BitVector())
832         continue;
833       setOperationAction(ISD::BUILD_VECTOR,
834                          VT.getSimpleVT().SimpleTy, Custom);
835       setOperationAction(ISD::VECTOR_SHUFFLE,
836                          VT.getSimpleVT().SimpleTy, Custom);
837       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
838                          VT.getSimpleVT().SimpleTy, Custom);
839     }
840
841     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
842     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
843     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
844     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
846     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
847
848     if (Subtarget->is64Bit()) {
849       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
850       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
851     }
852
853     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
854     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
855       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
856       EVT VT = SVT;
857
858       // Do not attempt to promote non-128-bit vectors
859       if (!VT.is128BitVector())
860         continue;
861
862       setOperationAction(ISD::AND,    SVT, Promote);
863       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
864       setOperationAction(ISD::OR,     SVT, Promote);
865       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
866       setOperationAction(ISD::XOR,    SVT, Promote);
867       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
868       setOperationAction(ISD::LOAD,   SVT, Promote);
869       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
870       setOperationAction(ISD::SELECT, SVT, Promote);
871       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
872     }
873
874     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
875
876     // Custom lower v2i64 and v2f64 selects.
877     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
878     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
879     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
880     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
881
882     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
883     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
884   }
885
886   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
887     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
888     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
889     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
890     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
891     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
892     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
893     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
894     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
895     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
896     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
897
898     // FIXME: Do we need to handle scalar-to-vector here?
899     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
900
901     // Can turn SHL into an integer multiply.
902     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
903     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
904
905     // i8 and i16 vectors are custom , because the source register and source
906     // source memory operand types are not the same width.  f32 vectors are
907     // custom since the immediate controlling the insert encodes additional
908     // information.
909     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
910     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
913
914     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
915     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
916     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
917     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
918
919     if (Subtarget->is64Bit()) {
920       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
921       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
922     }
923   }
924
925   if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
926     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
927     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
928     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
929     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
930
931     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
932     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
933     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
934
935     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
936     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
937   }
938
939   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
940     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
941
942   if (!UseSoftFloat && Subtarget->hasAVX()) {
943     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
944     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
945     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
946     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
947     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
948     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
949
950     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
951     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
952     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
953
954     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
955     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
956     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
957     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
958     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
959     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
960
961     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
962     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
963     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
964     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
965     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
966     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
967
968     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
969     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
970     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
971
972     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
973     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
974     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
975     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
976     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
977     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
978
979     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
980     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
981     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
982     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
983
984     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
985     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
986     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
987     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
988
989     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
990     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
991
992     setOperationAction(ISD::VSETCC,            MVT::v8i32, Custom);
993     setOperationAction(ISD::VSETCC,            MVT::v4i64, Custom);
994
995     // Custom lower several nodes for 256-bit types.
996     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
997                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
998       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
999       EVT VT = SVT;
1000
1001       // Extract subvector is special because the value type
1002       // (result) is 128-bit but the source is 256-bit wide.
1003       if (VT.is128BitVector())
1004         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1005
1006       // Do not attempt to custom lower other non-256-bit vectors
1007       if (!VT.is256BitVector())
1008         continue;
1009
1010       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1011       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1012       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1013       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1014       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1015       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1016     }
1017
1018     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1019     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1020       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1021       EVT VT = SVT;
1022
1023       // Do not attempt to promote non-256-bit vectors
1024       if (!VT.is256BitVector())
1025         continue;
1026
1027       setOperationAction(ISD::AND,    SVT, Promote);
1028       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1029       setOperationAction(ISD::OR,     SVT, Promote);
1030       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1031       setOperationAction(ISD::XOR,    SVT, Promote);
1032       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1033       setOperationAction(ISD::LOAD,   SVT, Promote);
1034       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1035       setOperationAction(ISD::SELECT, SVT, Promote);
1036       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1037     }
1038   }
1039
1040   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1041   // of this type with custom code.
1042   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1043          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1044     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1045   }
1046
1047   // We want to custom lower some of our intrinsics.
1048   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1049
1050
1051   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1052   // handle type legalization for these operations here.
1053   //
1054   // FIXME: We really should do custom legalization for addition and
1055   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1056   // than generic legalization for 64-bit multiplication-with-overflow, though.
1057   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1058     // Add/Sub/Mul with overflow operations are custom lowered.
1059     MVT VT = IntVTs[i];
1060     setOperationAction(ISD::SADDO, VT, Custom);
1061     setOperationAction(ISD::UADDO, VT, Custom);
1062     setOperationAction(ISD::SSUBO, VT, Custom);
1063     setOperationAction(ISD::USUBO, VT, Custom);
1064     setOperationAction(ISD::SMULO, VT, Custom);
1065     setOperationAction(ISD::UMULO, VT, Custom);
1066   }
1067
1068   // There are no 8-bit 3-address imul/mul instructions
1069   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1070   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1071
1072   if (!Subtarget->is64Bit()) {
1073     // These libcalls are not available in 32-bit.
1074     setLibcallName(RTLIB::SHL_I128, 0);
1075     setLibcallName(RTLIB::SRL_I128, 0);
1076     setLibcallName(RTLIB::SRA_I128, 0);
1077   }
1078
1079   // We have target-specific dag combine patterns for the following nodes:
1080   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1081   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1082   setTargetDAGCombine(ISD::BUILD_VECTOR);
1083   setTargetDAGCombine(ISD::SELECT);
1084   setTargetDAGCombine(ISD::SHL);
1085   setTargetDAGCombine(ISD::SRA);
1086   setTargetDAGCombine(ISD::SRL);
1087   setTargetDAGCombine(ISD::OR);
1088   setTargetDAGCombine(ISD::AND);
1089   setTargetDAGCombine(ISD::ADD);
1090   setTargetDAGCombine(ISD::SUB);
1091   setTargetDAGCombine(ISD::STORE);
1092   setTargetDAGCombine(ISD::ZERO_EXTEND);
1093   setTargetDAGCombine(ISD::SINT_TO_FP);
1094   if (Subtarget->is64Bit())
1095     setTargetDAGCombine(ISD::MUL);
1096
1097   computeRegisterProperties();
1098
1099   // On Darwin, -Os means optimize for size without hurting performance,
1100   // do not reduce the limit.
1101   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1102   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1103   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1104   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1105   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1106   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107   setPrefLoopAlignment(16);
1108   benefitFromCodePlacementOpt = true;
1109
1110   setPrefFunctionAlignment(4);
1111 }
1112
1113
1114 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1115   return MVT::i8;
1116 }
1117
1118
1119 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1120 /// the desired ByVal argument alignment.
1121 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1122   if (MaxAlign == 16)
1123     return;
1124   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1125     if (VTy->getBitWidth() == 128)
1126       MaxAlign = 16;
1127   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1128     unsigned EltAlign = 0;
1129     getMaxByValAlign(ATy->getElementType(), EltAlign);
1130     if (EltAlign > MaxAlign)
1131       MaxAlign = EltAlign;
1132   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1133     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1134       unsigned EltAlign = 0;
1135       getMaxByValAlign(STy->getElementType(i), EltAlign);
1136       if (EltAlign > MaxAlign)
1137         MaxAlign = EltAlign;
1138       if (MaxAlign == 16)
1139         break;
1140     }
1141   }
1142   return;
1143 }
1144
1145 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1146 /// function arguments in the caller parameter area. For X86, aggregates
1147 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1148 /// are at 4-byte boundaries.
1149 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1150   if (Subtarget->is64Bit()) {
1151     // Max of 8 and alignment of type.
1152     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1153     if (TyAlign > 8)
1154       return TyAlign;
1155     return 8;
1156   }
1157
1158   unsigned Align = 4;
1159   if (Subtarget->hasXMM())
1160     getMaxByValAlign(Ty, Align);
1161   return Align;
1162 }
1163
1164 /// getOptimalMemOpType - Returns the target specific optimal type for load
1165 /// and store operations as a result of memset, memcpy, and memmove
1166 /// lowering. If DstAlign is zero that means it's safe to destination
1167 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1168 /// means there isn't a need to check it against alignment requirement,
1169 /// probably because the source does not need to be loaded. If
1170 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1171 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1172 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1173 /// constant so it does not need to be loaded.
1174 /// It returns EVT::Other if the type should be determined using generic
1175 /// target-independent logic.
1176 EVT
1177 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1178                                        unsigned DstAlign, unsigned SrcAlign,
1179                                        bool NonScalarIntSafe,
1180                                        bool MemcpyStrSrc,
1181                                        MachineFunction &MF) const {
1182   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1183   // linux.  This is because the stack realignment code can't handle certain
1184   // cases like PR2962.  This should be removed when PR2962 is fixed.
1185   const Function *F = MF.getFunction();
1186   if (NonScalarIntSafe &&
1187       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1188     if (Size >= 16 &&
1189         (Subtarget->isUnalignedMemAccessFast() ||
1190          ((DstAlign == 0 || DstAlign >= 16) &&
1191           (SrcAlign == 0 || SrcAlign >= 16))) &&
1192         Subtarget->getStackAlignment() >= 16) {
1193       if (Subtarget->hasSSE2())
1194         return MVT::v4i32;
1195       if (Subtarget->hasSSE1())
1196         return MVT::v4f32;
1197     } else if (!MemcpyStrSrc && Size >= 8 &&
1198                !Subtarget->is64Bit() &&
1199                Subtarget->getStackAlignment() >= 8 &&
1200                Subtarget->hasXMMInt()) {
1201       // Do not use f64 to lower memcpy if source is string constant. It's
1202       // better to use i32 to avoid the loads.
1203       return MVT::f64;
1204     }
1205   }
1206   if (Subtarget->is64Bit() && Size >= 8)
1207     return MVT::i64;
1208   return MVT::i32;
1209 }
1210
1211 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1212 /// current function.  The returned value is a member of the
1213 /// MachineJumpTableInfo::JTEntryKind enum.
1214 unsigned X86TargetLowering::getJumpTableEncoding() const {
1215   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1216   // symbol.
1217   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1218       Subtarget->isPICStyleGOT())
1219     return MachineJumpTableInfo::EK_Custom32;
1220
1221   // Otherwise, use the normal jump table encoding heuristics.
1222   return TargetLowering::getJumpTableEncoding();
1223 }
1224
1225 const MCExpr *
1226 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1227                                              const MachineBasicBlock *MBB,
1228                                              unsigned uid,MCContext &Ctx) const{
1229   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1230          Subtarget->isPICStyleGOT());
1231   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1232   // entries.
1233   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1234                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1235 }
1236
1237 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1238 /// jumptable.
1239 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1240                                                     SelectionDAG &DAG) const {
1241   if (!Subtarget->is64Bit())
1242     // This doesn't have DebugLoc associated with it, but is not really the
1243     // same as a Register.
1244     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1245   return Table;
1246 }
1247
1248 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1249 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1250 /// MCExpr.
1251 const MCExpr *X86TargetLowering::
1252 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1253                              MCContext &Ctx) const {
1254   // X86-64 uses RIP relative addressing based on the jump table label.
1255   if (Subtarget->isPICStyleRIPRel())
1256     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1257
1258   // Otherwise, the reference is relative to the PIC base.
1259   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1260 }
1261
1262 // FIXME: Why this routine is here? Move to RegInfo!
1263 std::pair<const TargetRegisterClass*, uint8_t>
1264 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1265   const TargetRegisterClass *RRC = 0;
1266   uint8_t Cost = 1;
1267   switch (VT.getSimpleVT().SimpleTy) {
1268   default:
1269     return TargetLowering::findRepresentativeClass(VT);
1270   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1271     RRC = (Subtarget->is64Bit()
1272            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1273     break;
1274   case MVT::x86mmx:
1275     RRC = X86::VR64RegisterClass;
1276     break;
1277   case MVT::f32: case MVT::f64:
1278   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1279   case MVT::v4f32: case MVT::v2f64:
1280   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1281   case MVT::v4f64:
1282     RRC = X86::VR128RegisterClass;
1283     break;
1284   }
1285   return std::make_pair(RRC, Cost);
1286 }
1287
1288 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1289                                                unsigned &Offset) const {
1290   if (!Subtarget->isTargetLinux())
1291     return false;
1292
1293   if (Subtarget->is64Bit()) {
1294     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1295     Offset = 0x28;
1296     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1297       AddressSpace = 256;
1298     else
1299       AddressSpace = 257;
1300   } else {
1301     // %gs:0x14 on i386
1302     Offset = 0x14;
1303     AddressSpace = 256;
1304   }
1305   return true;
1306 }
1307
1308
1309 //===----------------------------------------------------------------------===//
1310 //               Return Value Calling Convention Implementation
1311 //===----------------------------------------------------------------------===//
1312
1313 #include "X86GenCallingConv.inc"
1314
1315 bool
1316 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1317                                   MachineFunction &MF, bool isVarArg,
1318                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1319                         LLVMContext &Context) const {
1320   SmallVector<CCValAssign, 16> RVLocs;
1321   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1322                  RVLocs, Context);
1323   return CCInfo.CheckReturn(Outs, RetCC_X86);
1324 }
1325
1326 SDValue
1327 X86TargetLowering::LowerReturn(SDValue Chain,
1328                                CallingConv::ID CallConv, bool isVarArg,
1329                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1330                                const SmallVectorImpl<SDValue> &OutVals,
1331                                DebugLoc dl, SelectionDAG &DAG) const {
1332   MachineFunction &MF = DAG.getMachineFunction();
1333   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1334
1335   SmallVector<CCValAssign, 16> RVLocs;
1336   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1337                  RVLocs, *DAG.getContext());
1338   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1339
1340   // Add the regs to the liveout set for the function.
1341   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1342   for (unsigned i = 0; i != RVLocs.size(); ++i)
1343     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1344       MRI.addLiveOut(RVLocs[i].getLocReg());
1345
1346   SDValue Flag;
1347
1348   SmallVector<SDValue, 6> RetOps;
1349   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1350   // Operand #1 = Bytes To Pop
1351   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1352                    MVT::i16));
1353
1354   // Copy the result values into the output registers.
1355   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356     CCValAssign &VA = RVLocs[i];
1357     assert(VA.isRegLoc() && "Can only return in registers!");
1358     SDValue ValToCopy = OutVals[i];
1359     EVT ValVT = ValToCopy.getValueType();
1360
1361     // If this is x86-64, and we disabled SSE, we can't return FP values,
1362     // or SSE or MMX vectors.
1363     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1364          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1365           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1366       report_fatal_error("SSE register return with SSE disabled");
1367     }
1368     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1369     // llvm-gcc has never done it right and no one has noticed, so this
1370     // should be OK for now.
1371     if (ValVT == MVT::f64 &&
1372         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1373       report_fatal_error("SSE2 register return with SSE2 disabled");
1374
1375     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1376     // the RET instruction and handled by the FP Stackifier.
1377     if (VA.getLocReg() == X86::ST0 ||
1378         VA.getLocReg() == X86::ST1) {
1379       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1380       // change the value to the FP stack register class.
1381       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1382         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1383       RetOps.push_back(ValToCopy);
1384       // Don't emit a copytoreg.
1385       continue;
1386     }
1387
1388     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1389     // which is returned in RAX / RDX.
1390     if (Subtarget->is64Bit()) {
1391       if (ValVT == MVT::x86mmx) {
1392         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1393           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1394           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1395                                   ValToCopy);
1396           // If we don't have SSE2 available, convert to v4f32 so the generated
1397           // register is legal.
1398           if (!Subtarget->hasSSE2())
1399             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1400         }
1401       }
1402     }
1403
1404     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1405     Flag = Chain.getValue(1);
1406   }
1407
1408   // The x86-64 ABI for returning structs by value requires that we copy
1409   // the sret argument into %rax for the return. We saved the argument into
1410   // a virtual register in the entry block, so now we copy the value out
1411   // and into %rax.
1412   if (Subtarget->is64Bit() &&
1413       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1414     MachineFunction &MF = DAG.getMachineFunction();
1415     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1416     unsigned Reg = FuncInfo->getSRetReturnReg();
1417     assert(Reg &&
1418            "SRetReturnReg should have been set in LowerFormalArguments().");
1419     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1420
1421     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1422     Flag = Chain.getValue(1);
1423
1424     // RAX now acts like a return value.
1425     MRI.addLiveOut(X86::RAX);
1426   }
1427
1428   RetOps[0] = Chain;  // Update chain.
1429
1430   // Add the flag if we have it.
1431   if (Flag.getNode())
1432     RetOps.push_back(Flag);
1433
1434   return DAG.getNode(X86ISD::RET_FLAG, dl,
1435                      MVT::Other, &RetOps[0], RetOps.size());
1436 }
1437
1438 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1439   if (N->getNumValues() != 1)
1440     return false;
1441   if (!N->hasNUsesOfValue(1, 0))
1442     return false;
1443
1444   SDNode *Copy = *N->use_begin();
1445   if (Copy->getOpcode() != ISD::CopyToReg &&
1446       Copy->getOpcode() != ISD::FP_EXTEND)
1447     return false;
1448
1449   bool HasRet = false;
1450   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1451        UI != UE; ++UI) {
1452     if (UI->getOpcode() != X86ISD::RET_FLAG)
1453       return false;
1454     HasRet = true;
1455   }
1456
1457   return HasRet;
1458 }
1459
1460 EVT
1461 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1462                                             ISD::NodeType ExtendKind) const {
1463   MVT ReturnMVT;
1464   // TODO: Is this also valid on 32-bit?
1465   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1466     ReturnMVT = MVT::i8;
1467   else
1468     ReturnMVT = MVT::i32;
1469
1470   EVT MinVT = getRegisterType(Context, ReturnMVT);
1471   return VT.bitsLT(MinVT) ? MinVT : VT;
1472 }
1473
1474 /// LowerCallResult - Lower the result values of a call into the
1475 /// appropriate copies out of appropriate physical registers.
1476 ///
1477 SDValue
1478 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1479                                    CallingConv::ID CallConv, bool isVarArg,
1480                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1481                                    DebugLoc dl, SelectionDAG &DAG,
1482                                    SmallVectorImpl<SDValue> &InVals) const {
1483
1484   // Assign locations to each value returned by this call.
1485   SmallVector<CCValAssign, 16> RVLocs;
1486   bool Is64Bit = Subtarget->is64Bit();
1487   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1488                  getTargetMachine(), RVLocs, *DAG.getContext());
1489   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1490
1491   // Copy all of the result registers out of their specified physreg.
1492   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1493     CCValAssign &VA = RVLocs[i];
1494     EVT CopyVT = VA.getValVT();
1495
1496     // If this is x86-64, and we disabled SSE, we can't return FP values
1497     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1498         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1499       report_fatal_error("SSE register return with SSE disabled");
1500     }
1501
1502     SDValue Val;
1503
1504     // If this is a call to a function that returns an fp value on the floating
1505     // point stack, we must guarantee the the value is popped from the stack, so
1506     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1507     // if the return value is not used. We use the FpPOP_RETVAL instruction
1508     // instead.
1509     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1510       // If we prefer to use the value in xmm registers, copy it out as f80 and
1511       // use a truncate to move it from fp stack reg to xmm reg.
1512       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1513       SDValue Ops[] = { Chain, InFlag };
1514       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1515                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1516       Val = Chain.getValue(0);
1517
1518       // Round the f80 to the right size, which also moves it to the appropriate
1519       // xmm register.
1520       if (CopyVT != VA.getValVT())
1521         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1522                           // This truncation won't change the value.
1523                           DAG.getIntPtrConstant(1));
1524     } else {
1525       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1526                                  CopyVT, InFlag).getValue(1);
1527       Val = Chain.getValue(0);
1528     }
1529     InFlag = Chain.getValue(2);
1530     InVals.push_back(Val);
1531   }
1532
1533   return Chain;
1534 }
1535
1536
1537 //===----------------------------------------------------------------------===//
1538 //                C & StdCall & Fast Calling Convention implementation
1539 //===----------------------------------------------------------------------===//
1540 //  StdCall calling convention seems to be standard for many Windows' API
1541 //  routines and around. It differs from C calling convention just a little:
1542 //  callee should clean up the stack, not caller. Symbols should be also
1543 //  decorated in some fancy way :) It doesn't support any vector arguments.
1544 //  For info on fast calling convention see Fast Calling Convention (tail call)
1545 //  implementation LowerX86_32FastCCCallTo.
1546
1547 /// CallIsStructReturn - Determines whether a call uses struct return
1548 /// semantics.
1549 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1550   if (Outs.empty())
1551     return false;
1552
1553   return Outs[0].Flags.isSRet();
1554 }
1555
1556 /// ArgsAreStructReturn - Determines whether a function uses struct
1557 /// return semantics.
1558 static bool
1559 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1560   if (Ins.empty())
1561     return false;
1562
1563   return Ins[0].Flags.isSRet();
1564 }
1565
1566 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1567 /// by "Src" to address "Dst" with size and alignment information specified by
1568 /// the specific parameter attribute. The copy will be passed as a byval
1569 /// function parameter.
1570 static SDValue
1571 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1572                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1573                           DebugLoc dl) {
1574   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1575
1576   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1577                        /*isVolatile*/false, /*AlwaysInline=*/true,
1578                        MachinePointerInfo(), MachinePointerInfo());
1579 }
1580
1581 /// IsTailCallConvention - Return true if the calling convention is one that
1582 /// supports tail call optimization.
1583 static bool IsTailCallConvention(CallingConv::ID CC) {
1584   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1585 }
1586
1587 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1588   if (!CI->isTailCall())
1589     return false;
1590
1591   CallSite CS(CI);
1592   CallingConv::ID CalleeCC = CS.getCallingConv();
1593   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1594     return false;
1595
1596   return true;
1597 }
1598
1599 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1600 /// a tailcall target by changing its ABI.
1601 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1602   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1603 }
1604
1605 SDValue
1606 X86TargetLowering::LowerMemArgument(SDValue Chain,
1607                                     CallingConv::ID CallConv,
1608                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1609                                     DebugLoc dl, SelectionDAG &DAG,
1610                                     const CCValAssign &VA,
1611                                     MachineFrameInfo *MFI,
1612                                     unsigned i) const {
1613   // Create the nodes corresponding to a load from this parameter slot.
1614   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1615   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1616   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1617   EVT ValVT;
1618
1619   // If value is passed by pointer we have address passed instead of the value
1620   // itself.
1621   if (VA.getLocInfo() == CCValAssign::Indirect)
1622     ValVT = VA.getLocVT();
1623   else
1624     ValVT = VA.getValVT();
1625
1626   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1627   // changed with more analysis.
1628   // In case of tail call optimization mark all arguments mutable. Since they
1629   // could be overwritten by lowering of arguments in case of a tail call.
1630   if (Flags.isByVal()) {
1631     unsigned Bytes = Flags.getByValSize();
1632     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1633     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1634     return DAG.getFrameIndex(FI, getPointerTy());
1635   } else {
1636     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1637                                     VA.getLocMemOffset(), isImmutable);
1638     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1639     return DAG.getLoad(ValVT, dl, Chain, FIN,
1640                        MachinePointerInfo::getFixedStack(FI),
1641                        false, false, 0);
1642   }
1643 }
1644
1645 SDValue
1646 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1647                                         CallingConv::ID CallConv,
1648                                         bool isVarArg,
1649                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1650                                         DebugLoc dl,
1651                                         SelectionDAG &DAG,
1652                                         SmallVectorImpl<SDValue> &InVals)
1653                                           const {
1654   MachineFunction &MF = DAG.getMachineFunction();
1655   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1656
1657   const Function* Fn = MF.getFunction();
1658   if (Fn->hasExternalLinkage() &&
1659       Subtarget->isTargetCygMing() &&
1660       Fn->getName() == "main")
1661     FuncInfo->setForceFramePointer(true);
1662
1663   MachineFrameInfo *MFI = MF.getFrameInfo();
1664   bool Is64Bit = Subtarget->is64Bit();
1665   bool IsWin64 = Subtarget->isTargetWin64();
1666
1667   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1668          "Var args not supported with calling convention fastcc or ghc");
1669
1670   // Assign locations to all of the incoming arguments.
1671   SmallVector<CCValAssign, 16> ArgLocs;
1672   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1673                  ArgLocs, *DAG.getContext());
1674
1675   // Allocate shadow area for Win64
1676   if (IsWin64) {
1677     CCInfo.AllocateStack(32, 8);
1678   }
1679
1680   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1681
1682   unsigned LastVal = ~0U;
1683   SDValue ArgValue;
1684   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1685     CCValAssign &VA = ArgLocs[i];
1686     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1687     // places.
1688     assert(VA.getValNo() != LastVal &&
1689            "Don't support value assigned to multiple locs yet");
1690     LastVal = VA.getValNo();
1691
1692     if (VA.isRegLoc()) {
1693       EVT RegVT = VA.getLocVT();
1694       TargetRegisterClass *RC = NULL;
1695       if (RegVT == MVT::i32)
1696         RC = X86::GR32RegisterClass;
1697       else if (Is64Bit && RegVT == MVT::i64)
1698         RC = X86::GR64RegisterClass;
1699       else if (RegVT == MVT::f32)
1700         RC = X86::FR32RegisterClass;
1701       else if (RegVT == MVT::f64)
1702         RC = X86::FR64RegisterClass;
1703       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1704         RC = X86::VR256RegisterClass;
1705       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1706         RC = X86::VR128RegisterClass;
1707       else if (RegVT == MVT::x86mmx)
1708         RC = X86::VR64RegisterClass;
1709       else
1710         llvm_unreachable("Unknown argument type!");
1711
1712       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1713       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1714
1715       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1716       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1717       // right size.
1718       if (VA.getLocInfo() == CCValAssign::SExt)
1719         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1720                                DAG.getValueType(VA.getValVT()));
1721       else if (VA.getLocInfo() == CCValAssign::ZExt)
1722         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1723                                DAG.getValueType(VA.getValVT()));
1724       else if (VA.getLocInfo() == CCValAssign::BCvt)
1725         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1726
1727       if (VA.isExtInLoc()) {
1728         // Handle MMX values passed in XMM regs.
1729         if (RegVT.isVector()) {
1730           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1731                                  ArgValue);
1732         } else
1733           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1734       }
1735     } else {
1736       assert(VA.isMemLoc());
1737       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1738     }
1739
1740     // If value is passed via pointer - do a load.
1741     if (VA.getLocInfo() == CCValAssign::Indirect)
1742       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1743                              MachinePointerInfo(), false, false, 0);
1744
1745     InVals.push_back(ArgValue);
1746   }
1747
1748   // The x86-64 ABI for returning structs by value requires that we copy
1749   // the sret argument into %rax for the return. Save the argument into
1750   // a virtual register so that we can access it from the return points.
1751   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1752     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1753     unsigned Reg = FuncInfo->getSRetReturnReg();
1754     if (!Reg) {
1755       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1756       FuncInfo->setSRetReturnReg(Reg);
1757     }
1758     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1759     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1760   }
1761
1762   unsigned StackSize = CCInfo.getNextStackOffset();
1763   // Align stack specially for tail calls.
1764   if (FuncIsMadeTailCallSafe(CallConv))
1765     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1766
1767   // If the function takes variable number of arguments, make a frame index for
1768   // the start of the first vararg value... for expansion of llvm.va_start.
1769   if (isVarArg) {
1770     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1771                     CallConv != CallingConv::X86_ThisCall)) {
1772       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1773     }
1774     if (Is64Bit) {
1775       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1776
1777       // FIXME: We should really autogenerate these arrays
1778       static const unsigned GPR64ArgRegsWin64[] = {
1779         X86::RCX, X86::RDX, X86::R8,  X86::R9
1780       };
1781       static const unsigned GPR64ArgRegs64Bit[] = {
1782         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1783       };
1784       static const unsigned XMMArgRegs64Bit[] = {
1785         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1786         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1787       };
1788       const unsigned *GPR64ArgRegs;
1789       unsigned NumXMMRegs = 0;
1790
1791       if (IsWin64) {
1792         // The XMM registers which might contain var arg parameters are shadowed
1793         // in their paired GPR.  So we only need to save the GPR to their home
1794         // slots.
1795         TotalNumIntRegs = 4;
1796         GPR64ArgRegs = GPR64ArgRegsWin64;
1797       } else {
1798         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1799         GPR64ArgRegs = GPR64ArgRegs64Bit;
1800
1801         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1802       }
1803       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1804                                                        TotalNumIntRegs);
1805
1806       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1807       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1808              "SSE register cannot be used when SSE is disabled!");
1809       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1810              "SSE register cannot be used when SSE is disabled!");
1811       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1812         // Kernel mode asks for SSE to be disabled, so don't push them
1813         // on the stack.
1814         TotalNumXMMRegs = 0;
1815
1816       if (IsWin64) {
1817         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1818         // Get to the caller-allocated home save location.  Add 8 to account
1819         // for the return address.
1820         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1821         FuncInfo->setRegSaveFrameIndex(
1822           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1823         // Fixup to set vararg frame on shadow area (4 x i64).
1824         if (NumIntRegs < 4)
1825           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1826       } else {
1827         // For X86-64, if there are vararg parameters that are passed via
1828         // registers, then we must store them to their spots on the stack so they
1829         // may be loaded by deferencing the result of va_next.
1830         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1831         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1832         FuncInfo->setRegSaveFrameIndex(
1833           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1834                                false));
1835       }
1836
1837       // Store the integer parameter registers.
1838       SmallVector<SDValue, 8> MemOps;
1839       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1840                                         getPointerTy());
1841       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1842       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1843         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1844                                   DAG.getIntPtrConstant(Offset));
1845         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1846                                      X86::GR64RegisterClass);
1847         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1848         SDValue Store =
1849           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1850                        MachinePointerInfo::getFixedStack(
1851                          FuncInfo->getRegSaveFrameIndex(), Offset),
1852                        false, false, 0);
1853         MemOps.push_back(Store);
1854         Offset += 8;
1855       }
1856
1857       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1858         // Now store the XMM (fp + vector) parameter registers.
1859         SmallVector<SDValue, 11> SaveXMMOps;
1860         SaveXMMOps.push_back(Chain);
1861
1862         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1863         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1864         SaveXMMOps.push_back(ALVal);
1865
1866         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1867                                FuncInfo->getRegSaveFrameIndex()));
1868         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1869                                FuncInfo->getVarArgsFPOffset()));
1870
1871         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1872           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1873                                        X86::VR128RegisterClass);
1874           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1875           SaveXMMOps.push_back(Val);
1876         }
1877         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1878                                      MVT::Other,
1879                                      &SaveXMMOps[0], SaveXMMOps.size()));
1880       }
1881
1882       if (!MemOps.empty())
1883         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1884                             &MemOps[0], MemOps.size());
1885     }
1886   }
1887
1888   // Some CCs need callee pop.
1889   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1890     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1891   } else {
1892     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1893     // If this is an sret function, the return should pop the hidden pointer.
1894     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1895       FuncInfo->setBytesToPopOnReturn(4);
1896   }
1897
1898   if (!Is64Bit) {
1899     // RegSaveFrameIndex is X86-64 only.
1900     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1901     if (CallConv == CallingConv::X86_FastCall ||
1902         CallConv == CallingConv::X86_ThisCall)
1903       // fastcc functions can't have varargs.
1904       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1905   }
1906
1907   return Chain;
1908 }
1909
1910 SDValue
1911 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1912                                     SDValue StackPtr, SDValue Arg,
1913                                     DebugLoc dl, SelectionDAG &DAG,
1914                                     const CCValAssign &VA,
1915                                     ISD::ArgFlagsTy Flags) const {
1916   unsigned LocMemOffset = VA.getLocMemOffset();
1917   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1918   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1919   if (Flags.isByVal())
1920     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1921
1922   return DAG.getStore(Chain, dl, Arg, PtrOff,
1923                       MachinePointerInfo::getStack(LocMemOffset),
1924                       false, false, 0);
1925 }
1926
1927 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1928 /// optimization is performed and it is required.
1929 SDValue
1930 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1931                                            SDValue &OutRetAddr, SDValue Chain,
1932                                            bool IsTailCall, bool Is64Bit,
1933                                            int FPDiff, DebugLoc dl) const {
1934   // Adjust the Return address stack slot.
1935   EVT VT = getPointerTy();
1936   OutRetAddr = getReturnAddressFrameIndex(DAG);
1937
1938   // Load the "old" Return address.
1939   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1940                            false, false, 0);
1941   return SDValue(OutRetAddr.getNode(), 1);
1942 }
1943
1944 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1945 /// optimization is performed and it is required (FPDiff!=0).
1946 static SDValue
1947 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1948                          SDValue Chain, SDValue RetAddrFrIdx,
1949                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1950   // Store the return address to the appropriate stack slot.
1951   if (!FPDiff) return Chain;
1952   // Calculate the new stack slot for the return address.
1953   int SlotSize = Is64Bit ? 8 : 4;
1954   int NewReturnAddrFI =
1955     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1956   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1957   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1958   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1959                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1960                        false, false, 0);
1961   return Chain;
1962 }
1963
1964 SDValue
1965 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1966                              CallingConv::ID CallConv, bool isVarArg,
1967                              bool &isTailCall,
1968                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1969                              const SmallVectorImpl<SDValue> &OutVals,
1970                              const SmallVectorImpl<ISD::InputArg> &Ins,
1971                              DebugLoc dl, SelectionDAG &DAG,
1972                              SmallVectorImpl<SDValue> &InVals) const {
1973   MachineFunction &MF = DAG.getMachineFunction();
1974   bool Is64Bit        = Subtarget->is64Bit();
1975   bool IsWin64        = Subtarget->isTargetWin64();
1976   bool IsStructRet    = CallIsStructReturn(Outs);
1977   bool IsSibcall      = false;
1978
1979   if (isTailCall) {
1980     // Check if it's really possible to do a tail call.
1981     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1982                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1983                                                    Outs, OutVals, Ins, DAG);
1984
1985     // Sibcalls are automatically detected tailcalls which do not require
1986     // ABI changes.
1987     if (!GuaranteedTailCallOpt && isTailCall)
1988       IsSibcall = true;
1989
1990     if (isTailCall)
1991       ++NumTailCalls;
1992   }
1993
1994   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1995          "Var args not supported with calling convention fastcc or ghc");
1996
1997   // Analyze operands of the call, assigning locations to each operand.
1998   SmallVector<CCValAssign, 16> ArgLocs;
1999   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2000                  ArgLocs, *DAG.getContext());
2001
2002   // Allocate shadow area for Win64
2003   if (IsWin64) {
2004     CCInfo.AllocateStack(32, 8);
2005   }
2006
2007   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2008
2009   // Get a count of how many bytes are to be pushed on the stack.
2010   unsigned NumBytes = CCInfo.getNextStackOffset();
2011   if (IsSibcall)
2012     // This is a sibcall. The memory operands are available in caller's
2013     // own caller's stack.
2014     NumBytes = 0;
2015   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2016     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2017
2018   int FPDiff = 0;
2019   if (isTailCall && !IsSibcall) {
2020     // Lower arguments at fp - stackoffset + fpdiff.
2021     unsigned NumBytesCallerPushed =
2022       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2023     FPDiff = NumBytesCallerPushed - NumBytes;
2024
2025     // Set the delta of movement of the returnaddr stackslot.
2026     // But only set if delta is greater than previous delta.
2027     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2028       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2029   }
2030
2031   if (!IsSibcall)
2032     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2033
2034   SDValue RetAddrFrIdx;
2035   // Load return address for tail calls.
2036   if (isTailCall && FPDiff)
2037     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2038                                     Is64Bit, FPDiff, dl);
2039
2040   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2041   SmallVector<SDValue, 8> MemOpChains;
2042   SDValue StackPtr;
2043
2044   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2045   // of tail call optimization arguments are handle later.
2046   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2047     CCValAssign &VA = ArgLocs[i];
2048     EVT RegVT = VA.getLocVT();
2049     SDValue Arg = OutVals[i];
2050     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2051     bool isByVal = Flags.isByVal();
2052
2053     // Promote the value if needed.
2054     switch (VA.getLocInfo()) {
2055     default: llvm_unreachable("Unknown loc info!");
2056     case CCValAssign::Full: break;
2057     case CCValAssign::SExt:
2058       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2059       break;
2060     case CCValAssign::ZExt:
2061       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2062       break;
2063     case CCValAssign::AExt:
2064       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2065         // Special case: passing MMX values in XMM registers.
2066         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2067         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2068         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2069       } else
2070         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2071       break;
2072     case CCValAssign::BCvt:
2073       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2074       break;
2075     case CCValAssign::Indirect: {
2076       // Store the argument.
2077       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2078       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2079       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2080                            MachinePointerInfo::getFixedStack(FI),
2081                            false, false, 0);
2082       Arg = SpillSlot;
2083       break;
2084     }
2085     }
2086
2087     if (VA.isRegLoc()) {
2088       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2089       if (isVarArg && IsWin64) {
2090         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2091         // shadow reg if callee is a varargs function.
2092         unsigned ShadowReg = 0;
2093         switch (VA.getLocReg()) {
2094         case X86::XMM0: ShadowReg = X86::RCX; break;
2095         case X86::XMM1: ShadowReg = X86::RDX; break;
2096         case X86::XMM2: ShadowReg = X86::R8; break;
2097         case X86::XMM3: ShadowReg = X86::R9; break;
2098         }
2099         if (ShadowReg)
2100           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2101       }
2102     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2103       assert(VA.isMemLoc());
2104       if (StackPtr.getNode() == 0)
2105         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2106       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2107                                              dl, DAG, VA, Flags));
2108     }
2109   }
2110
2111   if (!MemOpChains.empty())
2112     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2113                         &MemOpChains[0], MemOpChains.size());
2114
2115   // Build a sequence of copy-to-reg nodes chained together with token chain
2116   // and flag operands which copy the outgoing args into registers.
2117   SDValue InFlag;
2118   // Tail call byval lowering might overwrite argument registers so in case of
2119   // tail call optimization the copies to registers are lowered later.
2120   if (!isTailCall)
2121     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2122       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2123                                RegsToPass[i].second, InFlag);
2124       InFlag = Chain.getValue(1);
2125     }
2126
2127   if (Subtarget->isPICStyleGOT()) {
2128     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2129     // GOT pointer.
2130     if (!isTailCall) {
2131       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2132                                DAG.getNode(X86ISD::GlobalBaseReg,
2133                                            DebugLoc(), getPointerTy()),
2134                                InFlag);
2135       InFlag = Chain.getValue(1);
2136     } else {
2137       // If we are tail calling and generating PIC/GOT style code load the
2138       // address of the callee into ECX. The value in ecx is used as target of
2139       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2140       // for tail calls on PIC/GOT architectures. Normally we would just put the
2141       // address of GOT into ebx and then call target@PLT. But for tail calls
2142       // ebx would be restored (since ebx is callee saved) before jumping to the
2143       // target@PLT.
2144
2145       // Note: The actual moving to ECX is done further down.
2146       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2147       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2148           !G->getGlobal()->hasProtectedVisibility())
2149         Callee = LowerGlobalAddress(Callee, DAG);
2150       else if (isa<ExternalSymbolSDNode>(Callee))
2151         Callee = LowerExternalSymbol(Callee, DAG);
2152     }
2153   }
2154
2155   if (Is64Bit && isVarArg && !IsWin64) {
2156     // From AMD64 ABI document:
2157     // For calls that may call functions that use varargs or stdargs
2158     // (prototype-less calls or calls to functions containing ellipsis (...) in
2159     // the declaration) %al is used as hidden argument to specify the number
2160     // of SSE registers used. The contents of %al do not need to match exactly
2161     // the number of registers, but must be an ubound on the number of SSE
2162     // registers used and is in the range 0 - 8 inclusive.
2163
2164     // Count the number of XMM registers allocated.
2165     static const unsigned XMMArgRegs[] = {
2166       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2167       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2168     };
2169     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2170     assert((Subtarget->hasXMM() || !NumXMMRegs)
2171            && "SSE registers cannot be used when SSE is disabled");
2172
2173     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2174                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2175     InFlag = Chain.getValue(1);
2176   }
2177
2178
2179   // For tail calls lower the arguments to the 'real' stack slot.
2180   if (isTailCall) {
2181     // Force all the incoming stack arguments to be loaded from the stack
2182     // before any new outgoing arguments are stored to the stack, because the
2183     // outgoing stack slots may alias the incoming argument stack slots, and
2184     // the alias isn't otherwise explicit. This is slightly more conservative
2185     // than necessary, because it means that each store effectively depends
2186     // on every argument instead of just those arguments it would clobber.
2187     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2188
2189     SmallVector<SDValue, 8> MemOpChains2;
2190     SDValue FIN;
2191     int FI = 0;
2192     // Do not flag preceding copytoreg stuff together with the following stuff.
2193     InFlag = SDValue();
2194     if (GuaranteedTailCallOpt) {
2195       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2196         CCValAssign &VA = ArgLocs[i];
2197         if (VA.isRegLoc())
2198           continue;
2199         assert(VA.isMemLoc());
2200         SDValue Arg = OutVals[i];
2201         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2202         // Create frame index.
2203         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2204         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2205         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2206         FIN = DAG.getFrameIndex(FI, getPointerTy());
2207
2208         if (Flags.isByVal()) {
2209           // Copy relative to framepointer.
2210           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2211           if (StackPtr.getNode() == 0)
2212             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2213                                           getPointerTy());
2214           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2215
2216           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2217                                                            ArgChain,
2218                                                            Flags, DAG, dl));
2219         } else {
2220           // Store relative to framepointer.
2221           MemOpChains2.push_back(
2222             DAG.getStore(ArgChain, dl, Arg, FIN,
2223                          MachinePointerInfo::getFixedStack(FI),
2224                          false, false, 0));
2225         }
2226       }
2227     }
2228
2229     if (!MemOpChains2.empty())
2230       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2231                           &MemOpChains2[0], MemOpChains2.size());
2232
2233     // Copy arguments to their registers.
2234     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2235       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2236                                RegsToPass[i].second, InFlag);
2237       InFlag = Chain.getValue(1);
2238     }
2239     InFlag =SDValue();
2240
2241     // Store the return address to the appropriate stack slot.
2242     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2243                                      FPDiff, dl);
2244   }
2245
2246   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2247     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2248     // In the 64-bit large code model, we have to make all calls
2249     // through a register, since the call instruction's 32-bit
2250     // pc-relative offset may not be large enough to hold the whole
2251     // address.
2252   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2253     // If the callee is a GlobalAddress node (quite common, every direct call
2254     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2255     // it.
2256
2257     // We should use extra load for direct calls to dllimported functions in
2258     // non-JIT mode.
2259     const GlobalValue *GV = G->getGlobal();
2260     if (!GV->hasDLLImportLinkage()) {
2261       unsigned char OpFlags = 0;
2262       bool ExtraLoad = false;
2263       unsigned WrapperKind = ISD::DELETED_NODE;
2264
2265       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2266       // external symbols most go through the PLT in PIC mode.  If the symbol
2267       // has hidden or protected visibility, or if it is static or local, then
2268       // we don't need to use the PLT - we can directly call it.
2269       if (Subtarget->isTargetELF() &&
2270           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2271           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2272         OpFlags = X86II::MO_PLT;
2273       } else if (Subtarget->isPICStyleStubAny() &&
2274                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2275                  (!Subtarget->getTargetTriple().isMacOSX() ||
2276                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2277         // PC-relative references to external symbols should go through $stub,
2278         // unless we're building with the leopard linker or later, which
2279         // automatically synthesizes these stubs.
2280         OpFlags = X86II::MO_DARWIN_STUB;
2281       } else if (Subtarget->isPICStyleRIPRel() &&
2282                  isa<Function>(GV) &&
2283                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2284         // If the function is marked as non-lazy, generate an indirect call
2285         // which loads from the GOT directly. This avoids runtime overhead
2286         // at the cost of eager binding (and one extra byte of encoding).
2287         OpFlags = X86II::MO_GOTPCREL;
2288         WrapperKind = X86ISD::WrapperRIP;
2289         ExtraLoad = true;
2290       }
2291
2292       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2293                                           G->getOffset(), OpFlags);
2294
2295       // Add a wrapper if needed.
2296       if (WrapperKind != ISD::DELETED_NODE)
2297         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2298       // Add extra indirection if needed.
2299       if (ExtraLoad)
2300         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2301                              MachinePointerInfo::getGOT(),
2302                              false, false, 0);
2303     }
2304   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2305     unsigned char OpFlags = 0;
2306
2307     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2308     // external symbols should go through the PLT.
2309     if (Subtarget->isTargetELF() &&
2310         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2311       OpFlags = X86II::MO_PLT;
2312     } else if (Subtarget->isPICStyleStubAny() &&
2313                (!Subtarget->getTargetTriple().isMacOSX() ||
2314                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2315       // PC-relative references to external symbols should go through $stub,
2316       // unless we're building with the leopard linker or later, which
2317       // automatically synthesizes these stubs.
2318       OpFlags = X86II::MO_DARWIN_STUB;
2319     }
2320
2321     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2322                                          OpFlags);
2323   }
2324
2325   // Returns a chain & a flag for retval copy to use.
2326   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2327   SmallVector<SDValue, 8> Ops;
2328
2329   if (!IsSibcall && isTailCall) {
2330     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2331                            DAG.getIntPtrConstant(0, true), InFlag);
2332     InFlag = Chain.getValue(1);
2333   }
2334
2335   Ops.push_back(Chain);
2336   Ops.push_back(Callee);
2337
2338   if (isTailCall)
2339     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2340
2341   // Add argument registers to the end of the list so that they are known live
2342   // into the call.
2343   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2344     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2345                                   RegsToPass[i].second.getValueType()));
2346
2347   // Add an implicit use GOT pointer in EBX.
2348   if (!isTailCall && Subtarget->isPICStyleGOT())
2349     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2350
2351   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2352   if (Is64Bit && isVarArg && !IsWin64)
2353     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2354
2355   if (InFlag.getNode())
2356     Ops.push_back(InFlag);
2357
2358   if (isTailCall) {
2359     // We used to do:
2360     //// If this is the first return lowered for this function, add the regs
2361     //// to the liveout set for the function.
2362     // This isn't right, although it's probably harmless on x86; liveouts
2363     // should be computed from returns not tail calls.  Consider a void
2364     // function making a tail call to a function returning int.
2365     return DAG.getNode(X86ISD::TC_RETURN, dl,
2366                        NodeTys, &Ops[0], Ops.size());
2367   }
2368
2369   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2370   InFlag = Chain.getValue(1);
2371
2372   // Create the CALLSEQ_END node.
2373   unsigned NumBytesForCalleeToPush;
2374   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2375     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2376   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2377     // If this is a call to a struct-return function, the callee
2378     // pops the hidden struct pointer, so we have to push it back.
2379     // This is common for Darwin/X86, Linux & Mingw32 targets.
2380     NumBytesForCalleeToPush = 4;
2381   else
2382     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2383
2384   // Returns a flag for retval copy to use.
2385   if (!IsSibcall) {
2386     Chain = DAG.getCALLSEQ_END(Chain,
2387                                DAG.getIntPtrConstant(NumBytes, true),
2388                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2389                                                      true),
2390                                InFlag);
2391     InFlag = Chain.getValue(1);
2392   }
2393
2394   // Handle result values, copying them out of physregs into vregs that we
2395   // return.
2396   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2397                          Ins, dl, DAG, InVals);
2398 }
2399
2400
2401 //===----------------------------------------------------------------------===//
2402 //                Fast Calling Convention (tail call) implementation
2403 //===----------------------------------------------------------------------===//
2404
2405 //  Like std call, callee cleans arguments, convention except that ECX is
2406 //  reserved for storing the tail called function address. Only 2 registers are
2407 //  free for argument passing (inreg). Tail call optimization is performed
2408 //  provided:
2409 //                * tailcallopt is enabled
2410 //                * caller/callee are fastcc
2411 //  On X86_64 architecture with GOT-style position independent code only local
2412 //  (within module) calls are supported at the moment.
2413 //  To keep the stack aligned according to platform abi the function
2414 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2415 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2416 //  If a tail called function callee has more arguments than the caller the
2417 //  caller needs to make sure that there is room to move the RETADDR to. This is
2418 //  achieved by reserving an area the size of the argument delta right after the
2419 //  original REtADDR, but before the saved framepointer or the spilled registers
2420 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2421 //  stack layout:
2422 //    arg1
2423 //    arg2
2424 //    RETADDR
2425 //    [ new RETADDR
2426 //      move area ]
2427 //    (possible EBP)
2428 //    ESI
2429 //    EDI
2430 //    local1 ..
2431
2432 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2433 /// for a 16 byte align requirement.
2434 unsigned
2435 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2436                                                SelectionDAG& DAG) const {
2437   MachineFunction &MF = DAG.getMachineFunction();
2438   const TargetMachine &TM = MF.getTarget();
2439   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2440   unsigned StackAlignment = TFI.getStackAlignment();
2441   uint64_t AlignMask = StackAlignment - 1;
2442   int64_t Offset = StackSize;
2443   uint64_t SlotSize = TD->getPointerSize();
2444   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2445     // Number smaller than 12 so just add the difference.
2446     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2447   } else {
2448     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2449     Offset = ((~AlignMask) & Offset) + StackAlignment +
2450       (StackAlignment-SlotSize);
2451   }
2452   return Offset;
2453 }
2454
2455 /// MatchingStackOffset - Return true if the given stack call argument is
2456 /// already available in the same position (relatively) of the caller's
2457 /// incoming argument stack.
2458 static
2459 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2460                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2461                          const X86InstrInfo *TII) {
2462   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2463   int FI = INT_MAX;
2464   if (Arg.getOpcode() == ISD::CopyFromReg) {
2465     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2466     if (!TargetRegisterInfo::isVirtualRegister(VR))
2467       return false;
2468     MachineInstr *Def = MRI->getVRegDef(VR);
2469     if (!Def)
2470       return false;
2471     if (!Flags.isByVal()) {
2472       if (!TII->isLoadFromStackSlot(Def, FI))
2473         return false;
2474     } else {
2475       unsigned Opcode = Def->getOpcode();
2476       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2477           Def->getOperand(1).isFI()) {
2478         FI = Def->getOperand(1).getIndex();
2479         Bytes = Flags.getByValSize();
2480       } else
2481         return false;
2482     }
2483   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2484     if (Flags.isByVal())
2485       // ByVal argument is passed in as a pointer but it's now being
2486       // dereferenced. e.g.
2487       // define @foo(%struct.X* %A) {
2488       //   tail call @bar(%struct.X* byval %A)
2489       // }
2490       return false;
2491     SDValue Ptr = Ld->getBasePtr();
2492     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2493     if (!FINode)
2494       return false;
2495     FI = FINode->getIndex();
2496   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2497     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2498     FI = FINode->getIndex();
2499     Bytes = Flags.getByValSize();
2500   } else
2501     return false;
2502
2503   assert(FI != INT_MAX);
2504   if (!MFI->isFixedObjectIndex(FI))
2505     return false;
2506   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2507 }
2508
2509 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2510 /// for tail call optimization. Targets which want to do tail call
2511 /// optimization should implement this function.
2512 bool
2513 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2514                                                      CallingConv::ID CalleeCC,
2515                                                      bool isVarArg,
2516                                                      bool isCalleeStructRet,
2517                                                      bool isCallerStructRet,
2518                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2519                                     const SmallVectorImpl<SDValue> &OutVals,
2520                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2521                                                      SelectionDAG& DAG) const {
2522   if (!IsTailCallConvention(CalleeCC) &&
2523       CalleeCC != CallingConv::C)
2524     return false;
2525
2526   // If -tailcallopt is specified, make fastcc functions tail-callable.
2527   const MachineFunction &MF = DAG.getMachineFunction();
2528   const Function *CallerF = DAG.getMachineFunction().getFunction();
2529   CallingConv::ID CallerCC = CallerF->getCallingConv();
2530   bool CCMatch = CallerCC == CalleeCC;
2531
2532   if (GuaranteedTailCallOpt) {
2533     if (IsTailCallConvention(CalleeCC) && CCMatch)
2534       return true;
2535     return false;
2536   }
2537
2538   // Look for obvious safe cases to perform tail call optimization that do not
2539   // require ABI changes. This is what gcc calls sibcall.
2540
2541   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2542   // emit a special epilogue.
2543   if (RegInfo->needsStackRealignment(MF))
2544     return false;
2545
2546   // Also avoid sibcall optimization if either caller or callee uses struct
2547   // return semantics.
2548   if (isCalleeStructRet || isCallerStructRet)
2549     return false;
2550
2551   // An stdcall caller is expected to clean up its arguments; the callee
2552   // isn't going to do that.
2553   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2554     return false;
2555
2556   // Do not sibcall optimize vararg calls unless all arguments are passed via
2557   // registers.
2558   if (isVarArg && !Outs.empty()) {
2559
2560     // Optimizing for varargs on Win64 is unlikely to be safe without
2561     // additional testing.
2562     if (Subtarget->isTargetWin64())
2563       return false;
2564
2565     SmallVector<CCValAssign, 16> ArgLocs;
2566     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2567                    getTargetMachine(), ArgLocs, *DAG.getContext());
2568
2569     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2570     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2571       if (!ArgLocs[i].isRegLoc())
2572         return false;
2573   }
2574
2575   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2576   // Therefore if it's not used by the call it is not safe to optimize this into
2577   // a sibcall.
2578   bool Unused = false;
2579   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2580     if (!Ins[i].Used) {
2581       Unused = true;
2582       break;
2583     }
2584   }
2585   if (Unused) {
2586     SmallVector<CCValAssign, 16> RVLocs;
2587     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2588                    getTargetMachine(), RVLocs, *DAG.getContext());
2589     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2590     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2591       CCValAssign &VA = RVLocs[i];
2592       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2593         return false;
2594     }
2595   }
2596
2597   // If the calling conventions do not match, then we'd better make sure the
2598   // results are returned in the same way as what the caller expects.
2599   if (!CCMatch) {
2600     SmallVector<CCValAssign, 16> RVLocs1;
2601     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2602                     getTargetMachine(), RVLocs1, *DAG.getContext());
2603     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2604
2605     SmallVector<CCValAssign, 16> RVLocs2;
2606     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2607                     getTargetMachine(), RVLocs2, *DAG.getContext());
2608     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2609
2610     if (RVLocs1.size() != RVLocs2.size())
2611       return false;
2612     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2613       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2614         return false;
2615       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2616         return false;
2617       if (RVLocs1[i].isRegLoc()) {
2618         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2619           return false;
2620       } else {
2621         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2622           return false;
2623       }
2624     }
2625   }
2626
2627   // If the callee takes no arguments then go on to check the results of the
2628   // call.
2629   if (!Outs.empty()) {
2630     // Check if stack adjustment is needed. For now, do not do this if any
2631     // argument is passed on the stack.
2632     SmallVector<CCValAssign, 16> ArgLocs;
2633     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2634                    getTargetMachine(), ArgLocs, *DAG.getContext());
2635
2636     // Allocate shadow area for Win64
2637     if (Subtarget->isTargetWin64()) {
2638       CCInfo.AllocateStack(32, 8);
2639     }
2640
2641     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2642     if (CCInfo.getNextStackOffset()) {
2643       MachineFunction &MF = DAG.getMachineFunction();
2644       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2645         return false;
2646
2647       // Check if the arguments are already laid out in the right way as
2648       // the caller's fixed stack objects.
2649       MachineFrameInfo *MFI = MF.getFrameInfo();
2650       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2651       const X86InstrInfo *TII =
2652         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2653       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2654         CCValAssign &VA = ArgLocs[i];
2655         SDValue Arg = OutVals[i];
2656         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2657         if (VA.getLocInfo() == CCValAssign::Indirect)
2658           return false;
2659         if (!VA.isRegLoc()) {
2660           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2661                                    MFI, MRI, TII))
2662             return false;
2663         }
2664       }
2665     }
2666
2667     // If the tailcall address may be in a register, then make sure it's
2668     // possible to register allocate for it. In 32-bit, the call address can
2669     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2670     // callee-saved registers are restored. These happen to be the same
2671     // registers used to pass 'inreg' arguments so watch out for those.
2672     if (!Subtarget->is64Bit() &&
2673         !isa<GlobalAddressSDNode>(Callee) &&
2674         !isa<ExternalSymbolSDNode>(Callee)) {
2675       unsigned NumInRegs = 0;
2676       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2677         CCValAssign &VA = ArgLocs[i];
2678         if (!VA.isRegLoc())
2679           continue;
2680         unsigned Reg = VA.getLocReg();
2681         switch (Reg) {
2682         default: break;
2683         case X86::EAX: case X86::EDX: case X86::ECX:
2684           if (++NumInRegs == 3)
2685             return false;
2686           break;
2687         }
2688       }
2689     }
2690   }
2691
2692   return true;
2693 }
2694
2695 FastISel *
2696 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2697   return X86::createFastISel(funcInfo);
2698 }
2699
2700
2701 //===----------------------------------------------------------------------===//
2702 //                           Other Lowering Hooks
2703 //===----------------------------------------------------------------------===//
2704
2705 static bool MayFoldLoad(SDValue Op) {
2706   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2707 }
2708
2709 static bool MayFoldIntoStore(SDValue Op) {
2710   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2711 }
2712
2713 static bool isTargetShuffle(unsigned Opcode) {
2714   switch(Opcode) {
2715   default: return false;
2716   case X86ISD::PSHUFD:
2717   case X86ISD::PSHUFHW:
2718   case X86ISD::PSHUFLW:
2719   case X86ISD::SHUFPD:
2720   case X86ISD::PALIGN:
2721   case X86ISD::SHUFPS:
2722   case X86ISD::MOVLHPS:
2723   case X86ISD::MOVLHPD:
2724   case X86ISD::MOVHLPS:
2725   case X86ISD::MOVLPS:
2726   case X86ISD::MOVLPD:
2727   case X86ISD::MOVSHDUP:
2728   case X86ISD::MOVSLDUP:
2729   case X86ISD::MOVDDUP:
2730   case X86ISD::MOVSS:
2731   case X86ISD::MOVSD:
2732   case X86ISD::UNPCKLPS:
2733   case X86ISD::UNPCKLPD:
2734   case X86ISD::VUNPCKLPSY:
2735   case X86ISD::VUNPCKLPDY:
2736   case X86ISD::PUNPCKLWD:
2737   case X86ISD::PUNPCKLBW:
2738   case X86ISD::PUNPCKLDQ:
2739   case X86ISD::PUNPCKLQDQ:
2740   case X86ISD::UNPCKHPS:
2741   case X86ISD::UNPCKHPD:
2742   case X86ISD::VUNPCKHPSY:
2743   case X86ISD::VUNPCKHPDY:
2744   case X86ISD::PUNPCKHWD:
2745   case X86ISD::PUNPCKHBW:
2746   case X86ISD::PUNPCKHDQ:
2747   case X86ISD::PUNPCKHQDQ:
2748   case X86ISD::VPERMILPS:
2749   case X86ISD::VPERMILPSY:
2750   case X86ISD::VPERMILPD:
2751   case X86ISD::VPERMILPDY:
2752     return true;
2753   }
2754   return false;
2755 }
2756
2757 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2758                                                SDValue V1, SelectionDAG &DAG) {
2759   switch(Opc) {
2760   default: llvm_unreachable("Unknown x86 shuffle node");
2761   case X86ISD::MOVSHDUP:
2762   case X86ISD::MOVSLDUP:
2763   case X86ISD::MOVDDUP:
2764     return DAG.getNode(Opc, dl, VT, V1);
2765   }
2766
2767   return SDValue();
2768 }
2769
2770 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2771                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2772   switch(Opc) {
2773   default: llvm_unreachable("Unknown x86 shuffle node");
2774   case X86ISD::PSHUFD:
2775   case X86ISD::PSHUFHW:
2776   case X86ISD::PSHUFLW:
2777   case X86ISD::VPERMILPS:
2778   case X86ISD::VPERMILPSY:
2779   case X86ISD::VPERMILPD:
2780   case X86ISD::VPERMILPDY:
2781     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2782   }
2783
2784   return SDValue();
2785 }
2786
2787 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2788                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2789   switch(Opc) {
2790   default: llvm_unreachable("Unknown x86 shuffle node");
2791   case X86ISD::PALIGN:
2792   case X86ISD::SHUFPD:
2793   case X86ISD::SHUFPS:
2794     return DAG.getNode(Opc, dl, VT, V1, V2,
2795                        DAG.getConstant(TargetMask, MVT::i8));
2796   }
2797   return SDValue();
2798 }
2799
2800 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2801                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2802   switch(Opc) {
2803   default: llvm_unreachable("Unknown x86 shuffle node");
2804   case X86ISD::MOVLHPS:
2805   case X86ISD::MOVLHPD:
2806   case X86ISD::MOVHLPS:
2807   case X86ISD::MOVLPS:
2808   case X86ISD::MOVLPD:
2809   case X86ISD::MOVSS:
2810   case X86ISD::MOVSD:
2811   case X86ISD::UNPCKLPS:
2812   case X86ISD::UNPCKLPD:
2813   case X86ISD::VUNPCKLPSY:
2814   case X86ISD::VUNPCKLPDY:
2815   case X86ISD::PUNPCKLWD:
2816   case X86ISD::PUNPCKLBW:
2817   case X86ISD::PUNPCKLDQ:
2818   case X86ISD::PUNPCKLQDQ:
2819   case X86ISD::UNPCKHPS:
2820   case X86ISD::UNPCKHPD:
2821   case X86ISD::VUNPCKHPSY:
2822   case X86ISD::VUNPCKHPDY:
2823   case X86ISD::PUNPCKHWD:
2824   case X86ISD::PUNPCKHBW:
2825   case X86ISD::PUNPCKHDQ:
2826   case X86ISD::PUNPCKHQDQ:
2827     return DAG.getNode(Opc, dl, VT, V1, V2);
2828   }
2829   return SDValue();
2830 }
2831
2832 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2833   MachineFunction &MF = DAG.getMachineFunction();
2834   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2835   int ReturnAddrIndex = FuncInfo->getRAIndex();
2836
2837   if (ReturnAddrIndex == 0) {
2838     // Set up a frame object for the return address.
2839     uint64_t SlotSize = TD->getPointerSize();
2840     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2841                                                            false);
2842     FuncInfo->setRAIndex(ReturnAddrIndex);
2843   }
2844
2845   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2846 }
2847
2848
2849 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2850                                        bool hasSymbolicDisplacement) {
2851   // Offset should fit into 32 bit immediate field.
2852   if (!isInt<32>(Offset))
2853     return false;
2854
2855   // If we don't have a symbolic displacement - we don't have any extra
2856   // restrictions.
2857   if (!hasSymbolicDisplacement)
2858     return true;
2859
2860   // FIXME: Some tweaks might be needed for medium code model.
2861   if (M != CodeModel::Small && M != CodeModel::Kernel)
2862     return false;
2863
2864   // For small code model we assume that latest object is 16MB before end of 31
2865   // bits boundary. We may also accept pretty large negative constants knowing
2866   // that all objects are in the positive half of address space.
2867   if (M == CodeModel::Small && Offset < 16*1024*1024)
2868     return true;
2869
2870   // For kernel code model we know that all object resist in the negative half
2871   // of 32bits address space. We may not accept negative offsets, since they may
2872   // be just off and we may accept pretty large positive ones.
2873   if (M == CodeModel::Kernel && Offset > 0)
2874     return true;
2875
2876   return false;
2877 }
2878
2879 /// isCalleePop - Determines whether the callee is required to pop its
2880 /// own arguments. Callee pop is necessary to support tail calls.
2881 bool X86::isCalleePop(CallingConv::ID CallingConv,
2882                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2883   if (IsVarArg)
2884     return false;
2885
2886   switch (CallingConv) {
2887   default:
2888     return false;
2889   case CallingConv::X86_StdCall:
2890     return !is64Bit;
2891   case CallingConv::X86_FastCall:
2892     return !is64Bit;
2893   case CallingConv::X86_ThisCall:
2894     return !is64Bit;
2895   case CallingConv::Fast:
2896     return TailCallOpt;
2897   case CallingConv::GHC:
2898     return TailCallOpt;
2899   }
2900 }
2901
2902 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2903 /// specific condition code, returning the condition code and the LHS/RHS of the
2904 /// comparison to make.
2905 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2906                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2907   if (!isFP) {
2908     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2909       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2910         // X > -1   -> X == 0, jump !sign.
2911         RHS = DAG.getConstant(0, RHS.getValueType());
2912         return X86::COND_NS;
2913       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2914         // X < 0   -> X == 0, jump on sign.
2915         return X86::COND_S;
2916       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2917         // X < 1   -> X <= 0
2918         RHS = DAG.getConstant(0, RHS.getValueType());
2919         return X86::COND_LE;
2920       }
2921     }
2922
2923     switch (SetCCOpcode) {
2924     default: llvm_unreachable("Invalid integer condition!");
2925     case ISD::SETEQ:  return X86::COND_E;
2926     case ISD::SETGT:  return X86::COND_G;
2927     case ISD::SETGE:  return X86::COND_GE;
2928     case ISD::SETLT:  return X86::COND_L;
2929     case ISD::SETLE:  return X86::COND_LE;
2930     case ISD::SETNE:  return X86::COND_NE;
2931     case ISD::SETULT: return X86::COND_B;
2932     case ISD::SETUGT: return X86::COND_A;
2933     case ISD::SETULE: return X86::COND_BE;
2934     case ISD::SETUGE: return X86::COND_AE;
2935     }
2936   }
2937
2938   // First determine if it is required or is profitable to flip the operands.
2939
2940   // If LHS is a foldable load, but RHS is not, flip the condition.
2941   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2942       !ISD::isNON_EXTLoad(RHS.getNode())) {
2943     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2944     std::swap(LHS, RHS);
2945   }
2946
2947   switch (SetCCOpcode) {
2948   default: break;
2949   case ISD::SETOLT:
2950   case ISD::SETOLE:
2951   case ISD::SETUGT:
2952   case ISD::SETUGE:
2953     std::swap(LHS, RHS);
2954     break;
2955   }
2956
2957   // On a floating point condition, the flags are set as follows:
2958   // ZF  PF  CF   op
2959   //  0 | 0 | 0 | X > Y
2960   //  0 | 0 | 1 | X < Y
2961   //  1 | 0 | 0 | X == Y
2962   //  1 | 1 | 1 | unordered
2963   switch (SetCCOpcode) {
2964   default: llvm_unreachable("Condcode should be pre-legalized away");
2965   case ISD::SETUEQ:
2966   case ISD::SETEQ:   return X86::COND_E;
2967   case ISD::SETOLT:              // flipped
2968   case ISD::SETOGT:
2969   case ISD::SETGT:   return X86::COND_A;
2970   case ISD::SETOLE:              // flipped
2971   case ISD::SETOGE:
2972   case ISD::SETGE:   return X86::COND_AE;
2973   case ISD::SETUGT:              // flipped
2974   case ISD::SETULT:
2975   case ISD::SETLT:   return X86::COND_B;
2976   case ISD::SETUGE:              // flipped
2977   case ISD::SETULE:
2978   case ISD::SETLE:   return X86::COND_BE;
2979   case ISD::SETONE:
2980   case ISD::SETNE:   return X86::COND_NE;
2981   case ISD::SETUO:   return X86::COND_P;
2982   case ISD::SETO:    return X86::COND_NP;
2983   case ISD::SETOEQ:
2984   case ISD::SETUNE:  return X86::COND_INVALID;
2985   }
2986 }
2987
2988 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2989 /// code. Current x86 isa includes the following FP cmov instructions:
2990 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2991 static bool hasFPCMov(unsigned X86CC) {
2992   switch (X86CC) {
2993   default:
2994     return false;
2995   case X86::COND_B:
2996   case X86::COND_BE:
2997   case X86::COND_E:
2998   case X86::COND_P:
2999   case X86::COND_A:
3000   case X86::COND_AE:
3001   case X86::COND_NE:
3002   case X86::COND_NP:
3003     return true;
3004   }
3005 }
3006
3007 /// isFPImmLegal - Returns true if the target can instruction select the
3008 /// specified FP immediate natively. If false, the legalizer will
3009 /// materialize the FP immediate as a load from a constant pool.
3010 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3011   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3012     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3013       return true;
3014   }
3015   return false;
3016 }
3017
3018 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3019 /// the specified range (L, H].
3020 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3021   return (Val < 0) || (Val >= Low && Val < Hi);
3022 }
3023
3024 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3025 /// specified value.
3026 static bool isUndefOrEqual(int Val, int CmpVal) {
3027   if (Val < 0 || Val == CmpVal)
3028     return true;
3029   return false;
3030 }
3031
3032 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3033 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3034 /// the second operand.
3035 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3036   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3037     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3038   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3039     return (Mask[0] < 2 && Mask[1] < 2);
3040   return false;
3041 }
3042
3043 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3044   SmallVector<int, 8> M;
3045   N->getMask(M);
3046   return ::isPSHUFDMask(M, N->getValueType(0));
3047 }
3048
3049 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3050 /// is suitable for input to PSHUFHW.
3051 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3052   if (VT != MVT::v8i16)
3053     return false;
3054
3055   // Lower quadword copied in order or undef.
3056   for (int i = 0; i != 4; ++i)
3057     if (Mask[i] >= 0 && Mask[i] != i)
3058       return false;
3059
3060   // Upper quadword shuffled.
3061   for (int i = 4; i != 8; ++i)
3062     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3063       return false;
3064
3065   return true;
3066 }
3067
3068 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3069   SmallVector<int, 8> M;
3070   N->getMask(M);
3071   return ::isPSHUFHWMask(M, N->getValueType(0));
3072 }
3073
3074 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3075 /// is suitable for input to PSHUFLW.
3076 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3077   if (VT != MVT::v8i16)
3078     return false;
3079
3080   // Upper quadword copied in order.
3081   for (int i = 4; i != 8; ++i)
3082     if (Mask[i] >= 0 && Mask[i] != i)
3083       return false;
3084
3085   // Lower quadword shuffled.
3086   for (int i = 0; i != 4; ++i)
3087     if (Mask[i] >= 4)
3088       return false;
3089
3090   return true;
3091 }
3092
3093 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3094   SmallVector<int, 8> M;
3095   N->getMask(M);
3096   return ::isPSHUFLWMask(M, N->getValueType(0));
3097 }
3098
3099 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3100 /// is suitable for input to PALIGNR.
3101 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3102                           bool hasSSSE3) {
3103   int i, e = VT.getVectorNumElements();
3104   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3105     return false;
3106
3107   // Do not handle v2i64 / v2f64 shuffles with palignr.
3108   if (e < 4 || !hasSSSE3)
3109     return false;
3110
3111   for (i = 0; i != e; ++i)
3112     if (Mask[i] >= 0)
3113       break;
3114
3115   // All undef, not a palignr.
3116   if (i == e)
3117     return false;
3118
3119   // Make sure we're shifting in the right direction.
3120   if (Mask[i] <= i)
3121     return false;
3122
3123   int s = Mask[i] - i;
3124
3125   // Check the rest of the elements to see if they are consecutive.
3126   for (++i; i != e; ++i) {
3127     int m = Mask[i];
3128     if (m >= 0 && m != s+i)
3129       return false;
3130   }
3131   return true;
3132 }
3133
3134 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3135 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3136 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3137   int NumElems = VT.getVectorNumElements();
3138   if (NumElems != 2 && NumElems != 4)
3139     return false;
3140
3141   int Half = NumElems / 2;
3142   for (int i = 0; i < Half; ++i)
3143     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3144       return false;
3145   for (int i = Half; i < NumElems; ++i)
3146     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3147       return false;
3148
3149   return true;
3150 }
3151
3152 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3153   SmallVector<int, 8> M;
3154   N->getMask(M);
3155   return ::isSHUFPMask(M, N->getValueType(0));
3156 }
3157
3158 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3159 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3160 /// half elements to come from vector 1 (which would equal the dest.) and
3161 /// the upper half to come from vector 2.
3162 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3163   int NumElems = VT.getVectorNumElements();
3164
3165   if (NumElems != 2 && NumElems != 4)
3166     return false;
3167
3168   int Half = NumElems / 2;
3169   for (int i = 0; i < Half; ++i)
3170     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3171       return false;
3172   for (int i = Half; i < NumElems; ++i)
3173     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3174       return false;
3175   return true;
3176 }
3177
3178 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3179   SmallVector<int, 8> M;
3180   N->getMask(M);
3181   return isCommutedSHUFPMask(M, N->getValueType(0));
3182 }
3183
3184 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3185 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3186 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3187   EVT VT = N->getValueType(0);
3188   unsigned NumElems = VT.getVectorNumElements();
3189
3190   if (VT.getSizeInBits() != 128)
3191     return false;
3192
3193   if (NumElems != 4)
3194     return false;
3195
3196   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3197   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3198          isUndefOrEqual(N->getMaskElt(1), 7) &&
3199          isUndefOrEqual(N->getMaskElt(2), 2) &&
3200          isUndefOrEqual(N->getMaskElt(3), 3);
3201 }
3202
3203 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3204 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3205 /// <2, 3, 2, 3>
3206 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3207   EVT VT = N->getValueType(0);
3208   unsigned NumElems = VT.getVectorNumElements();
3209
3210   if (VT.getSizeInBits() != 128)
3211     return false;
3212
3213   if (NumElems != 4)
3214     return false;
3215
3216   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3217          isUndefOrEqual(N->getMaskElt(1), 3) &&
3218          isUndefOrEqual(N->getMaskElt(2), 2) &&
3219          isUndefOrEqual(N->getMaskElt(3), 3);
3220 }
3221
3222 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3223 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3224 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3225   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3226
3227   if (NumElems != 2 && NumElems != 4)
3228     return false;
3229
3230   for (unsigned i = 0; i < NumElems/2; ++i)
3231     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3232       return false;
3233
3234   for (unsigned i = NumElems/2; i < NumElems; ++i)
3235     if (!isUndefOrEqual(N->getMaskElt(i), i))
3236       return false;
3237
3238   return true;
3239 }
3240
3241 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3242 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3243 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3244   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3245
3246   if ((NumElems != 2 && NumElems != 4)
3247       || N->getValueType(0).getSizeInBits() > 128)
3248     return false;
3249
3250   for (unsigned i = 0; i < NumElems/2; ++i)
3251     if (!isUndefOrEqual(N->getMaskElt(i), i))
3252       return false;
3253
3254   for (unsigned i = 0; i < NumElems/2; ++i)
3255     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3256       return false;
3257
3258   return true;
3259 }
3260
3261 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3262 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3263 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3264                          bool V2IsSplat = false) {
3265   int NumElts = VT.getVectorNumElements();
3266
3267   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3268          "Unsupported vector type for unpckh");
3269
3270   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3271     return false;
3272
3273   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3274   // independently on 128-bit lanes.
3275   unsigned NumLanes = VT.getSizeInBits()/128;
3276   unsigned NumLaneElts = NumElts/NumLanes;
3277
3278   unsigned Start = 0;
3279   unsigned End = NumLaneElts;
3280   for (unsigned s = 0; s < NumLanes; ++s) {
3281     for (unsigned i = Start, j = s * NumLaneElts;
3282          i != End;
3283          i += 2, ++j) {
3284       int BitI  = Mask[i];
3285       int BitI1 = Mask[i+1];
3286       if (!isUndefOrEqual(BitI, j))
3287         return false;
3288       if (V2IsSplat) {
3289         if (!isUndefOrEqual(BitI1, NumElts))
3290           return false;
3291       } else {
3292         if (!isUndefOrEqual(BitI1, j + NumElts))
3293           return false;
3294       }
3295     }
3296     // Process the next 128 bits.
3297     Start += NumLaneElts;
3298     End += NumLaneElts;
3299   }
3300
3301   return true;
3302 }
3303
3304 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3305   SmallVector<int, 8> M;
3306   N->getMask(M);
3307   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3308 }
3309
3310 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3311 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3312 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3313                          bool V2IsSplat = false) {
3314   int NumElts = VT.getVectorNumElements();
3315
3316   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3317          "Unsupported vector type for unpckh");
3318
3319   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3320     return false;
3321
3322   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3323   // independently on 128-bit lanes.
3324   unsigned NumLanes = VT.getSizeInBits()/128;
3325   unsigned NumLaneElts = NumElts/NumLanes;
3326
3327   unsigned Start = 0;
3328   unsigned End = NumLaneElts;
3329   for (unsigned l = 0; l != NumLanes; ++l) {
3330     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3331                              i != End; i += 2, ++j) {
3332       int BitI  = Mask[i];
3333       int BitI1 = Mask[i+1];
3334       if (!isUndefOrEqual(BitI, j))
3335         return false;
3336       if (V2IsSplat) {
3337         if (isUndefOrEqual(BitI1, NumElts))
3338           return false;
3339       } else {
3340         if (!isUndefOrEqual(BitI1, j+NumElts))
3341           return false;
3342       }
3343     }
3344     // Process the next 128 bits.
3345     Start += NumLaneElts;
3346     End += NumLaneElts;
3347   }
3348   return true;
3349 }
3350
3351 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3352   SmallVector<int, 8> M;
3353   N->getMask(M);
3354   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3355 }
3356
3357 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3358 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3359 /// <0, 0, 1, 1>
3360 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3361   int NumElems = VT.getVectorNumElements();
3362   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3363     return false;
3364
3365   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3366   // independently on 128-bit lanes.
3367   unsigned NumLanes = VT.getSizeInBits() / 128;
3368   unsigned NumLaneElts = NumElems / NumLanes;
3369
3370   for (unsigned s = 0; s < NumLanes; ++s) {
3371     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3372          i != NumLaneElts * (s + 1);
3373          i += 2, ++j) {
3374       int BitI  = Mask[i];
3375       int BitI1 = Mask[i+1];
3376
3377       if (!isUndefOrEqual(BitI, j))
3378         return false;
3379       if (!isUndefOrEqual(BitI1, j))
3380         return false;
3381     }
3382   }
3383
3384   return true;
3385 }
3386
3387 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3388   SmallVector<int, 8> M;
3389   N->getMask(M);
3390   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3391 }
3392
3393 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3394 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3395 /// <2, 2, 3, 3>
3396 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3397   int NumElems = VT.getVectorNumElements();
3398   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3399     return false;
3400
3401   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3402     int BitI  = Mask[i];
3403     int BitI1 = Mask[i+1];
3404     if (!isUndefOrEqual(BitI, j))
3405       return false;
3406     if (!isUndefOrEqual(BitI1, j))
3407       return false;
3408   }
3409   return true;
3410 }
3411
3412 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3413   SmallVector<int, 8> M;
3414   N->getMask(M);
3415   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3416 }
3417
3418 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3420 /// MOVSD, and MOVD, i.e. setting the lowest element.
3421 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3422   if (VT.getVectorElementType().getSizeInBits() < 32)
3423     return false;
3424
3425   int NumElts = VT.getVectorNumElements();
3426
3427   if (!isUndefOrEqual(Mask[0], NumElts))
3428     return false;
3429
3430   for (int i = 1; i < NumElts; ++i)
3431     if (!isUndefOrEqual(Mask[i], i))
3432       return false;
3433
3434   return true;
3435 }
3436
3437 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3438   SmallVector<int, 8> M;
3439   N->getMask(M);
3440   return ::isMOVLMask(M, N->getValueType(0));
3441 }
3442
3443 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3444 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3445 /// Note that VPERMIL mask matching is different depending whether theunderlying
3446 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3447 /// to the same elements of the low, but to the higher half of the source.
3448 /// In VPERMILPD the two lanes could be shuffled independently of each other
3449 /// with the same restriction that lanes can't be crossed.
3450 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3451                             const X86Subtarget *Subtarget) {
3452   int NumElts = VT.getVectorNumElements();
3453   int NumLanes = VT.getSizeInBits()/128;
3454
3455   if (!Subtarget->hasAVX())
3456     return false;
3457
3458   // Match any permutation of 128-bit vector with 64-bit types
3459   if (NumLanes == 1 && NumElts != 2)
3460     return false;
3461
3462   // Only match 256-bit with 32 types
3463   if (VT.getSizeInBits() == 256 && NumElts != 4)
3464     return false;
3465
3466   // The mask on the high lane is independent of the low. Both can match
3467   // any element in inside its own lane, but can't cross.
3468   int LaneSize = NumElts/NumLanes;
3469   for (int l = 0; l < NumLanes; ++l)
3470     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3471       int LaneStart = l*LaneSize;
3472       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3473         return false;
3474     }
3475
3476   return true;
3477 }
3478
3479 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3480 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3481 /// Note that VPERMIL mask matching is different depending whether theunderlying
3482 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3483 /// to the same elements of the low, but to the higher half of the source.
3484 /// In VPERMILPD the two lanes could be shuffled independently of each other
3485 /// with the same restriction that lanes can't be crossed.
3486 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3487                             const X86Subtarget *Subtarget) {
3488   unsigned NumElts = VT.getVectorNumElements();
3489   unsigned NumLanes = VT.getSizeInBits()/128;
3490
3491   if (!Subtarget->hasAVX())
3492     return false;
3493
3494   // Match any permutation of 128-bit vector with 32-bit types
3495   if (NumLanes == 1 && NumElts != 4)
3496     return false;
3497
3498   // Only match 256-bit with 32 types
3499   if (VT.getSizeInBits() == 256 && NumElts != 8)
3500     return false;
3501
3502   // The mask on the high lane should be the same as the low. Actually,
3503   // they can differ if any of the corresponding index in a lane is undef
3504   // and the other stays in range.
3505   int LaneSize = NumElts/NumLanes;
3506   for (int i = 0; i < LaneSize; ++i) {
3507     int HighElt = i+LaneSize;
3508     if (Mask[i] < 0 && (isUndefOrInRange(Mask[HighElt], LaneSize, NumElts)))
3509       continue;
3510     if (Mask[HighElt] < 0 && (isUndefOrInRange(Mask[i], 0, LaneSize)))
3511       continue;
3512     if (Mask[HighElt]-Mask[i] != LaneSize)
3513       return false;
3514   }
3515
3516   return true;
3517 }
3518
3519 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3520 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3521 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3522   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3523   EVT VT = SVOp->getValueType(0);
3524
3525   int NumElts = VT.getVectorNumElements();
3526   int NumLanes = VT.getSizeInBits()/128;
3527   int LaneSize = NumElts/NumLanes;
3528
3529   // Although the mask is equal for both lanes do it twice to get the cases
3530   // where a mask will match because the same mask element is undef on the
3531   // first half but valid on the second. This would get pathological cases
3532   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3533   unsigned Mask = 0;
3534   for (int l = 0; l < NumLanes; ++l) {
3535     for (int i = 0; i < LaneSize; ++i) {
3536       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3537       if (MaskElt < 0)
3538         continue;
3539       if (MaskElt >= LaneSize)
3540         MaskElt -= LaneSize;
3541       Mask |= MaskElt << (i*2);
3542     }
3543   }
3544
3545   return Mask;
3546 }
3547
3548 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3549 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3550 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3551   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3552   EVT VT = SVOp->getValueType(0);
3553
3554   int NumElts = VT.getVectorNumElements();
3555   int NumLanes = VT.getSizeInBits()/128;
3556
3557   unsigned Mask = 0;
3558   int LaneSize = NumElts/NumLanes;
3559   for (int l = 0; l < NumLanes; ++l)
3560     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3561       int MaskElt = SVOp->getMaskElt(i);
3562       if (MaskElt < 0)
3563         continue;
3564       Mask |= (MaskElt-l*LaneSize) << i;
3565     }
3566
3567   return Mask;
3568 }
3569
3570 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3571 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3572 /// element of vector 2 and the other elements to come from vector 1 in order.
3573 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3574                                bool V2IsSplat = false, bool V2IsUndef = false) {
3575   int NumOps = VT.getVectorNumElements();
3576   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3577     return false;
3578
3579   if (!isUndefOrEqual(Mask[0], 0))
3580     return false;
3581
3582   for (int i = 1; i < NumOps; ++i)
3583     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3584           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3585           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3586       return false;
3587
3588   return true;
3589 }
3590
3591 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3592                            bool V2IsUndef = false) {
3593   SmallVector<int, 8> M;
3594   N->getMask(M);
3595   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3596 }
3597
3598 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3599 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3600 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3601 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3602                          const X86Subtarget *Subtarget) {
3603   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3604     return false;
3605
3606   // The second vector must be undef
3607   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3608     return false;
3609
3610   EVT VT = N->getValueType(0);
3611   unsigned NumElems = VT.getVectorNumElements();
3612
3613   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3614       (VT.getSizeInBits() == 256 && NumElems != 8))
3615     return false;
3616
3617   // "i+1" is the value the indexed mask element must have
3618   for (unsigned i = 0; i < NumElems; i += 2)
3619     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3620         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3621       return false;
3622
3623   return true;
3624 }
3625
3626 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3627 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3628 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3629 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3630                          const X86Subtarget *Subtarget) {
3631   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3632     return false;
3633
3634   // The second vector must be undef
3635   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3636     return false;
3637
3638   EVT VT = N->getValueType(0);
3639   unsigned NumElems = VT.getVectorNumElements();
3640
3641   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3642       (VT.getSizeInBits() == 256 && NumElems != 8))
3643     return false;
3644
3645   // "i" is the value the indexed mask element must have
3646   for (unsigned i = 0; i < NumElems; i += 2)
3647     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3648         !isUndefOrEqual(N->getMaskElt(i+1), i))
3649       return false;
3650
3651   return true;
3652 }
3653
3654 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3655 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3656 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3657   int e = N->getValueType(0).getVectorNumElements() / 2;
3658
3659   for (int i = 0; i < e; ++i)
3660     if (!isUndefOrEqual(N->getMaskElt(i), i))
3661       return false;
3662   for (int i = 0; i < e; ++i)
3663     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3664       return false;
3665   return true;
3666 }
3667
3668 /// isVEXTRACTF128Index - Return true if the specified
3669 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3670 /// suitable for input to VEXTRACTF128.
3671 bool X86::isVEXTRACTF128Index(SDNode *N) {
3672   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3673     return false;
3674
3675   // The index should be aligned on a 128-bit boundary.
3676   uint64_t Index =
3677     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3678
3679   unsigned VL = N->getValueType(0).getVectorNumElements();
3680   unsigned VBits = N->getValueType(0).getSizeInBits();
3681   unsigned ElSize = VBits / VL;
3682   bool Result = (Index * ElSize) % 128 == 0;
3683
3684   return Result;
3685 }
3686
3687 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3688 /// operand specifies a subvector insert that is suitable for input to
3689 /// VINSERTF128.
3690 bool X86::isVINSERTF128Index(SDNode *N) {
3691   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3692     return false;
3693
3694   // The index should be aligned on a 128-bit boundary.
3695   uint64_t Index =
3696     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3697
3698   unsigned VL = N->getValueType(0).getVectorNumElements();
3699   unsigned VBits = N->getValueType(0).getSizeInBits();
3700   unsigned ElSize = VBits / VL;
3701   bool Result = (Index * ElSize) % 128 == 0;
3702
3703   return Result;
3704 }
3705
3706 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3707 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3708 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3709   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3710   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3711
3712   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3713   unsigned Mask = 0;
3714   for (int i = 0; i < NumOperands; ++i) {
3715     int Val = SVOp->getMaskElt(NumOperands-i-1);
3716     if (Val < 0) Val = 0;
3717     if (Val >= NumOperands) Val -= NumOperands;
3718     Mask |= Val;
3719     if (i != NumOperands - 1)
3720       Mask <<= Shift;
3721   }
3722   return Mask;
3723 }
3724
3725 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3726 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3727 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3728   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3729   unsigned Mask = 0;
3730   // 8 nodes, but we only care about the last 4.
3731   for (unsigned i = 7; i >= 4; --i) {
3732     int Val = SVOp->getMaskElt(i);
3733     if (Val >= 0)
3734       Mask |= (Val - 4);
3735     if (i != 4)
3736       Mask <<= 2;
3737   }
3738   return Mask;
3739 }
3740
3741 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3742 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3743 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3744   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3745   unsigned Mask = 0;
3746   // 8 nodes, but we only care about the first 4.
3747   for (int i = 3; i >= 0; --i) {
3748     int Val = SVOp->getMaskElt(i);
3749     if (Val >= 0)
3750       Mask |= Val;
3751     if (i != 0)
3752       Mask <<= 2;
3753   }
3754   return Mask;
3755 }
3756
3757 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3758 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3759 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3760   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3761   EVT VVT = N->getValueType(0);
3762   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3763   int Val = 0;
3764
3765   unsigned i, e;
3766   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3767     Val = SVOp->getMaskElt(i);
3768     if (Val >= 0)
3769       break;
3770   }
3771   assert(Val - i > 0 && "PALIGNR imm should be positive");
3772   return (Val - i) * EltSize;
3773 }
3774
3775 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3776 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3777 /// instructions.
3778 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3779   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3780     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3781
3782   uint64_t Index =
3783     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3784
3785   EVT VecVT = N->getOperand(0).getValueType();
3786   EVT ElVT = VecVT.getVectorElementType();
3787
3788   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3789   return Index / NumElemsPerChunk;
3790 }
3791
3792 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3793 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3794 /// instructions.
3795 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3796   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3797     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3798
3799   uint64_t Index =
3800     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3801
3802   EVT VecVT = N->getValueType(0);
3803   EVT ElVT = VecVT.getVectorElementType();
3804
3805   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3806   return Index / NumElemsPerChunk;
3807 }
3808
3809 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3810 /// constant +0.0.
3811 bool X86::isZeroNode(SDValue Elt) {
3812   return ((isa<ConstantSDNode>(Elt) &&
3813            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3814           (isa<ConstantFPSDNode>(Elt) &&
3815            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3816 }
3817
3818 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3819 /// their permute mask.
3820 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3821                                     SelectionDAG &DAG) {
3822   EVT VT = SVOp->getValueType(0);
3823   unsigned NumElems = VT.getVectorNumElements();
3824   SmallVector<int, 8> MaskVec;
3825
3826   for (unsigned i = 0; i != NumElems; ++i) {
3827     int idx = SVOp->getMaskElt(i);
3828     if (idx < 0)
3829       MaskVec.push_back(idx);
3830     else if (idx < (int)NumElems)
3831       MaskVec.push_back(idx + NumElems);
3832     else
3833       MaskVec.push_back(idx - NumElems);
3834   }
3835   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3836                               SVOp->getOperand(0), &MaskVec[0]);
3837 }
3838
3839 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3840 /// the two vector operands have swapped position.
3841 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3842   unsigned NumElems = VT.getVectorNumElements();
3843   for (unsigned i = 0; i != NumElems; ++i) {
3844     int idx = Mask[i];
3845     if (idx < 0)
3846       continue;
3847     else if (idx < (int)NumElems)
3848       Mask[i] = idx + NumElems;
3849     else
3850       Mask[i] = idx - NumElems;
3851   }
3852 }
3853
3854 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3855 /// match movhlps. The lower half elements should come from upper half of
3856 /// V1 (and in order), and the upper half elements should come from the upper
3857 /// half of V2 (and in order).
3858 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3859   if (Op->getValueType(0).getVectorNumElements() != 4)
3860     return false;
3861   for (unsigned i = 0, e = 2; i != e; ++i)
3862     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3863       return false;
3864   for (unsigned i = 2; i != 4; ++i)
3865     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3866       return false;
3867   return true;
3868 }
3869
3870 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3871 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3872 /// required.
3873 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3874   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3875     return false;
3876   N = N->getOperand(0).getNode();
3877   if (!ISD::isNON_EXTLoad(N))
3878     return false;
3879   if (LD)
3880     *LD = cast<LoadSDNode>(N);
3881   return true;
3882 }
3883
3884 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3885 /// match movlp{s|d}. The lower half elements should come from lower half of
3886 /// V1 (and in order), and the upper half elements should come from the upper
3887 /// half of V2 (and in order). And since V1 will become the source of the
3888 /// MOVLP, it must be either a vector load or a scalar load to vector.
3889 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3890                                ShuffleVectorSDNode *Op) {
3891   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3892     return false;
3893   // Is V2 is a vector load, don't do this transformation. We will try to use
3894   // load folding shufps op.
3895   if (ISD::isNON_EXTLoad(V2))
3896     return false;
3897
3898   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3899
3900   if (NumElems != 2 && NumElems != 4)
3901     return false;
3902   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3903     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3904       return false;
3905   for (unsigned i = NumElems/2; i != NumElems; ++i)
3906     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3907       return false;
3908   return true;
3909 }
3910
3911 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3912 /// all the same.
3913 static bool isSplatVector(SDNode *N) {
3914   if (N->getOpcode() != ISD::BUILD_VECTOR)
3915     return false;
3916
3917   SDValue SplatValue = N->getOperand(0);
3918   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3919     if (N->getOperand(i) != SplatValue)
3920       return false;
3921   return true;
3922 }
3923
3924 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3925 /// to an zero vector.
3926 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3927 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3928   SDValue V1 = N->getOperand(0);
3929   SDValue V2 = N->getOperand(1);
3930   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3931   for (unsigned i = 0; i != NumElems; ++i) {
3932     int Idx = N->getMaskElt(i);
3933     if (Idx >= (int)NumElems) {
3934       unsigned Opc = V2.getOpcode();
3935       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3936         continue;
3937       if (Opc != ISD::BUILD_VECTOR ||
3938           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3939         return false;
3940     } else if (Idx >= 0) {
3941       unsigned Opc = V1.getOpcode();
3942       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3943         continue;
3944       if (Opc != ISD::BUILD_VECTOR ||
3945           !X86::isZeroNode(V1.getOperand(Idx)))
3946         return false;
3947     }
3948   }
3949   return true;
3950 }
3951
3952 /// getZeroVector - Returns a vector of specified type with all zero elements.
3953 ///
3954 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3955                              DebugLoc dl) {
3956   assert(VT.isVector() && "Expected a vector type");
3957
3958   // Always build SSE zero vectors as <4 x i32> bitcasted
3959   // to their dest type. This ensures they get CSE'd.
3960   SDValue Vec;
3961   if (VT.getSizeInBits() == 128) {  // SSE
3962     if (HasSSE2) {  // SSE2
3963       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3964       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3965     } else { // SSE1
3966       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3967       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3968     }
3969   } else if (VT.getSizeInBits() == 256) { // AVX
3970     // 256-bit logic and arithmetic instructions in AVX are
3971     // all floating-point, no support for integer ops. Default
3972     // to emitting fp zeroed vectors then.
3973     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3974     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3975     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3976   }
3977   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3978 }
3979
3980 /// getOnesVector - Returns a vector of specified type with all bits set.
3981 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
3982 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
3983 /// original type, ensuring they get CSE'd.
3984 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3985   assert(VT.isVector() && "Expected a vector type");
3986   assert((VT.is128BitVector() || VT.is256BitVector())
3987          && "Expected a 128-bit or 256-bit vector type");
3988
3989   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3990   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3991                             Cst, Cst, Cst, Cst);
3992
3993   if (VT.is256BitVector()) {
3994     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
3995                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
3996     Vec = Insert128BitVector(InsV, Vec,
3997                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
3998   }
3999
4000   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4001 }
4002
4003 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4004 /// that point to V2 points to its first element.
4005 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4006   EVT VT = SVOp->getValueType(0);
4007   unsigned NumElems = VT.getVectorNumElements();
4008
4009   bool Changed = false;
4010   SmallVector<int, 8> MaskVec;
4011   SVOp->getMask(MaskVec);
4012
4013   for (unsigned i = 0; i != NumElems; ++i) {
4014     if (MaskVec[i] > (int)NumElems) {
4015       MaskVec[i] = NumElems;
4016       Changed = true;
4017     }
4018   }
4019   if (Changed)
4020     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4021                                 SVOp->getOperand(1), &MaskVec[0]);
4022   return SDValue(SVOp, 0);
4023 }
4024
4025 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4026 /// operation of specified width.
4027 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4028                        SDValue V2) {
4029   unsigned NumElems = VT.getVectorNumElements();
4030   SmallVector<int, 8> Mask;
4031   Mask.push_back(NumElems);
4032   for (unsigned i = 1; i != NumElems; ++i)
4033     Mask.push_back(i);
4034   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4035 }
4036
4037 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4038 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4039                           SDValue V2) {
4040   unsigned NumElems = VT.getVectorNumElements();
4041   SmallVector<int, 8> Mask;
4042   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4043     Mask.push_back(i);
4044     Mask.push_back(i + NumElems);
4045   }
4046   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4047 }
4048
4049 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4050 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4051                           SDValue V2) {
4052   unsigned NumElems = VT.getVectorNumElements();
4053   unsigned Half = NumElems/2;
4054   SmallVector<int, 8> Mask;
4055   for (unsigned i = 0; i != Half; ++i) {
4056     Mask.push_back(i + Half);
4057     Mask.push_back(i + NumElems + Half);
4058   }
4059   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4060 }
4061
4062 // PromoteSplatv8v16 - All i16 and i8 vector types can't be used directly by
4063 // a generic shuffle instruction because the target has no such instructions.
4064 // Generate shuffles which repeat i16 and i8 several times until they can be
4065 // represented by v4f32 and then be manipulated by target suported shuffles.
4066 static SDValue PromoteSplatv8v16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4067   EVT VT = V.getValueType();
4068   int NumElems = VT.getVectorNumElements();
4069   DebugLoc dl = V.getDebugLoc();
4070
4071   while (NumElems > 4) {
4072     if (EltNo < NumElems/2) {
4073       V = getUnpackl(DAG, dl, VT, V, V);
4074     } else {
4075       V = getUnpackh(DAG, dl, VT, V, V);
4076       EltNo -= NumElems/2;
4077     }
4078     NumElems >>= 1;
4079   }
4080   return V;
4081 }
4082
4083 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4084 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4085   EVT VT = V.getValueType();
4086   DebugLoc dl = V.getDebugLoc();
4087   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4088          && "Vector size not supported");
4089
4090   bool Is128 = VT.getSizeInBits() == 128;
4091   EVT NVT = Is128 ? MVT::v4f32 : MVT::v8f32;
4092   V = DAG.getNode(ISD::BITCAST, dl, NVT, V);
4093
4094   if (Is128) {
4095     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4096     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
4097   } else {
4098     // The second half of indicies refer to the higher part, which is a
4099     // duplication of the lower one. This makes this shuffle a perfect match
4100     // for the VPERM instruction.
4101     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4102                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4103     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
4104   }
4105
4106   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4107 }
4108
4109 /// PromoteVectorToScalarSplat - Since there's no native support for
4110 /// scalar_to_vector for 256-bit AVX, a 128-bit scalar_to_vector +
4111 /// INSERT_SUBVECTOR is generated. Recognize this idiom and do the
4112 /// shuffle before the insertion, this yields less instructions in the end.
4113 static SDValue PromoteVectorToScalarSplat(ShuffleVectorSDNode *SV,
4114                                           SelectionDAG &DAG) {
4115   EVT SrcVT = SV->getValueType(0);
4116   SDValue V1 = SV->getOperand(0);
4117   DebugLoc dl = SV->getDebugLoc();
4118   int NumElems = SrcVT.getVectorNumElements();
4119
4120   assert(SrcVT.is256BitVector() && "unknown howto handle vector type");
4121
4122   SmallVector<int, 4> Mask;
4123   for (int i = 0; i < NumElems/2; ++i)
4124     Mask.push_back(SV->getMaskElt(i));
4125
4126   EVT SVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
4127                              NumElems/2);
4128   SDValue SV1 = DAG.getVectorShuffle(SVT, dl, V1.getOperand(1),
4129                                      DAG.getUNDEF(SVT), &Mask[0]);
4130   SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), SV1,
4131                                     DAG.getConstant(0, MVT::i32), DAG, dl);
4132
4133   return Insert128BitVector(InsV, SV1,
4134                        DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4135 }
4136
4137 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32 and
4138 /// v8i32, v16i16 or v32i8 to v8f32.
4139 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4140   EVT SrcVT = SV->getValueType(0);
4141   SDValue V1 = SV->getOperand(0);
4142   DebugLoc dl = SV->getDebugLoc();
4143
4144   int EltNo = SV->getSplatIndex();
4145   int NumElems = SrcVT.getVectorNumElements();
4146   unsigned Size = SrcVT.getSizeInBits();
4147
4148   // Extract the 128-bit part containing the splat element and update
4149   // the splat element index when it refers to the higher register.
4150   if (Size == 256) {
4151     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4152     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4153     if (Idx > 0)
4154       EltNo -= NumElems/2;
4155   }
4156
4157   // Make this 128-bit vector duplicate i8 and i16 elements
4158   if (NumElems > 4)
4159     V1 = PromoteSplatv8v16(V1, DAG, EltNo);
4160
4161   // Recreate the 256-bit vector and place the same 128-bit vector
4162   // into the low and high part. This is necessary because we want
4163   // to use VPERM to shuffle the v8f32 vector, and VPERM only shuffles
4164   // inside each separate v4f32 lane.
4165   if (Size == 256) {
4166     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4167                          DAG.getConstant(0, MVT::i32), DAG, dl);
4168     V1 = Insert128BitVector(InsV, V1,
4169                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4170   }
4171
4172   return getLegalSplat(DAG, V1, EltNo);
4173 }
4174
4175 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4176 /// vector of zero or undef vector.  This produces a shuffle where the low
4177 /// element of V2 is swizzled into the zero/undef vector, landing at element
4178 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4179 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4180                                              bool isZero, bool HasSSE2,
4181                                              SelectionDAG &DAG) {
4182   EVT VT = V2.getValueType();
4183   SDValue V1 = isZero
4184     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4185   unsigned NumElems = VT.getVectorNumElements();
4186   SmallVector<int, 16> MaskVec;
4187   for (unsigned i = 0; i != NumElems; ++i)
4188     // If this is the insertion idx, put the low elt of V2 here.
4189     MaskVec.push_back(i == Idx ? NumElems : i);
4190   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4191 }
4192
4193 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4194 /// element of the result of the vector shuffle.
4195 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4196                                    unsigned Depth) {
4197   if (Depth == 6)
4198     return SDValue();  // Limit search depth.
4199
4200   SDValue V = SDValue(N, 0);
4201   EVT VT = V.getValueType();
4202   unsigned Opcode = V.getOpcode();
4203
4204   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4205   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4206     Index = SV->getMaskElt(Index);
4207
4208     if (Index < 0)
4209       return DAG.getUNDEF(VT.getVectorElementType());
4210
4211     int NumElems = VT.getVectorNumElements();
4212     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4213     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4214   }
4215
4216   // Recurse into target specific vector shuffles to find scalars.
4217   if (isTargetShuffle(Opcode)) {
4218     int NumElems = VT.getVectorNumElements();
4219     SmallVector<unsigned, 16> ShuffleMask;
4220     SDValue ImmN;
4221
4222     switch(Opcode) {
4223     case X86ISD::SHUFPS:
4224     case X86ISD::SHUFPD:
4225       ImmN = N->getOperand(N->getNumOperands()-1);
4226       DecodeSHUFPSMask(NumElems,
4227                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4228                        ShuffleMask);
4229       break;
4230     case X86ISD::PUNPCKHBW:
4231     case X86ISD::PUNPCKHWD:
4232     case X86ISD::PUNPCKHDQ:
4233     case X86ISD::PUNPCKHQDQ:
4234       DecodePUNPCKHMask(NumElems, ShuffleMask);
4235       break;
4236     case X86ISD::UNPCKHPS:
4237     case X86ISD::UNPCKHPD:
4238     case X86ISD::VUNPCKHPSY:
4239     case X86ISD::VUNPCKHPDY:
4240       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4241       break;
4242     case X86ISD::PUNPCKLBW:
4243     case X86ISD::PUNPCKLWD:
4244     case X86ISD::PUNPCKLDQ:
4245     case X86ISD::PUNPCKLQDQ:
4246       DecodePUNPCKLMask(VT, ShuffleMask);
4247       break;
4248     case X86ISD::UNPCKLPS:
4249     case X86ISD::UNPCKLPD:
4250     case X86ISD::VUNPCKLPSY:
4251     case X86ISD::VUNPCKLPDY:
4252       DecodeUNPCKLPMask(VT, ShuffleMask);
4253       break;
4254     case X86ISD::MOVHLPS:
4255       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4256       break;
4257     case X86ISD::MOVLHPS:
4258       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4259       break;
4260     case X86ISD::PSHUFD:
4261       ImmN = N->getOperand(N->getNumOperands()-1);
4262       DecodePSHUFMask(NumElems,
4263                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4264                       ShuffleMask);
4265       break;
4266     case X86ISD::PSHUFHW:
4267       ImmN = N->getOperand(N->getNumOperands()-1);
4268       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4269                         ShuffleMask);
4270       break;
4271     case X86ISD::PSHUFLW:
4272       ImmN = N->getOperand(N->getNumOperands()-1);
4273       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4274                         ShuffleMask);
4275       break;
4276     case X86ISD::MOVSS:
4277     case X86ISD::MOVSD: {
4278       // The index 0 always comes from the first element of the second source,
4279       // this is why MOVSS and MOVSD are used in the first place. The other
4280       // elements come from the other positions of the first source vector.
4281       unsigned OpNum = (Index == 0) ? 1 : 0;
4282       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4283                                  Depth+1);
4284     }
4285     case X86ISD::VPERMILPS:
4286       ImmN = N->getOperand(N->getNumOperands()-1);
4287       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4288                         ShuffleMask);
4289       break;
4290     case X86ISD::VPERMILPSY:
4291       ImmN = N->getOperand(N->getNumOperands()-1);
4292       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4293                         ShuffleMask);
4294       break;
4295     case X86ISD::VPERMILPD:
4296       ImmN = N->getOperand(N->getNumOperands()-1);
4297       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4298                         ShuffleMask);
4299       break;
4300     case X86ISD::VPERMILPDY:
4301       ImmN = N->getOperand(N->getNumOperands()-1);
4302       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4303                         ShuffleMask);
4304       break;
4305     default:
4306       assert("not implemented for target shuffle node");
4307       return SDValue();
4308     }
4309
4310     Index = ShuffleMask[Index];
4311     if (Index < 0)
4312       return DAG.getUNDEF(VT.getVectorElementType());
4313
4314     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4315     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4316                                Depth+1);
4317   }
4318
4319   // Actual nodes that may contain scalar elements
4320   if (Opcode == ISD::BITCAST) {
4321     V = V.getOperand(0);
4322     EVT SrcVT = V.getValueType();
4323     unsigned NumElems = VT.getVectorNumElements();
4324
4325     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4326       return SDValue();
4327   }
4328
4329   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4330     return (Index == 0) ? V.getOperand(0)
4331                           : DAG.getUNDEF(VT.getVectorElementType());
4332
4333   if (V.getOpcode() == ISD::BUILD_VECTOR)
4334     return V.getOperand(Index);
4335
4336   return SDValue();
4337 }
4338
4339 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4340 /// shuffle operation which come from a consecutively from a zero. The
4341 /// search can start in two different directions, from left or right.
4342 static
4343 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4344                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4345   int i = 0;
4346
4347   while (i < NumElems) {
4348     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4349     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4350     if (!(Elt.getNode() &&
4351          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4352       break;
4353     ++i;
4354   }
4355
4356   return i;
4357 }
4358
4359 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4360 /// MaskE correspond consecutively to elements from one of the vector operands,
4361 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4362 static
4363 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4364                               int OpIdx, int NumElems, unsigned &OpNum) {
4365   bool SeenV1 = false;
4366   bool SeenV2 = false;
4367
4368   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4369     int Idx = SVOp->getMaskElt(i);
4370     // Ignore undef indicies
4371     if (Idx < 0)
4372       continue;
4373
4374     if (Idx < NumElems)
4375       SeenV1 = true;
4376     else
4377       SeenV2 = true;
4378
4379     // Only accept consecutive elements from the same vector
4380     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4381       return false;
4382   }
4383
4384   OpNum = SeenV1 ? 0 : 1;
4385   return true;
4386 }
4387
4388 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4389 /// logical left shift of a vector.
4390 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4391                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4392   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4393   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4394               false /* check zeros from right */, DAG);
4395   unsigned OpSrc;
4396
4397   if (!NumZeros)
4398     return false;
4399
4400   // Considering the elements in the mask that are not consecutive zeros,
4401   // check if they consecutively come from only one of the source vectors.
4402   //
4403   //               V1 = {X, A, B, C}     0
4404   //                         \  \  \    /
4405   //   vector_shuffle V1, V2 <1, 2, 3, X>
4406   //
4407   if (!isShuffleMaskConsecutive(SVOp,
4408             0,                   // Mask Start Index
4409             NumElems-NumZeros-1, // Mask End Index
4410             NumZeros,            // Where to start looking in the src vector
4411             NumElems,            // Number of elements in vector
4412             OpSrc))              // Which source operand ?
4413     return false;
4414
4415   isLeft = false;
4416   ShAmt = NumZeros;
4417   ShVal = SVOp->getOperand(OpSrc);
4418   return true;
4419 }
4420
4421 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4422 /// logical left shift of a vector.
4423 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4424                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4425   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4426   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4427               true /* check zeros from left */, DAG);
4428   unsigned OpSrc;
4429
4430   if (!NumZeros)
4431     return false;
4432
4433   // Considering the elements in the mask that are not consecutive zeros,
4434   // check if they consecutively come from only one of the source vectors.
4435   //
4436   //                           0    { A, B, X, X } = V2
4437   //                          / \    /  /
4438   //   vector_shuffle V1, V2 <X, X, 4, 5>
4439   //
4440   if (!isShuffleMaskConsecutive(SVOp,
4441             NumZeros,     // Mask Start Index
4442             NumElems-1,   // Mask End Index
4443             0,            // Where to start looking in the src vector
4444             NumElems,     // Number of elements in vector
4445             OpSrc))       // Which source operand ?
4446     return false;
4447
4448   isLeft = true;
4449   ShAmt = NumZeros;
4450   ShVal = SVOp->getOperand(OpSrc);
4451   return true;
4452 }
4453
4454 /// isVectorShift - Returns true if the shuffle can be implemented as a
4455 /// logical left or right shift of a vector.
4456 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4457                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4458   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4459       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4460     return true;
4461
4462   return false;
4463 }
4464
4465 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4466 ///
4467 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4468                                        unsigned NumNonZero, unsigned NumZero,
4469                                        SelectionDAG &DAG,
4470                                        const TargetLowering &TLI) {
4471   if (NumNonZero > 8)
4472     return SDValue();
4473
4474   DebugLoc dl = Op.getDebugLoc();
4475   SDValue V(0, 0);
4476   bool First = true;
4477   for (unsigned i = 0; i < 16; ++i) {
4478     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4479     if (ThisIsNonZero && First) {
4480       if (NumZero)
4481         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4482       else
4483         V = DAG.getUNDEF(MVT::v8i16);
4484       First = false;
4485     }
4486
4487     if ((i & 1) != 0) {
4488       SDValue ThisElt(0, 0), LastElt(0, 0);
4489       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4490       if (LastIsNonZero) {
4491         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4492                               MVT::i16, Op.getOperand(i-1));
4493       }
4494       if (ThisIsNonZero) {
4495         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4496         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4497                               ThisElt, DAG.getConstant(8, MVT::i8));
4498         if (LastIsNonZero)
4499           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4500       } else
4501         ThisElt = LastElt;
4502
4503       if (ThisElt.getNode())
4504         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4505                         DAG.getIntPtrConstant(i/2));
4506     }
4507   }
4508
4509   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4510 }
4511
4512 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4513 ///
4514 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4515                                      unsigned NumNonZero, unsigned NumZero,
4516                                      SelectionDAG &DAG,
4517                                      const TargetLowering &TLI) {
4518   if (NumNonZero > 4)
4519     return SDValue();
4520
4521   DebugLoc dl = Op.getDebugLoc();
4522   SDValue V(0, 0);
4523   bool First = true;
4524   for (unsigned i = 0; i < 8; ++i) {
4525     bool isNonZero = (NonZeros & (1 << i)) != 0;
4526     if (isNonZero) {
4527       if (First) {
4528         if (NumZero)
4529           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4530         else
4531           V = DAG.getUNDEF(MVT::v8i16);
4532         First = false;
4533       }
4534       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4535                       MVT::v8i16, V, Op.getOperand(i),
4536                       DAG.getIntPtrConstant(i));
4537     }
4538   }
4539
4540   return V;
4541 }
4542
4543 /// getVShift - Return a vector logical shift node.
4544 ///
4545 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4546                          unsigned NumBits, SelectionDAG &DAG,
4547                          const TargetLowering &TLI, DebugLoc dl) {
4548   EVT ShVT = MVT::v2i64;
4549   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4550   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4551   return DAG.getNode(ISD::BITCAST, dl, VT,
4552                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4553                              DAG.getConstant(NumBits,
4554                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4555 }
4556
4557 SDValue
4558 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4559                                           SelectionDAG &DAG) const {
4560
4561   // Check if the scalar load can be widened into a vector load. And if
4562   // the address is "base + cst" see if the cst can be "absorbed" into
4563   // the shuffle mask.
4564   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4565     SDValue Ptr = LD->getBasePtr();
4566     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4567       return SDValue();
4568     EVT PVT = LD->getValueType(0);
4569     if (PVT != MVT::i32 && PVT != MVT::f32)
4570       return SDValue();
4571
4572     int FI = -1;
4573     int64_t Offset = 0;
4574     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4575       FI = FINode->getIndex();
4576       Offset = 0;
4577     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4578                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4579       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4580       Offset = Ptr.getConstantOperandVal(1);
4581       Ptr = Ptr.getOperand(0);
4582     } else {
4583       return SDValue();
4584     }
4585
4586     // FIXME: 256-bit vector instructions don't require a strict alignment,
4587     // improve this code to support it better.
4588     unsigned RequiredAlign = VT.getSizeInBits()/8;
4589     SDValue Chain = LD->getChain();
4590     // Make sure the stack object alignment is at least 16 or 32.
4591     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4592     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4593       if (MFI->isFixedObjectIndex(FI)) {
4594         // Can't change the alignment. FIXME: It's possible to compute
4595         // the exact stack offset and reference FI + adjust offset instead.
4596         // If someone *really* cares about this. That's the way to implement it.
4597         return SDValue();
4598       } else {
4599         MFI->setObjectAlignment(FI, RequiredAlign);
4600       }
4601     }
4602
4603     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4604     // Ptr + (Offset & ~15).
4605     if (Offset < 0)
4606       return SDValue();
4607     if ((Offset % RequiredAlign) & 3)
4608       return SDValue();
4609     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4610     if (StartOffset)
4611       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4612                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4613
4614     int EltNo = (Offset - StartOffset) >> 2;
4615     int NumElems = VT.getVectorNumElements();
4616
4617     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4618     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4619     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4620                              LD->getPointerInfo().getWithOffset(StartOffset),
4621                              false, false, 0);
4622
4623     // Canonicalize it to a v4i32 or v8i32 shuffle.
4624     SmallVector<int, 8> Mask;
4625     for (int i = 0; i < NumElems; ++i)
4626       Mask.push_back(EltNo);
4627
4628     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4629     return DAG.getNode(ISD::BITCAST, dl, NVT,
4630                        DAG.getVectorShuffle(CanonVT, dl, V1,
4631                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4632   }
4633
4634   return SDValue();
4635 }
4636
4637 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4638 /// vector of type 'VT', see if the elements can be replaced by a single large
4639 /// load which has the same value as a build_vector whose operands are 'elts'.
4640 ///
4641 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4642 ///
4643 /// FIXME: we'd also like to handle the case where the last elements are zero
4644 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4645 /// There's even a handy isZeroNode for that purpose.
4646 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4647                                         DebugLoc &DL, SelectionDAG &DAG) {
4648   EVT EltVT = VT.getVectorElementType();
4649   unsigned NumElems = Elts.size();
4650
4651   LoadSDNode *LDBase = NULL;
4652   unsigned LastLoadedElt = -1U;
4653
4654   // For each element in the initializer, see if we've found a load or an undef.
4655   // If we don't find an initial load element, or later load elements are
4656   // non-consecutive, bail out.
4657   for (unsigned i = 0; i < NumElems; ++i) {
4658     SDValue Elt = Elts[i];
4659
4660     if (!Elt.getNode() ||
4661         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4662       return SDValue();
4663     if (!LDBase) {
4664       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4665         return SDValue();
4666       LDBase = cast<LoadSDNode>(Elt.getNode());
4667       LastLoadedElt = i;
4668       continue;
4669     }
4670     if (Elt.getOpcode() == ISD::UNDEF)
4671       continue;
4672
4673     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4674     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4675       return SDValue();
4676     LastLoadedElt = i;
4677   }
4678
4679   // If we have found an entire vector of loads and undefs, then return a large
4680   // load of the entire vector width starting at the base pointer.  If we found
4681   // consecutive loads for the low half, generate a vzext_load node.
4682   if (LastLoadedElt == NumElems - 1) {
4683     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4684       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4685                          LDBase->getPointerInfo(),
4686                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4687     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4688                        LDBase->getPointerInfo(),
4689                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4690                        LDBase->getAlignment());
4691   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4692              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4693     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4694     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4695     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4696                                               Ops, 2, MVT::i32,
4697                                               LDBase->getMemOperand());
4698     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4699   }
4700   return SDValue();
4701 }
4702
4703 SDValue
4704 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4705   DebugLoc dl = Op.getDebugLoc();
4706
4707   EVT VT = Op.getValueType();
4708   EVT ExtVT = VT.getVectorElementType();
4709   unsigned NumElems = Op.getNumOperands();
4710
4711   // Vectors containing all zeros can be matched by pxor and xorps later
4712   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
4713     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
4714     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
4715     if (Op.getValueType() == MVT::v4i32 ||
4716         Op.getValueType() == MVT::v8i32)
4717       return Op;
4718
4719     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4720   }
4721
4722   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
4723   // vectors or broken into v4i32 operations on 256-bit vectors.
4724   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
4725     if (Op.getValueType() == MVT::v4i32)
4726       return Op;
4727
4728     return getOnesVector(Op.getValueType(), DAG, dl);
4729   }
4730
4731   unsigned EVTBits = ExtVT.getSizeInBits();
4732
4733   unsigned NumZero  = 0;
4734   unsigned NumNonZero = 0;
4735   unsigned NonZeros = 0;
4736   bool IsAllConstants = true;
4737   SmallSet<SDValue, 8> Values;
4738   for (unsigned i = 0; i < NumElems; ++i) {
4739     SDValue Elt = Op.getOperand(i);
4740     if (Elt.getOpcode() == ISD::UNDEF)
4741       continue;
4742     Values.insert(Elt);
4743     if (Elt.getOpcode() != ISD::Constant &&
4744         Elt.getOpcode() != ISD::ConstantFP)
4745       IsAllConstants = false;
4746     if (X86::isZeroNode(Elt))
4747       NumZero++;
4748     else {
4749       NonZeros |= (1 << i);
4750       NumNonZero++;
4751     }
4752   }
4753
4754   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4755   if (NumNonZero == 0)
4756     return DAG.getUNDEF(VT);
4757
4758   // Special case for single non-zero, non-undef, element.
4759   if (NumNonZero == 1) {
4760     unsigned Idx = CountTrailingZeros_32(NonZeros);
4761     SDValue Item = Op.getOperand(Idx);
4762
4763     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4764     // the value are obviously zero, truncate the value to i32 and do the
4765     // insertion that way.  Only do this if the value is non-constant or if the
4766     // value is a constant being inserted into element 0.  It is cheaper to do
4767     // a constant pool load than it is to do a movd + shuffle.
4768     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4769         (!IsAllConstants || Idx == 0)) {
4770       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4771         // Handle SSE only.
4772         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4773         EVT VecVT = MVT::v4i32;
4774         unsigned VecElts = 4;
4775
4776         // Truncate the value (which may itself be a constant) to i32, and
4777         // convert it to a vector with movd (S2V+shuffle to zero extend).
4778         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4779         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4780         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4781                                            Subtarget->hasSSE2(), DAG);
4782
4783         // Now we have our 32-bit value zero extended in the low element of
4784         // a vector.  If Idx != 0, swizzle it into place.
4785         if (Idx != 0) {
4786           SmallVector<int, 4> Mask;
4787           Mask.push_back(Idx);
4788           for (unsigned i = 1; i != VecElts; ++i)
4789             Mask.push_back(i);
4790           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4791                                       DAG.getUNDEF(Item.getValueType()),
4792                                       &Mask[0]);
4793         }
4794         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4795       }
4796     }
4797
4798     // If we have a constant or non-constant insertion into the low element of
4799     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4800     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4801     // depending on what the source datatype is.
4802     if (Idx == 0) {
4803       if (NumZero == 0) {
4804         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4805       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4806           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4807         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4808         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4809         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4810                                            DAG);
4811       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4812         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4813         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4814         EVT MiddleVT = MVT::v4i32;
4815         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4816         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4817                                            Subtarget->hasSSE2(), DAG);
4818         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4819       }
4820     }
4821
4822     // Is it a vector logical left shift?
4823     if (NumElems == 2 && Idx == 1 &&
4824         X86::isZeroNode(Op.getOperand(0)) &&
4825         !X86::isZeroNode(Op.getOperand(1))) {
4826       unsigned NumBits = VT.getSizeInBits();
4827       return getVShift(true, VT,
4828                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4829                                    VT, Op.getOperand(1)),
4830                        NumBits/2, DAG, *this, dl);
4831     }
4832
4833     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4834       return SDValue();
4835
4836     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4837     // is a non-constant being inserted into an element other than the low one,
4838     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4839     // movd/movss) to move this into the low element, then shuffle it into
4840     // place.
4841     if (EVTBits == 32) {
4842       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4843
4844       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4845       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4846                                          Subtarget->hasSSE2(), DAG);
4847       SmallVector<int, 8> MaskVec;
4848       for (unsigned i = 0; i < NumElems; i++)
4849         MaskVec.push_back(i == Idx ? 0 : 1);
4850       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4851     }
4852   }
4853
4854   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4855   if (Values.size() == 1) {
4856     if (EVTBits == 32) {
4857       // Instead of a shuffle like this:
4858       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4859       // Check if it's possible to issue this instead.
4860       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4861       unsigned Idx = CountTrailingZeros_32(NonZeros);
4862       SDValue Item = Op.getOperand(Idx);
4863       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4864         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4865     }
4866     return SDValue();
4867   }
4868
4869   // A vector full of immediates; various special cases are already
4870   // handled, so this is best done with a single constant-pool load.
4871   if (IsAllConstants)
4872     return SDValue();
4873
4874   // For AVX-length vectors, build the individual 128-bit pieces and use
4875   // shuffles to put them in place.
4876   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
4877     SmallVector<SDValue, 32> V;
4878     for (unsigned i = 0; i < NumElems; ++i)
4879       V.push_back(Op.getOperand(i));
4880
4881     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4882
4883     // Build both the lower and upper subvector.
4884     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4885     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4886                                 NumElems/2);
4887
4888     // Recreate the wider vector with the lower and upper part.
4889     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
4890                                 DAG.getConstant(0, MVT::i32), DAG, dl);
4891     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
4892                               DAG, dl);
4893   }
4894
4895   // Let legalizer expand 2-wide build_vectors.
4896   if (EVTBits == 64) {
4897     if (NumNonZero == 1) {
4898       // One half is zero or undef.
4899       unsigned Idx = CountTrailingZeros_32(NonZeros);
4900       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4901                                  Op.getOperand(Idx));
4902       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4903                                          Subtarget->hasSSE2(), DAG);
4904     }
4905     return SDValue();
4906   }
4907
4908   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4909   if (EVTBits == 8 && NumElems == 16) {
4910     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4911                                         *this);
4912     if (V.getNode()) return V;
4913   }
4914
4915   if (EVTBits == 16 && NumElems == 8) {
4916     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4917                                       *this);
4918     if (V.getNode()) return V;
4919   }
4920
4921   // If element VT is == 32 bits, turn it into a number of shuffles.
4922   SmallVector<SDValue, 8> V;
4923   V.resize(NumElems);
4924   if (NumElems == 4 && NumZero > 0) {
4925     for (unsigned i = 0; i < 4; ++i) {
4926       bool isZero = !(NonZeros & (1 << i));
4927       if (isZero)
4928         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4929       else
4930         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4931     }
4932
4933     for (unsigned i = 0; i < 2; ++i) {
4934       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4935         default: break;
4936         case 0:
4937           V[i] = V[i*2];  // Must be a zero vector.
4938           break;
4939         case 1:
4940           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4941           break;
4942         case 2:
4943           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4944           break;
4945         case 3:
4946           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4947           break;
4948       }
4949     }
4950
4951     SmallVector<int, 8> MaskVec;
4952     bool Reverse = (NonZeros & 0x3) == 2;
4953     for (unsigned i = 0; i < 2; ++i)
4954       MaskVec.push_back(Reverse ? 1-i : i);
4955     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4956     for (unsigned i = 0; i < 2; ++i)
4957       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4958     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4959   }
4960
4961   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4962     // Check for a build vector of consecutive loads.
4963     for (unsigned i = 0; i < NumElems; ++i)
4964       V[i] = Op.getOperand(i);
4965
4966     // Check for elements which are consecutive loads.
4967     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4968     if (LD.getNode())
4969       return LD;
4970
4971     // For SSE 4.1, use insertps to put the high elements into the low element.
4972     if (getSubtarget()->hasSSE41()) {
4973       SDValue Result;
4974       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4975         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4976       else
4977         Result = DAG.getUNDEF(VT);
4978
4979       for (unsigned i = 1; i < NumElems; ++i) {
4980         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4981         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4982                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4983       }
4984       return Result;
4985     }
4986
4987     // Otherwise, expand into a number of unpckl*, start by extending each of
4988     // our (non-undef) elements to the full vector width with the element in the
4989     // bottom slot of the vector (which generates no code for SSE).
4990     for (unsigned i = 0; i < NumElems; ++i) {
4991       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4992         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4993       else
4994         V[i] = DAG.getUNDEF(VT);
4995     }
4996
4997     // Next, we iteratively mix elements, e.g. for v4f32:
4998     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4999     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5000     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5001     unsigned EltStride = NumElems >> 1;
5002     while (EltStride != 0) {
5003       for (unsigned i = 0; i < EltStride; ++i) {
5004         // If V[i+EltStride] is undef and this is the first round of mixing,
5005         // then it is safe to just drop this shuffle: V[i] is already in the
5006         // right place, the one element (since it's the first round) being
5007         // inserted as undef can be dropped.  This isn't safe for successive
5008         // rounds because they will permute elements within both vectors.
5009         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5010             EltStride == NumElems/2)
5011           continue;
5012
5013         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5014       }
5015       EltStride >>= 1;
5016     }
5017     return V[0];
5018   }
5019   return SDValue();
5020 }
5021
5022 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5023 // them in a MMX register.  This is better than doing a stack convert.
5024 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5025   DebugLoc dl = Op.getDebugLoc();
5026   EVT ResVT = Op.getValueType();
5027
5028   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5029          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5030   int Mask[2];
5031   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5032   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5033   InVec = Op.getOperand(1);
5034   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5035     unsigned NumElts = ResVT.getVectorNumElements();
5036     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5037     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5038                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5039   } else {
5040     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5041     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5042     Mask[0] = 0; Mask[1] = 2;
5043     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5044   }
5045   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5046 }
5047
5048 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5049 // to create 256-bit vectors from two other 128-bit ones.
5050 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5051   DebugLoc dl = Op.getDebugLoc();
5052   EVT ResVT = Op.getValueType();
5053
5054   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5055
5056   SDValue V1 = Op.getOperand(0);
5057   SDValue V2 = Op.getOperand(1);
5058   unsigned NumElems = ResVT.getVectorNumElements();
5059
5060   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5061                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5062   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5063                             DAG, dl);
5064 }
5065
5066 SDValue
5067 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5068   EVT ResVT = Op.getValueType();
5069
5070   assert(Op.getNumOperands() == 2);
5071   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5072          "Unsupported CONCAT_VECTORS for value type");
5073
5074   // We support concatenate two MMX registers and place them in a MMX register.
5075   // This is better than doing a stack convert.
5076   if (ResVT.is128BitVector())
5077     return LowerMMXCONCAT_VECTORS(Op, DAG);
5078
5079   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5080   // from two other 128-bit ones.
5081   return LowerAVXCONCAT_VECTORS(Op, DAG);
5082 }
5083
5084 // v8i16 shuffles - Prefer shuffles in the following order:
5085 // 1. [all]   pshuflw, pshufhw, optional move
5086 // 2. [ssse3] 1 x pshufb
5087 // 3. [ssse3] 2 x pshufb + 1 x por
5088 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5089 SDValue
5090 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5091                                             SelectionDAG &DAG) const {
5092   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5093   SDValue V1 = SVOp->getOperand(0);
5094   SDValue V2 = SVOp->getOperand(1);
5095   DebugLoc dl = SVOp->getDebugLoc();
5096   SmallVector<int, 8> MaskVals;
5097
5098   // Determine if more than 1 of the words in each of the low and high quadwords
5099   // of the result come from the same quadword of one of the two inputs.  Undef
5100   // mask values count as coming from any quadword, for better codegen.
5101   SmallVector<unsigned, 4> LoQuad(4);
5102   SmallVector<unsigned, 4> HiQuad(4);
5103   BitVector InputQuads(4);
5104   for (unsigned i = 0; i < 8; ++i) {
5105     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5106     int EltIdx = SVOp->getMaskElt(i);
5107     MaskVals.push_back(EltIdx);
5108     if (EltIdx < 0) {
5109       ++Quad[0];
5110       ++Quad[1];
5111       ++Quad[2];
5112       ++Quad[3];
5113       continue;
5114     }
5115     ++Quad[EltIdx / 4];
5116     InputQuads.set(EltIdx / 4);
5117   }
5118
5119   int BestLoQuad = -1;
5120   unsigned MaxQuad = 1;
5121   for (unsigned i = 0; i < 4; ++i) {
5122     if (LoQuad[i] > MaxQuad) {
5123       BestLoQuad = i;
5124       MaxQuad = LoQuad[i];
5125     }
5126   }
5127
5128   int BestHiQuad = -1;
5129   MaxQuad = 1;
5130   for (unsigned i = 0; i < 4; ++i) {
5131     if (HiQuad[i] > MaxQuad) {
5132       BestHiQuad = i;
5133       MaxQuad = HiQuad[i];
5134     }
5135   }
5136
5137   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5138   // of the two input vectors, shuffle them into one input vector so only a
5139   // single pshufb instruction is necessary. If There are more than 2 input
5140   // quads, disable the next transformation since it does not help SSSE3.
5141   bool V1Used = InputQuads[0] || InputQuads[1];
5142   bool V2Used = InputQuads[2] || InputQuads[3];
5143   if (Subtarget->hasSSSE3()) {
5144     if (InputQuads.count() == 2 && V1Used && V2Used) {
5145       BestLoQuad = InputQuads.find_first();
5146       BestHiQuad = InputQuads.find_next(BestLoQuad);
5147     }
5148     if (InputQuads.count() > 2) {
5149       BestLoQuad = -1;
5150       BestHiQuad = -1;
5151     }
5152   }
5153
5154   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5155   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5156   // words from all 4 input quadwords.
5157   SDValue NewV;
5158   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5159     SmallVector<int, 8> MaskV;
5160     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5161     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5162     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5163                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5164                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5165     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5166
5167     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5168     // source words for the shuffle, to aid later transformations.
5169     bool AllWordsInNewV = true;
5170     bool InOrder[2] = { true, true };
5171     for (unsigned i = 0; i != 8; ++i) {
5172       int idx = MaskVals[i];
5173       if (idx != (int)i)
5174         InOrder[i/4] = false;
5175       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5176         continue;
5177       AllWordsInNewV = false;
5178       break;
5179     }
5180
5181     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5182     if (AllWordsInNewV) {
5183       for (int i = 0; i != 8; ++i) {
5184         int idx = MaskVals[i];
5185         if (idx < 0)
5186           continue;
5187         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5188         if ((idx != i) && idx < 4)
5189           pshufhw = false;
5190         if ((idx != i) && idx > 3)
5191           pshuflw = false;
5192       }
5193       V1 = NewV;
5194       V2Used = false;
5195       BestLoQuad = 0;
5196       BestHiQuad = 1;
5197     }
5198
5199     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5200     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5201     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5202       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5203       unsigned TargetMask = 0;
5204       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5205                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5206       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5207                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5208       V1 = NewV.getOperand(0);
5209       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5210     }
5211   }
5212
5213   // If we have SSSE3, and all words of the result are from 1 input vector,
5214   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5215   // is present, fall back to case 4.
5216   if (Subtarget->hasSSSE3()) {
5217     SmallVector<SDValue,16> pshufbMask;
5218
5219     // If we have elements from both input vectors, set the high bit of the
5220     // shuffle mask element to zero out elements that come from V2 in the V1
5221     // mask, and elements that come from V1 in the V2 mask, so that the two
5222     // results can be OR'd together.
5223     bool TwoInputs = V1Used && V2Used;
5224     for (unsigned i = 0; i != 8; ++i) {
5225       int EltIdx = MaskVals[i] * 2;
5226       if (TwoInputs && (EltIdx >= 16)) {
5227         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5228         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5229         continue;
5230       }
5231       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5232       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5233     }
5234     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5235     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5236                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5237                                  MVT::v16i8, &pshufbMask[0], 16));
5238     if (!TwoInputs)
5239       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5240
5241     // Calculate the shuffle mask for the second input, shuffle it, and
5242     // OR it with the first shuffled input.
5243     pshufbMask.clear();
5244     for (unsigned i = 0; i != 8; ++i) {
5245       int EltIdx = MaskVals[i] * 2;
5246       if (EltIdx < 16) {
5247         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5248         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5249         continue;
5250       }
5251       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5252       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5253     }
5254     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5255     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5256                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5257                                  MVT::v16i8, &pshufbMask[0], 16));
5258     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5259     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5260   }
5261
5262   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5263   // and update MaskVals with new element order.
5264   BitVector InOrder(8);
5265   if (BestLoQuad >= 0) {
5266     SmallVector<int, 8> MaskV;
5267     for (int i = 0; i != 4; ++i) {
5268       int idx = MaskVals[i];
5269       if (idx < 0) {
5270         MaskV.push_back(-1);
5271         InOrder.set(i);
5272       } else if ((idx / 4) == BestLoQuad) {
5273         MaskV.push_back(idx & 3);
5274         InOrder.set(i);
5275       } else {
5276         MaskV.push_back(-1);
5277       }
5278     }
5279     for (unsigned i = 4; i != 8; ++i)
5280       MaskV.push_back(i);
5281     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5282                                 &MaskV[0]);
5283
5284     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5285       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5286                                NewV.getOperand(0),
5287                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5288                                DAG);
5289   }
5290
5291   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5292   // and update MaskVals with the new element order.
5293   if (BestHiQuad >= 0) {
5294     SmallVector<int, 8> MaskV;
5295     for (unsigned i = 0; i != 4; ++i)
5296       MaskV.push_back(i);
5297     for (unsigned i = 4; i != 8; ++i) {
5298       int idx = MaskVals[i];
5299       if (idx < 0) {
5300         MaskV.push_back(-1);
5301         InOrder.set(i);
5302       } else if ((idx / 4) == BestHiQuad) {
5303         MaskV.push_back((idx & 3) + 4);
5304         InOrder.set(i);
5305       } else {
5306         MaskV.push_back(-1);
5307       }
5308     }
5309     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5310                                 &MaskV[0]);
5311
5312     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5313       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5314                               NewV.getOperand(0),
5315                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5316                               DAG);
5317   }
5318
5319   // In case BestHi & BestLo were both -1, which means each quadword has a word
5320   // from each of the four input quadwords, calculate the InOrder bitvector now
5321   // before falling through to the insert/extract cleanup.
5322   if (BestLoQuad == -1 && BestHiQuad == -1) {
5323     NewV = V1;
5324     for (int i = 0; i != 8; ++i)
5325       if (MaskVals[i] < 0 || MaskVals[i] == i)
5326         InOrder.set(i);
5327   }
5328
5329   // The other elements are put in the right place using pextrw and pinsrw.
5330   for (unsigned i = 0; i != 8; ++i) {
5331     if (InOrder[i])
5332       continue;
5333     int EltIdx = MaskVals[i];
5334     if (EltIdx < 0)
5335       continue;
5336     SDValue ExtOp = (EltIdx < 8)
5337     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5338                   DAG.getIntPtrConstant(EltIdx))
5339     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5340                   DAG.getIntPtrConstant(EltIdx - 8));
5341     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5342                        DAG.getIntPtrConstant(i));
5343   }
5344   return NewV;
5345 }
5346
5347 // v16i8 shuffles - Prefer shuffles in the following order:
5348 // 1. [ssse3] 1 x pshufb
5349 // 2. [ssse3] 2 x pshufb + 1 x por
5350 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5351 static
5352 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5353                                  SelectionDAG &DAG,
5354                                  const X86TargetLowering &TLI) {
5355   SDValue V1 = SVOp->getOperand(0);
5356   SDValue V2 = SVOp->getOperand(1);
5357   DebugLoc dl = SVOp->getDebugLoc();
5358   SmallVector<int, 16> MaskVals;
5359   SVOp->getMask(MaskVals);
5360
5361   // If we have SSSE3, case 1 is generated when all result bytes come from
5362   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5363   // present, fall back to case 3.
5364   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5365   bool V1Only = true;
5366   bool V2Only = true;
5367   for (unsigned i = 0; i < 16; ++i) {
5368     int EltIdx = MaskVals[i];
5369     if (EltIdx < 0)
5370       continue;
5371     if (EltIdx < 16)
5372       V2Only = false;
5373     else
5374       V1Only = false;
5375   }
5376
5377   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5378   if (TLI.getSubtarget()->hasSSSE3()) {
5379     SmallVector<SDValue,16> pshufbMask;
5380
5381     // If all result elements are from one input vector, then only translate
5382     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5383     //
5384     // Otherwise, we have elements from both input vectors, and must zero out
5385     // elements that come from V2 in the first mask, and V1 in the second mask
5386     // so that we can OR them together.
5387     bool TwoInputs = !(V1Only || V2Only);
5388     for (unsigned i = 0; i != 16; ++i) {
5389       int EltIdx = MaskVals[i];
5390       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5391         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5392         continue;
5393       }
5394       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5395     }
5396     // If all the elements are from V2, assign it to V1 and return after
5397     // building the first pshufb.
5398     if (V2Only)
5399       V1 = V2;
5400     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5401                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5402                                  MVT::v16i8, &pshufbMask[0], 16));
5403     if (!TwoInputs)
5404       return V1;
5405
5406     // Calculate the shuffle mask for the second input, shuffle it, and
5407     // OR it with the first shuffled input.
5408     pshufbMask.clear();
5409     for (unsigned i = 0; i != 16; ++i) {
5410       int EltIdx = MaskVals[i];
5411       if (EltIdx < 16) {
5412         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5413         continue;
5414       }
5415       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5416     }
5417     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5418                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5419                                  MVT::v16i8, &pshufbMask[0], 16));
5420     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5421   }
5422
5423   // No SSSE3 - Calculate in place words and then fix all out of place words
5424   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5425   // the 16 different words that comprise the two doublequadword input vectors.
5426   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5427   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5428   SDValue NewV = V2Only ? V2 : V1;
5429   for (int i = 0; i != 8; ++i) {
5430     int Elt0 = MaskVals[i*2];
5431     int Elt1 = MaskVals[i*2+1];
5432
5433     // This word of the result is all undef, skip it.
5434     if (Elt0 < 0 && Elt1 < 0)
5435       continue;
5436
5437     // This word of the result is already in the correct place, skip it.
5438     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5439       continue;
5440     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5441       continue;
5442
5443     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5444     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5445     SDValue InsElt;
5446
5447     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5448     // using a single extract together, load it and store it.
5449     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5450       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5451                            DAG.getIntPtrConstant(Elt1 / 2));
5452       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5453                         DAG.getIntPtrConstant(i));
5454       continue;
5455     }
5456
5457     // If Elt1 is defined, extract it from the appropriate source.  If the
5458     // source byte is not also odd, shift the extracted word left 8 bits
5459     // otherwise clear the bottom 8 bits if we need to do an or.
5460     if (Elt1 >= 0) {
5461       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5462                            DAG.getIntPtrConstant(Elt1 / 2));
5463       if ((Elt1 & 1) == 0)
5464         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5465                              DAG.getConstant(8,
5466                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5467       else if (Elt0 >= 0)
5468         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5469                              DAG.getConstant(0xFF00, MVT::i16));
5470     }
5471     // If Elt0 is defined, extract it from the appropriate source.  If the
5472     // source byte is not also even, shift the extracted word right 8 bits. If
5473     // Elt1 was also defined, OR the extracted values together before
5474     // inserting them in the result.
5475     if (Elt0 >= 0) {
5476       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5477                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5478       if ((Elt0 & 1) != 0)
5479         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5480                               DAG.getConstant(8,
5481                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5482       else if (Elt1 >= 0)
5483         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5484                              DAG.getConstant(0x00FF, MVT::i16));
5485       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5486                          : InsElt0;
5487     }
5488     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5489                        DAG.getIntPtrConstant(i));
5490   }
5491   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5492 }
5493
5494 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5495 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5496 /// done when every pair / quad of shuffle mask elements point to elements in
5497 /// the right sequence. e.g.
5498 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5499 static
5500 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5501                                  SelectionDAG &DAG, DebugLoc dl) {
5502   EVT VT = SVOp->getValueType(0);
5503   SDValue V1 = SVOp->getOperand(0);
5504   SDValue V2 = SVOp->getOperand(1);
5505   unsigned NumElems = VT.getVectorNumElements();
5506   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5507   EVT NewVT;
5508   switch (VT.getSimpleVT().SimpleTy) {
5509   default: assert(false && "Unexpected!");
5510   case MVT::v4f32: NewVT = MVT::v2f64; break;
5511   case MVT::v4i32: NewVT = MVT::v2i64; break;
5512   case MVT::v8i16: NewVT = MVT::v4i32; break;
5513   case MVT::v16i8: NewVT = MVT::v4i32; break;
5514   }
5515
5516   int Scale = NumElems / NewWidth;
5517   SmallVector<int, 8> MaskVec;
5518   for (unsigned i = 0; i < NumElems; i += Scale) {
5519     int StartIdx = -1;
5520     for (int j = 0; j < Scale; ++j) {
5521       int EltIdx = SVOp->getMaskElt(i+j);
5522       if (EltIdx < 0)
5523         continue;
5524       if (StartIdx == -1)
5525         StartIdx = EltIdx - (EltIdx % Scale);
5526       if (EltIdx != StartIdx + j)
5527         return SDValue();
5528     }
5529     if (StartIdx == -1)
5530       MaskVec.push_back(-1);
5531     else
5532       MaskVec.push_back(StartIdx / Scale);
5533   }
5534
5535   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5536   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5537   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5538 }
5539
5540 /// getVZextMovL - Return a zero-extending vector move low node.
5541 ///
5542 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5543                             SDValue SrcOp, SelectionDAG &DAG,
5544                             const X86Subtarget *Subtarget, DebugLoc dl) {
5545   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5546     LoadSDNode *LD = NULL;
5547     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5548       LD = dyn_cast<LoadSDNode>(SrcOp);
5549     if (!LD) {
5550       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5551       // instead.
5552       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5553       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5554           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5555           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5556           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5557         // PR2108
5558         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5559         return DAG.getNode(ISD::BITCAST, dl, VT,
5560                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5561                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5562                                                    OpVT,
5563                                                    SrcOp.getOperand(0)
5564                                                           .getOperand(0))));
5565       }
5566     }
5567   }
5568
5569   return DAG.getNode(ISD::BITCAST, dl, VT,
5570                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5571                                  DAG.getNode(ISD::BITCAST, dl,
5572                                              OpVT, SrcOp)));
5573 }
5574
5575 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5576 /// which could not be matched by any known target speficic shuffle
5577 static SDValue
5578 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5579   return SDValue();
5580 }
5581
5582 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5583 /// 4 elements, and match them with several different shuffle types.
5584 static SDValue
5585 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5586   SDValue V1 = SVOp->getOperand(0);
5587   SDValue V2 = SVOp->getOperand(1);
5588   DebugLoc dl = SVOp->getDebugLoc();
5589   EVT VT = SVOp->getValueType(0);
5590
5591   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5592
5593   SmallVector<std::pair<int, int>, 8> Locs;
5594   Locs.resize(4);
5595   SmallVector<int, 8> Mask1(4U, -1);
5596   SmallVector<int, 8> PermMask;
5597   SVOp->getMask(PermMask);
5598
5599   unsigned NumHi = 0;
5600   unsigned NumLo = 0;
5601   for (unsigned i = 0; i != 4; ++i) {
5602     int Idx = PermMask[i];
5603     if (Idx < 0) {
5604       Locs[i] = std::make_pair(-1, -1);
5605     } else {
5606       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5607       if (Idx < 4) {
5608         Locs[i] = std::make_pair(0, NumLo);
5609         Mask1[NumLo] = Idx;
5610         NumLo++;
5611       } else {
5612         Locs[i] = std::make_pair(1, NumHi);
5613         if (2+NumHi < 4)
5614           Mask1[2+NumHi] = Idx;
5615         NumHi++;
5616       }
5617     }
5618   }
5619
5620   if (NumLo <= 2 && NumHi <= 2) {
5621     // If no more than two elements come from either vector. This can be
5622     // implemented with two shuffles. First shuffle gather the elements.
5623     // The second shuffle, which takes the first shuffle as both of its
5624     // vector operands, put the elements into the right order.
5625     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5626
5627     SmallVector<int, 8> Mask2(4U, -1);
5628
5629     for (unsigned i = 0; i != 4; ++i) {
5630       if (Locs[i].first == -1)
5631         continue;
5632       else {
5633         unsigned Idx = (i < 2) ? 0 : 4;
5634         Idx += Locs[i].first * 2 + Locs[i].second;
5635         Mask2[i] = Idx;
5636       }
5637     }
5638
5639     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5640   } else if (NumLo == 3 || NumHi == 3) {
5641     // Otherwise, we must have three elements from one vector, call it X, and
5642     // one element from the other, call it Y.  First, use a shufps to build an
5643     // intermediate vector with the one element from Y and the element from X
5644     // that will be in the same half in the final destination (the indexes don't
5645     // matter). Then, use a shufps to build the final vector, taking the half
5646     // containing the element from Y from the intermediate, and the other half
5647     // from X.
5648     if (NumHi == 3) {
5649       // Normalize it so the 3 elements come from V1.
5650       CommuteVectorShuffleMask(PermMask, VT);
5651       std::swap(V1, V2);
5652     }
5653
5654     // Find the element from V2.
5655     unsigned HiIndex;
5656     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5657       int Val = PermMask[HiIndex];
5658       if (Val < 0)
5659         continue;
5660       if (Val >= 4)
5661         break;
5662     }
5663
5664     Mask1[0] = PermMask[HiIndex];
5665     Mask1[1] = -1;
5666     Mask1[2] = PermMask[HiIndex^1];
5667     Mask1[3] = -1;
5668     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5669
5670     if (HiIndex >= 2) {
5671       Mask1[0] = PermMask[0];
5672       Mask1[1] = PermMask[1];
5673       Mask1[2] = HiIndex & 1 ? 6 : 4;
5674       Mask1[3] = HiIndex & 1 ? 4 : 6;
5675       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5676     } else {
5677       Mask1[0] = HiIndex & 1 ? 2 : 0;
5678       Mask1[1] = HiIndex & 1 ? 0 : 2;
5679       Mask1[2] = PermMask[2];
5680       Mask1[3] = PermMask[3];
5681       if (Mask1[2] >= 0)
5682         Mask1[2] += 4;
5683       if (Mask1[3] >= 0)
5684         Mask1[3] += 4;
5685       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5686     }
5687   }
5688
5689   // Break it into (shuffle shuffle_hi, shuffle_lo).
5690   Locs.clear();
5691   Locs.resize(4);
5692   SmallVector<int,8> LoMask(4U, -1);
5693   SmallVector<int,8> HiMask(4U, -1);
5694
5695   SmallVector<int,8> *MaskPtr = &LoMask;
5696   unsigned MaskIdx = 0;
5697   unsigned LoIdx = 0;
5698   unsigned HiIdx = 2;
5699   for (unsigned i = 0; i != 4; ++i) {
5700     if (i == 2) {
5701       MaskPtr = &HiMask;
5702       MaskIdx = 1;
5703       LoIdx = 0;
5704       HiIdx = 2;
5705     }
5706     int Idx = PermMask[i];
5707     if (Idx < 0) {
5708       Locs[i] = std::make_pair(-1, -1);
5709     } else if (Idx < 4) {
5710       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5711       (*MaskPtr)[LoIdx] = Idx;
5712       LoIdx++;
5713     } else {
5714       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5715       (*MaskPtr)[HiIdx] = Idx;
5716       HiIdx++;
5717     }
5718   }
5719
5720   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5721   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5722   SmallVector<int, 8> MaskOps;
5723   for (unsigned i = 0; i != 4; ++i) {
5724     if (Locs[i].first == -1) {
5725       MaskOps.push_back(-1);
5726     } else {
5727       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5728       MaskOps.push_back(Idx);
5729     }
5730   }
5731   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5732 }
5733
5734 static bool MayFoldVectorLoad(SDValue V) {
5735   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5736     V = V.getOperand(0);
5737   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5738     V = V.getOperand(0);
5739   if (MayFoldLoad(V))
5740     return true;
5741   return false;
5742 }
5743
5744 // FIXME: the version above should always be used. Since there's
5745 // a bug where several vector shuffles can't be folded because the
5746 // DAG is not updated during lowering and a node claims to have two
5747 // uses while it only has one, use this version, and let isel match
5748 // another instruction if the load really happens to have more than
5749 // one use. Remove this version after this bug get fixed.
5750 // rdar://8434668, PR8156
5751 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5752   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5753     V = V.getOperand(0);
5754   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5755     V = V.getOperand(0);
5756   if (ISD::isNormalLoad(V.getNode()))
5757     return true;
5758   return false;
5759 }
5760
5761 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5762 /// a vector extract, and if both can be later optimized into a single load.
5763 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5764 /// here because otherwise a target specific shuffle node is going to be
5765 /// emitted for this shuffle, and the optimization not done.
5766 /// FIXME: This is probably not the best approach, but fix the problem
5767 /// until the right path is decided.
5768 static
5769 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5770                                          const TargetLowering &TLI) {
5771   EVT VT = V.getValueType();
5772   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5773
5774   // Be sure that the vector shuffle is present in a pattern like this:
5775   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5776   if (!V.hasOneUse())
5777     return false;
5778
5779   SDNode *N = *V.getNode()->use_begin();
5780   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5781     return false;
5782
5783   SDValue EltNo = N->getOperand(1);
5784   if (!isa<ConstantSDNode>(EltNo))
5785     return false;
5786
5787   // If the bit convert changed the number of elements, it is unsafe
5788   // to examine the mask.
5789   bool HasShuffleIntoBitcast = false;
5790   if (V.getOpcode() == ISD::BITCAST) {
5791     EVT SrcVT = V.getOperand(0).getValueType();
5792     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5793       return false;
5794     V = V.getOperand(0);
5795     HasShuffleIntoBitcast = true;
5796   }
5797
5798   // Select the input vector, guarding against out of range extract vector.
5799   unsigned NumElems = VT.getVectorNumElements();
5800   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5801   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5802   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5803
5804   // Skip one more bit_convert if necessary
5805   if (V.getOpcode() == ISD::BITCAST)
5806     V = V.getOperand(0);
5807
5808   if (ISD::isNormalLoad(V.getNode())) {
5809     // Is the original load suitable?
5810     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5811
5812     // FIXME: avoid the multi-use bug that is preventing lots of
5813     // of foldings to be detected, this is still wrong of course, but
5814     // give the temporary desired behavior, and if it happens that
5815     // the load has real more uses, during isel it will not fold, and
5816     // will generate poor code.
5817     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5818       return false;
5819
5820     if (!HasShuffleIntoBitcast)
5821       return true;
5822
5823     // If there's a bitcast before the shuffle, check if the load type and
5824     // alignment is valid.
5825     unsigned Align = LN0->getAlignment();
5826     unsigned NewAlign =
5827       TLI.getTargetData()->getABITypeAlignment(
5828                                     VT.getTypeForEVT(*DAG.getContext()));
5829
5830     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5831       return false;
5832   }
5833
5834   return true;
5835 }
5836
5837 static
5838 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5839   EVT VT = Op.getValueType();
5840
5841   // Canonizalize to v2f64.
5842   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5843   return DAG.getNode(ISD::BITCAST, dl, VT,
5844                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5845                                           V1, DAG));
5846 }
5847
5848 static
5849 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5850                         bool HasSSE2) {
5851   SDValue V1 = Op.getOperand(0);
5852   SDValue V2 = Op.getOperand(1);
5853   EVT VT = Op.getValueType();
5854
5855   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5856
5857   if (HasSSE2 && VT == MVT::v2f64)
5858     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5859
5860   // v4f32 or v4i32
5861   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5862 }
5863
5864 static
5865 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5866   SDValue V1 = Op.getOperand(0);
5867   SDValue V2 = Op.getOperand(1);
5868   EVT VT = Op.getValueType();
5869
5870   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5871          "unsupported shuffle type");
5872
5873   if (V2.getOpcode() == ISD::UNDEF)
5874     V2 = V1;
5875
5876   // v4i32 or v4f32
5877   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5878 }
5879
5880 static
5881 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5882   SDValue V1 = Op.getOperand(0);
5883   SDValue V2 = Op.getOperand(1);
5884   EVT VT = Op.getValueType();
5885   unsigned NumElems = VT.getVectorNumElements();
5886
5887   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5888   // operand of these instructions is only memory, so check if there's a
5889   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5890   // same masks.
5891   bool CanFoldLoad = false;
5892
5893   // Trivial case, when V2 comes from a load.
5894   if (MayFoldVectorLoad(V2))
5895     CanFoldLoad = true;
5896
5897   // When V1 is a load, it can be folded later into a store in isel, example:
5898   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5899   //    turns into:
5900   //  (MOVLPSmr addr:$src1, VR128:$src2)
5901   // So, recognize this potential and also use MOVLPS or MOVLPD
5902   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5903     CanFoldLoad = true;
5904
5905   // Both of them can't be memory operations though.
5906   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5907     CanFoldLoad = false;
5908
5909   if (CanFoldLoad) {
5910     if (HasSSE2 && NumElems == 2)
5911       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5912
5913     if (NumElems == 4)
5914       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5915   }
5916
5917   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5918   // movl and movlp will both match v2i64, but v2i64 is never matched by
5919   // movl earlier because we make it strict to avoid messing with the movlp load
5920   // folding logic (see the code above getMOVLP call). Match it here then,
5921   // this is horrible, but will stay like this until we move all shuffle
5922   // matching to x86 specific nodes. Note that for the 1st condition all
5923   // types are matched with movsd.
5924   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5925     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5926   else if (HasSSE2)
5927     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5928
5929
5930   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5931
5932   // Invert the operand order and use SHUFPS to match it.
5933   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5934                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5935 }
5936
5937 static inline unsigned getUNPCKLOpcode(EVT VT) {
5938   switch(VT.getSimpleVT().SimpleTy) {
5939   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5940   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5941   case MVT::v4f32: return X86ISD::UNPCKLPS;
5942   case MVT::v2f64: return X86ISD::UNPCKLPD;
5943   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5944   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5945   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5946   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5947   default:
5948     llvm_unreachable("Unknown type for unpckl");
5949   }
5950   return 0;
5951 }
5952
5953 static inline unsigned getUNPCKHOpcode(EVT VT) {
5954   switch(VT.getSimpleVT().SimpleTy) {
5955   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5956   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5957   case MVT::v4f32: return X86ISD::UNPCKHPS;
5958   case MVT::v2f64: return X86ISD::UNPCKHPD;
5959   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
5960   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
5961   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5962   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5963   default:
5964     llvm_unreachable("Unknown type for unpckh");
5965   }
5966   return 0;
5967 }
5968
5969 static inline unsigned getVPERMILOpcode(EVT VT) {
5970   switch(VT.getSimpleVT().SimpleTy) {
5971   case MVT::v4i32:
5972   case MVT::v4f32: return X86ISD::VPERMILPS;
5973   case MVT::v2i64:
5974   case MVT::v2f64: return X86ISD::VPERMILPD;
5975   case MVT::v8i32:
5976   case MVT::v8f32: return X86ISD::VPERMILPSY;
5977   case MVT::v4i64:
5978   case MVT::v4f64: return X86ISD::VPERMILPDY;
5979   default:
5980     llvm_unreachable("Unknown type for vpermil");
5981   }
5982   return 0;
5983 }
5984
5985 static
5986 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5987                                const TargetLowering &TLI,
5988                                const X86Subtarget *Subtarget) {
5989   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5990   EVT VT = Op.getValueType();
5991   DebugLoc dl = Op.getDebugLoc();
5992   SDValue V1 = Op.getOperand(0);
5993   SDValue V2 = Op.getOperand(1);
5994
5995   if (isZeroShuffle(SVOp))
5996     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5997
5998   // Handle splat operations
5999   if (SVOp->isSplat()) {
6000     unsigned NumElem = VT.getVectorNumElements();
6001     // Special case, this is the only place now where it's allowed to return
6002     // a vector_shuffle operation without using a target specific node, because
6003     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6004     // this be moved to DAGCombine instead?
6005     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6006       return Op;
6007
6008     // Since there's no native support for scalar_to_vector for 256-bit AVX, a
6009     // 128-bit scalar_to_vector + INSERT_SUBVECTOR is generated. Recognize this
6010     // idiom and do the shuffle before the insertion, this yields less
6011     // instructions in the end.
6012     if (VT.is256BitVector() &&
6013         V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
6014         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
6015         V1.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR)
6016       return PromoteVectorToScalarSplat(SVOp, DAG);
6017
6018     // Handle splats by matching through known shuffle masks
6019     if ((VT.is128BitVector() && NumElem <= 4) ||
6020         (VT.is256BitVector() && NumElem <= 8))
6021       return SDValue();
6022
6023     // All i16 and i8 vector types can't be used directly by a generic shuffle
6024     // instruction because the target has no such instruction. Generate shuffles
6025     // which repeat i16 and i8 several times until they fit in i32, and then can
6026     // be manipulated by target suported shuffles. After the insertion of the
6027     // necessary shuffles, the result is bitcasted back to v4f32 or v8f32.
6028     return PromoteSplat(SVOp, DAG);
6029   }
6030
6031   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6032   // do it!
6033   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6034     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6035     if (NewOp.getNode())
6036       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6037   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6038     // FIXME: Figure out a cleaner way to do this.
6039     // Try to make use of movq to zero out the top part.
6040     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6041       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6042       if (NewOp.getNode()) {
6043         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6044           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6045                               DAG, Subtarget, dl);
6046       }
6047     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6048       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6049       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6050         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6051                             DAG, Subtarget, dl);
6052     }
6053   }
6054   return SDValue();
6055 }
6056
6057 SDValue
6058 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6059   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6060   SDValue V1 = Op.getOperand(0);
6061   SDValue V2 = Op.getOperand(1);
6062   EVT VT = Op.getValueType();
6063   DebugLoc dl = Op.getDebugLoc();
6064   unsigned NumElems = VT.getVectorNumElements();
6065   bool isMMX = VT.getSizeInBits() == 64;
6066   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6067   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6068   bool V1IsSplat = false;
6069   bool V2IsSplat = false;
6070   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6071   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6072   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6073   MachineFunction &MF = DAG.getMachineFunction();
6074   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6075
6076   // Shuffle operations on MMX not supported.
6077   if (isMMX)
6078     return Op;
6079
6080   // Vector shuffle lowering takes 3 steps:
6081   //
6082   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6083   //    narrowing and commutation of operands should be handled.
6084   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6085   //    shuffle nodes.
6086   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6087   //    so the shuffle can be broken into other shuffles and the legalizer can
6088   //    try the lowering again.
6089   //
6090   // The general ideia is that no vector_shuffle operation should be left to
6091   // be matched during isel, all of them must be converted to a target specific
6092   // node here.
6093
6094   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6095   // narrowing and commutation of operands should be handled. The actual code
6096   // doesn't include all of those, work in progress...
6097   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6098   if (NewOp.getNode())
6099     return NewOp;
6100
6101   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6102   // unpckh_undef). Only use pshufd if speed is more important than size.
6103   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6104     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6105   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6106     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6107
6108   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6109       RelaxedMayFoldVectorLoad(V1))
6110     return getMOVDDup(Op, dl, V1, DAG);
6111
6112   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6113     return getMOVHighToLow(Op, dl, DAG);
6114
6115   // Use to match splats
6116   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6117       (VT == MVT::v2f64 || VT == MVT::v2i64))
6118     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6119
6120   if (X86::isPSHUFDMask(SVOp)) {
6121     // The actual implementation will match the mask in the if above and then
6122     // during isel it can match several different instructions, not only pshufd
6123     // as its name says, sad but true, emulate the behavior for now...
6124     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6125         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6126
6127     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6128
6129     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6130       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6131
6132     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6133       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
6134                                   TargetMask, DAG);
6135
6136     if (VT == MVT::v4f32)
6137       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
6138                                   TargetMask, DAG);
6139   }
6140
6141   // Check if this can be converted into a logical shift.
6142   bool isLeft = false;
6143   unsigned ShAmt = 0;
6144   SDValue ShVal;
6145   bool isShift = getSubtarget()->hasSSE2() &&
6146     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6147   if (isShift && ShVal.hasOneUse()) {
6148     // If the shifted value has multiple uses, it may be cheaper to use
6149     // v_set0 + movlhps or movhlps, etc.
6150     EVT EltVT = VT.getVectorElementType();
6151     ShAmt *= EltVT.getSizeInBits();
6152     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6153   }
6154
6155   if (X86::isMOVLMask(SVOp)) {
6156     if (V1IsUndef)
6157       return V2;
6158     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6159       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6160     if (!X86::isMOVLPMask(SVOp)) {
6161       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6162         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6163
6164       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6165         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6166     }
6167   }
6168
6169   // FIXME: fold these into legal mask.
6170   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6171     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6172
6173   if (X86::isMOVHLPSMask(SVOp))
6174     return getMOVHighToLow(Op, dl, DAG);
6175
6176   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6177     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6178
6179   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6180     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6181
6182   if (X86::isMOVLPMask(SVOp))
6183     return getMOVLP(Op, dl, DAG, HasSSE2);
6184
6185   if (ShouldXformToMOVHLPS(SVOp) ||
6186       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6187     return CommuteVectorShuffle(SVOp, DAG);
6188
6189   if (isShift) {
6190     // No better options. Use a vshl / vsrl.
6191     EVT EltVT = VT.getVectorElementType();
6192     ShAmt *= EltVT.getSizeInBits();
6193     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6194   }
6195
6196   bool Commuted = false;
6197   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6198   // 1,1,1,1 -> v8i16 though.
6199   V1IsSplat = isSplatVector(V1.getNode());
6200   V2IsSplat = isSplatVector(V2.getNode());
6201
6202   // Canonicalize the splat or undef, if present, to be on the RHS.
6203   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6204     Op = CommuteVectorShuffle(SVOp, DAG);
6205     SVOp = cast<ShuffleVectorSDNode>(Op);
6206     V1 = SVOp->getOperand(0);
6207     V2 = SVOp->getOperand(1);
6208     std::swap(V1IsSplat, V2IsSplat);
6209     std::swap(V1IsUndef, V2IsUndef);
6210     Commuted = true;
6211   }
6212
6213   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6214     // Shuffling low element of v1 into undef, just return v1.
6215     if (V2IsUndef)
6216       return V1;
6217     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6218     // the instruction selector will not match, so get a canonical MOVL with
6219     // swapped operands to undo the commute.
6220     return getMOVL(DAG, dl, VT, V2, V1);
6221   }
6222
6223   if (X86::isUNPCKLMask(SVOp))
6224     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6225
6226   if (X86::isUNPCKHMask(SVOp))
6227     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6228
6229   if (V2IsSplat) {
6230     // Normalize mask so all entries that point to V2 points to its first
6231     // element then try to match unpck{h|l} again. If match, return a
6232     // new vector_shuffle with the corrected mask.
6233     SDValue NewMask = NormalizeMask(SVOp, DAG);
6234     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6235     if (NSVOp != SVOp) {
6236       if (X86::isUNPCKLMask(NSVOp, true)) {
6237         return NewMask;
6238       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6239         return NewMask;
6240       }
6241     }
6242   }
6243
6244   if (Commuted) {
6245     // Commute is back and try unpck* again.
6246     // FIXME: this seems wrong.
6247     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6248     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6249
6250     if (X86::isUNPCKLMask(NewSVOp))
6251       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6252
6253     if (X86::isUNPCKHMask(NewSVOp))
6254       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6255   }
6256
6257   // Normalize the node to match x86 shuffle ops if needed
6258   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6259     return CommuteVectorShuffle(SVOp, DAG);
6260
6261   // The checks below are all present in isShuffleMaskLegal, but they are
6262   // inlined here right now to enable us to directly emit target specific
6263   // nodes, and remove one by one until they don't return Op anymore.
6264   SmallVector<int, 16> M;
6265   SVOp->getMask(M);
6266
6267   if (isPALIGNRMask(M, VT, HasSSSE3))
6268     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6269                                 X86::getShufflePALIGNRImmediate(SVOp),
6270                                 DAG);
6271
6272   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6273       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6274     if (VT == MVT::v2f64)
6275       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6276     if (VT == MVT::v2i64)
6277       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6278   }
6279
6280   if (isPSHUFHWMask(M, VT))
6281     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6282                                 X86::getShufflePSHUFHWImmediate(SVOp),
6283                                 DAG);
6284
6285   if (isPSHUFLWMask(M, VT))
6286     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6287                                 X86::getShufflePSHUFLWImmediate(SVOp),
6288                                 DAG);
6289
6290   if (isSHUFPMask(M, VT)) {
6291     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6292     if (VT == MVT::v4f32 || VT == MVT::v4i32)
6293       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6294                                   TargetMask, DAG);
6295     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6296       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6297                                   TargetMask, DAG);
6298   }
6299
6300   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6301     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6302   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6303     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6304
6305   //===--------------------------------------------------------------------===//
6306   // Generate target specific nodes for 128 or 256-bit shuffles only
6307   // supported in the AVX instruction set.
6308   //
6309
6310   // Handle VPERMILPS* permutations
6311   if (isVPERMILPSMask(M, VT, Subtarget))
6312     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6313                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6314
6315   // Handle VPERMILPD* permutations
6316   if (isVPERMILPDMask(M, VT, Subtarget))
6317     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6318                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6319
6320   //===--------------------------------------------------------------------===//
6321   // Since no target specific shuffle was selected for this generic one,
6322   // lower it into other known shuffles. FIXME: this isn't true yet, but
6323   // this is the plan.
6324   //
6325
6326   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6327   if (VT == MVT::v8i16) {
6328     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6329     if (NewOp.getNode())
6330       return NewOp;
6331   }
6332
6333   if (VT == MVT::v16i8) {
6334     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6335     if (NewOp.getNode())
6336       return NewOp;
6337   }
6338
6339   // Handle all 128-bit wide vectors with 4 elements, and match them with
6340   // several different shuffle types.
6341   if (NumElems == 4 && VT.getSizeInBits() == 128)
6342     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6343
6344   // Handle general 256-bit shuffles
6345   if (VT.is256BitVector())
6346     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6347
6348   return SDValue();
6349 }
6350
6351 SDValue
6352 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6353                                                 SelectionDAG &DAG) const {
6354   EVT VT = Op.getValueType();
6355   DebugLoc dl = Op.getDebugLoc();
6356
6357   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6358     return SDValue();
6359
6360   if (VT.getSizeInBits() == 8) {
6361     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6362                                     Op.getOperand(0), Op.getOperand(1));
6363     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6364                                     DAG.getValueType(VT));
6365     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6366   } else if (VT.getSizeInBits() == 16) {
6367     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6368     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6369     if (Idx == 0)
6370       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6371                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6372                                      DAG.getNode(ISD::BITCAST, dl,
6373                                                  MVT::v4i32,
6374                                                  Op.getOperand(0)),
6375                                      Op.getOperand(1)));
6376     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6377                                     Op.getOperand(0), Op.getOperand(1));
6378     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6379                                     DAG.getValueType(VT));
6380     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6381   } else if (VT == MVT::f32) {
6382     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6383     // the result back to FR32 register. It's only worth matching if the
6384     // result has a single use which is a store or a bitcast to i32.  And in
6385     // the case of a store, it's not worth it if the index is a constant 0,
6386     // because a MOVSSmr can be used instead, which is smaller and faster.
6387     if (!Op.hasOneUse())
6388       return SDValue();
6389     SDNode *User = *Op.getNode()->use_begin();
6390     if ((User->getOpcode() != ISD::STORE ||
6391          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6392           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6393         (User->getOpcode() != ISD::BITCAST ||
6394          User->getValueType(0) != MVT::i32))
6395       return SDValue();
6396     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6397                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6398                                               Op.getOperand(0)),
6399                                               Op.getOperand(1));
6400     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6401   } else if (VT == MVT::i32) {
6402     // ExtractPS works with constant index.
6403     if (isa<ConstantSDNode>(Op.getOperand(1)))
6404       return Op;
6405   }
6406   return SDValue();
6407 }
6408
6409
6410 SDValue
6411 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6412                                            SelectionDAG &DAG) const {
6413   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6414     return SDValue();
6415
6416   SDValue Vec = Op.getOperand(0);
6417   EVT VecVT = Vec.getValueType();
6418
6419   // If this is a 256-bit vector result, first extract the 128-bit vector and
6420   // then extract the element from the 128-bit vector.
6421   if (VecVT.getSizeInBits() == 256) {
6422     DebugLoc dl = Op.getNode()->getDebugLoc();
6423     unsigned NumElems = VecVT.getVectorNumElements();
6424     SDValue Idx = Op.getOperand(1);
6425     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6426
6427     // Get the 128-bit vector.
6428     bool Upper = IdxVal >= NumElems/2;
6429     Vec = Extract128BitVector(Vec,
6430                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6431
6432     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6433                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6434   }
6435
6436   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6437
6438   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6439     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6440     if (Res.getNode())
6441       return Res;
6442   }
6443
6444   EVT VT = Op.getValueType();
6445   DebugLoc dl = Op.getDebugLoc();
6446   // TODO: handle v16i8.
6447   if (VT.getSizeInBits() == 16) {
6448     SDValue Vec = Op.getOperand(0);
6449     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6450     if (Idx == 0)
6451       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6452                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6453                                      DAG.getNode(ISD::BITCAST, dl,
6454                                                  MVT::v4i32, Vec),
6455                                      Op.getOperand(1)));
6456     // Transform it so it match pextrw which produces a 32-bit result.
6457     EVT EltVT = MVT::i32;
6458     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6459                                     Op.getOperand(0), Op.getOperand(1));
6460     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6461                                     DAG.getValueType(VT));
6462     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6463   } else if (VT.getSizeInBits() == 32) {
6464     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6465     if (Idx == 0)
6466       return Op;
6467
6468     // SHUFPS the element to the lowest double word, then movss.
6469     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6470     EVT VVT = Op.getOperand(0).getValueType();
6471     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6472                                        DAG.getUNDEF(VVT), Mask);
6473     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6474                        DAG.getIntPtrConstant(0));
6475   } else if (VT.getSizeInBits() == 64) {
6476     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6477     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6478     //        to match extract_elt for f64.
6479     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6480     if (Idx == 0)
6481       return Op;
6482
6483     // UNPCKHPD the element to the lowest double word, then movsd.
6484     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6485     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6486     int Mask[2] = { 1, -1 };
6487     EVT VVT = Op.getOperand(0).getValueType();
6488     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6489                                        DAG.getUNDEF(VVT), Mask);
6490     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6491                        DAG.getIntPtrConstant(0));
6492   }
6493
6494   return SDValue();
6495 }
6496
6497 SDValue
6498 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6499                                                SelectionDAG &DAG) const {
6500   EVT VT = Op.getValueType();
6501   EVT EltVT = VT.getVectorElementType();
6502   DebugLoc dl = Op.getDebugLoc();
6503
6504   SDValue N0 = Op.getOperand(0);
6505   SDValue N1 = Op.getOperand(1);
6506   SDValue N2 = Op.getOperand(2);
6507
6508   if (VT.getSizeInBits() == 256)
6509     return SDValue();
6510
6511   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6512       isa<ConstantSDNode>(N2)) {
6513     unsigned Opc;
6514     if (VT == MVT::v8i16)
6515       Opc = X86ISD::PINSRW;
6516     else if (VT == MVT::v16i8)
6517       Opc = X86ISD::PINSRB;
6518     else
6519       Opc = X86ISD::PINSRB;
6520
6521     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6522     // argument.
6523     if (N1.getValueType() != MVT::i32)
6524       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6525     if (N2.getValueType() != MVT::i32)
6526       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6527     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6528   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6529     // Bits [7:6] of the constant are the source select.  This will always be
6530     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6531     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6532     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6533     // Bits [5:4] of the constant are the destination select.  This is the
6534     //  value of the incoming immediate.
6535     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6536     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6537     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6538     // Create this as a scalar to vector..
6539     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6540     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6541   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6542     // PINSR* works with constant index.
6543     return Op;
6544   }
6545   return SDValue();
6546 }
6547
6548 SDValue
6549 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6550   EVT VT = Op.getValueType();
6551   EVT EltVT = VT.getVectorElementType();
6552
6553   DebugLoc dl = Op.getDebugLoc();
6554   SDValue N0 = Op.getOperand(0);
6555   SDValue N1 = Op.getOperand(1);
6556   SDValue N2 = Op.getOperand(2);
6557
6558   // If this is a 256-bit vector result, first extract the 128-bit vector,
6559   // insert the element into the extracted half and then place it back.
6560   if (VT.getSizeInBits() == 256) {
6561     if (!isa<ConstantSDNode>(N2))
6562       return SDValue();
6563
6564     // Get the desired 128-bit vector half.
6565     unsigned NumElems = VT.getVectorNumElements();
6566     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6567     bool Upper = IdxVal >= NumElems/2;
6568     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6569     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6570
6571     // Insert the element into the desired half.
6572     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6573                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6574
6575     // Insert the changed part back to the 256-bit vector
6576     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6577   }
6578
6579   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
6580     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6581
6582   if (EltVT == MVT::i8)
6583     return SDValue();
6584
6585   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6586     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6587     // as its second argument.
6588     if (N1.getValueType() != MVT::i32)
6589       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6590     if (N2.getValueType() != MVT::i32)
6591       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6592     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6593   }
6594   return SDValue();
6595 }
6596
6597 SDValue
6598 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6599   LLVMContext *Context = DAG.getContext();
6600   DebugLoc dl = Op.getDebugLoc();
6601   EVT OpVT = Op.getValueType();
6602
6603   // If this is a 256-bit vector result, first insert into a 128-bit
6604   // vector and then insert into the 256-bit vector.
6605   if (OpVT.getSizeInBits() > 128) {
6606     // Insert into a 128-bit vector.
6607     EVT VT128 = EVT::getVectorVT(*Context,
6608                                  OpVT.getVectorElementType(),
6609                                  OpVT.getVectorNumElements() / 2);
6610
6611     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6612
6613     // Insert the 128-bit vector.
6614     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6615                               DAG.getConstant(0, MVT::i32),
6616                               DAG, dl);
6617   }
6618
6619   if (Op.getValueType() == MVT::v1i64 &&
6620       Op.getOperand(0).getValueType() == MVT::i64)
6621     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6622
6623   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6624   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6625          "Expected an SSE type!");
6626   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6627                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6628 }
6629
6630 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6631 // a simple subregister reference or explicit instructions to grab
6632 // upper bits of a vector.
6633 SDValue
6634 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6635   if (Subtarget->hasAVX()) {
6636     DebugLoc dl = Op.getNode()->getDebugLoc();
6637     SDValue Vec = Op.getNode()->getOperand(0);
6638     SDValue Idx = Op.getNode()->getOperand(1);
6639
6640     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6641         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6642         return Extract128BitVector(Vec, Idx, DAG, dl);
6643     }
6644   }
6645   return SDValue();
6646 }
6647
6648 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6649 // simple superregister reference or explicit instructions to insert
6650 // the upper bits of a vector.
6651 SDValue
6652 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6653   if (Subtarget->hasAVX()) {
6654     DebugLoc dl = Op.getNode()->getDebugLoc();
6655     SDValue Vec = Op.getNode()->getOperand(0);
6656     SDValue SubVec = Op.getNode()->getOperand(1);
6657     SDValue Idx = Op.getNode()->getOperand(2);
6658
6659     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6660         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6661       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6662     }
6663   }
6664   return SDValue();
6665 }
6666
6667 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6668 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6669 // one of the above mentioned nodes. It has to be wrapped because otherwise
6670 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6671 // be used to form addressing mode. These wrapped nodes will be selected
6672 // into MOV32ri.
6673 SDValue
6674 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6675   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6676
6677   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6678   // global base reg.
6679   unsigned char OpFlag = 0;
6680   unsigned WrapperKind = X86ISD::Wrapper;
6681   CodeModel::Model M = getTargetMachine().getCodeModel();
6682
6683   if (Subtarget->isPICStyleRIPRel() &&
6684       (M == CodeModel::Small || M == CodeModel::Kernel))
6685     WrapperKind = X86ISD::WrapperRIP;
6686   else if (Subtarget->isPICStyleGOT())
6687     OpFlag = X86II::MO_GOTOFF;
6688   else if (Subtarget->isPICStyleStubPIC())
6689     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6690
6691   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6692                                              CP->getAlignment(),
6693                                              CP->getOffset(), OpFlag);
6694   DebugLoc DL = CP->getDebugLoc();
6695   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6696   // With PIC, the address is actually $g + Offset.
6697   if (OpFlag) {
6698     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6699                          DAG.getNode(X86ISD::GlobalBaseReg,
6700                                      DebugLoc(), getPointerTy()),
6701                          Result);
6702   }
6703
6704   return Result;
6705 }
6706
6707 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6708   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6709
6710   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6711   // global base reg.
6712   unsigned char OpFlag = 0;
6713   unsigned WrapperKind = X86ISD::Wrapper;
6714   CodeModel::Model M = getTargetMachine().getCodeModel();
6715
6716   if (Subtarget->isPICStyleRIPRel() &&
6717       (M == CodeModel::Small || M == CodeModel::Kernel))
6718     WrapperKind = X86ISD::WrapperRIP;
6719   else if (Subtarget->isPICStyleGOT())
6720     OpFlag = X86II::MO_GOTOFF;
6721   else if (Subtarget->isPICStyleStubPIC())
6722     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6723
6724   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6725                                           OpFlag);
6726   DebugLoc DL = JT->getDebugLoc();
6727   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6728
6729   // With PIC, the address is actually $g + Offset.
6730   if (OpFlag)
6731     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6732                          DAG.getNode(X86ISD::GlobalBaseReg,
6733                                      DebugLoc(), getPointerTy()),
6734                          Result);
6735
6736   return Result;
6737 }
6738
6739 SDValue
6740 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6741   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6742
6743   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6744   // global base reg.
6745   unsigned char OpFlag = 0;
6746   unsigned WrapperKind = X86ISD::Wrapper;
6747   CodeModel::Model M = getTargetMachine().getCodeModel();
6748
6749   if (Subtarget->isPICStyleRIPRel() &&
6750       (M == CodeModel::Small || M == CodeModel::Kernel))
6751     WrapperKind = X86ISD::WrapperRIP;
6752   else if (Subtarget->isPICStyleGOT())
6753     OpFlag = X86II::MO_GOTOFF;
6754   else if (Subtarget->isPICStyleStubPIC())
6755     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6756
6757   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6758
6759   DebugLoc DL = Op.getDebugLoc();
6760   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6761
6762
6763   // With PIC, the address is actually $g + Offset.
6764   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6765       !Subtarget->is64Bit()) {
6766     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6767                          DAG.getNode(X86ISD::GlobalBaseReg,
6768                                      DebugLoc(), getPointerTy()),
6769                          Result);
6770   }
6771
6772   return Result;
6773 }
6774
6775 SDValue
6776 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6777   // Create the TargetBlockAddressAddress node.
6778   unsigned char OpFlags =
6779     Subtarget->ClassifyBlockAddressReference();
6780   CodeModel::Model M = getTargetMachine().getCodeModel();
6781   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6782   DebugLoc dl = Op.getDebugLoc();
6783   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6784                                        /*isTarget=*/true, OpFlags);
6785
6786   if (Subtarget->isPICStyleRIPRel() &&
6787       (M == CodeModel::Small || M == CodeModel::Kernel))
6788     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6789   else
6790     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6791
6792   // With PIC, the address is actually $g + Offset.
6793   if (isGlobalRelativeToPICBase(OpFlags)) {
6794     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6795                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6796                          Result);
6797   }
6798
6799   return Result;
6800 }
6801
6802 SDValue
6803 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6804                                       int64_t Offset,
6805                                       SelectionDAG &DAG) const {
6806   // Create the TargetGlobalAddress node, folding in the constant
6807   // offset if it is legal.
6808   unsigned char OpFlags =
6809     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6810   CodeModel::Model M = getTargetMachine().getCodeModel();
6811   SDValue Result;
6812   if (OpFlags == X86II::MO_NO_FLAG &&
6813       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6814     // A direct static reference to a global.
6815     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6816     Offset = 0;
6817   } else {
6818     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6819   }
6820
6821   if (Subtarget->isPICStyleRIPRel() &&
6822       (M == CodeModel::Small || M == CodeModel::Kernel))
6823     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6824   else
6825     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6826
6827   // With PIC, the address is actually $g + Offset.
6828   if (isGlobalRelativeToPICBase(OpFlags)) {
6829     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6830                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6831                          Result);
6832   }
6833
6834   // For globals that require a load from a stub to get the address, emit the
6835   // load.
6836   if (isGlobalStubReference(OpFlags))
6837     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6838                          MachinePointerInfo::getGOT(), false, false, 0);
6839
6840   // If there was a non-zero offset that we didn't fold, create an explicit
6841   // addition for it.
6842   if (Offset != 0)
6843     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6844                          DAG.getConstant(Offset, getPointerTy()));
6845
6846   return Result;
6847 }
6848
6849 SDValue
6850 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6851   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6852   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6853   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6854 }
6855
6856 static SDValue
6857 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6858            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6859            unsigned char OperandFlags) {
6860   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6861   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6862   DebugLoc dl = GA->getDebugLoc();
6863   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6864                                            GA->getValueType(0),
6865                                            GA->getOffset(),
6866                                            OperandFlags);
6867   if (InFlag) {
6868     SDValue Ops[] = { Chain,  TGA, *InFlag };
6869     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6870   } else {
6871     SDValue Ops[]  = { Chain, TGA };
6872     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6873   }
6874
6875   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6876   MFI->setAdjustsStack(true);
6877
6878   SDValue Flag = Chain.getValue(1);
6879   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6880 }
6881
6882 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6883 static SDValue
6884 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6885                                 const EVT PtrVT) {
6886   SDValue InFlag;
6887   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6888   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6889                                      DAG.getNode(X86ISD::GlobalBaseReg,
6890                                                  DebugLoc(), PtrVT), InFlag);
6891   InFlag = Chain.getValue(1);
6892
6893   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6894 }
6895
6896 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6897 static SDValue
6898 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6899                                 const EVT PtrVT) {
6900   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6901                     X86::RAX, X86II::MO_TLSGD);
6902 }
6903
6904 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6905 // "local exec" model.
6906 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6907                                    const EVT PtrVT, TLSModel::Model model,
6908                                    bool is64Bit) {
6909   DebugLoc dl = GA->getDebugLoc();
6910
6911   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6912   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6913                                                          is64Bit ? 257 : 256));
6914
6915   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6916                                       DAG.getIntPtrConstant(0),
6917                                       MachinePointerInfo(Ptr), false, false, 0);
6918
6919   unsigned char OperandFlags = 0;
6920   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6921   // initialexec.
6922   unsigned WrapperKind = X86ISD::Wrapper;
6923   if (model == TLSModel::LocalExec) {
6924     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6925   } else if (is64Bit) {
6926     assert(model == TLSModel::InitialExec);
6927     OperandFlags = X86II::MO_GOTTPOFF;
6928     WrapperKind = X86ISD::WrapperRIP;
6929   } else {
6930     assert(model == TLSModel::InitialExec);
6931     OperandFlags = X86II::MO_INDNTPOFF;
6932   }
6933
6934   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6935   // exec)
6936   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6937                                            GA->getValueType(0),
6938                                            GA->getOffset(), OperandFlags);
6939   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6940
6941   if (model == TLSModel::InitialExec)
6942     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6943                          MachinePointerInfo::getGOT(), false, false, 0);
6944
6945   // The address of the thread local variable is the add of the thread
6946   // pointer with the offset of the variable.
6947   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6948 }
6949
6950 SDValue
6951 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6952
6953   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6954   const GlobalValue *GV = GA->getGlobal();
6955
6956   if (Subtarget->isTargetELF()) {
6957     // TODO: implement the "local dynamic" model
6958     // TODO: implement the "initial exec"model for pic executables
6959
6960     // If GV is an alias then use the aliasee for determining
6961     // thread-localness.
6962     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6963       GV = GA->resolveAliasedGlobal(false);
6964
6965     TLSModel::Model model
6966       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6967
6968     switch (model) {
6969       case TLSModel::GeneralDynamic:
6970       case TLSModel::LocalDynamic: // not implemented
6971         if (Subtarget->is64Bit())
6972           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6973         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6974
6975       case TLSModel::InitialExec:
6976       case TLSModel::LocalExec:
6977         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6978                                    Subtarget->is64Bit());
6979     }
6980   } else if (Subtarget->isTargetDarwin()) {
6981     // Darwin only has one model of TLS.  Lower to that.
6982     unsigned char OpFlag = 0;
6983     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6984                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6985
6986     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6987     // global base reg.
6988     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6989                   !Subtarget->is64Bit();
6990     if (PIC32)
6991       OpFlag = X86II::MO_TLVP_PIC_BASE;
6992     else
6993       OpFlag = X86II::MO_TLVP;
6994     DebugLoc DL = Op.getDebugLoc();
6995     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6996                                                 GA->getValueType(0),
6997                                                 GA->getOffset(), OpFlag);
6998     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6999
7000     // With PIC32, the address is actually $g + Offset.
7001     if (PIC32)
7002       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7003                            DAG.getNode(X86ISD::GlobalBaseReg,
7004                                        DebugLoc(), getPointerTy()),
7005                            Offset);
7006
7007     // Lowering the machine isd will make sure everything is in the right
7008     // location.
7009     SDValue Chain = DAG.getEntryNode();
7010     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7011     SDValue Args[] = { Chain, Offset };
7012     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7013
7014     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7015     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7016     MFI->setAdjustsStack(true);
7017
7018     // And our return value (tls address) is in the standard call return value
7019     // location.
7020     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7021     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7022   }
7023
7024   assert(false &&
7025          "TLS not implemented for this target.");
7026
7027   llvm_unreachable("Unreachable");
7028   return SDValue();
7029 }
7030
7031
7032 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7033 /// take a 2 x i32 value to shift plus a shift amount.
7034 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7035   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7036   EVT VT = Op.getValueType();
7037   unsigned VTBits = VT.getSizeInBits();
7038   DebugLoc dl = Op.getDebugLoc();
7039   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7040   SDValue ShOpLo = Op.getOperand(0);
7041   SDValue ShOpHi = Op.getOperand(1);
7042   SDValue ShAmt  = Op.getOperand(2);
7043   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7044                                      DAG.getConstant(VTBits - 1, MVT::i8))
7045                        : DAG.getConstant(0, VT);
7046
7047   SDValue Tmp2, Tmp3;
7048   if (Op.getOpcode() == ISD::SHL_PARTS) {
7049     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7050     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7051   } else {
7052     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7053     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7054   }
7055
7056   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7057                                 DAG.getConstant(VTBits, MVT::i8));
7058   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7059                              AndNode, DAG.getConstant(0, MVT::i8));
7060
7061   SDValue Hi, Lo;
7062   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7063   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7064   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7065
7066   if (Op.getOpcode() == ISD::SHL_PARTS) {
7067     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7068     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7069   } else {
7070     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7071     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7072   }
7073
7074   SDValue Ops[2] = { Lo, Hi };
7075   return DAG.getMergeValues(Ops, 2, dl);
7076 }
7077
7078 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7079                                            SelectionDAG &DAG) const {
7080   EVT SrcVT = Op.getOperand(0).getValueType();
7081
7082   if (SrcVT.isVector())
7083     return SDValue();
7084
7085   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7086          "Unknown SINT_TO_FP to lower!");
7087
7088   // These are really Legal; return the operand so the caller accepts it as
7089   // Legal.
7090   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7091     return Op;
7092   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7093       Subtarget->is64Bit()) {
7094     return Op;
7095   }
7096
7097   DebugLoc dl = Op.getDebugLoc();
7098   unsigned Size = SrcVT.getSizeInBits()/8;
7099   MachineFunction &MF = DAG.getMachineFunction();
7100   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7101   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7102   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7103                                StackSlot,
7104                                MachinePointerInfo::getFixedStack(SSFI),
7105                                false, false, 0);
7106   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7107 }
7108
7109 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7110                                      SDValue StackSlot,
7111                                      SelectionDAG &DAG) const {
7112   // Build the FILD
7113   DebugLoc DL = Op.getDebugLoc();
7114   SDVTList Tys;
7115   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7116   if (useSSE)
7117     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7118   else
7119     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7120
7121   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7122
7123   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7124   MachineMemOperand *MMO;
7125   if (FI) {
7126     int SSFI = FI->getIndex();
7127     MMO =
7128       DAG.getMachineFunction()
7129       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7130                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7131   } else {
7132     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7133     StackSlot = StackSlot.getOperand(1);
7134   }
7135   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7136   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7137                                            X86ISD::FILD, DL,
7138                                            Tys, Ops, array_lengthof(Ops),
7139                                            SrcVT, MMO);
7140
7141   if (useSSE) {
7142     Chain = Result.getValue(1);
7143     SDValue InFlag = Result.getValue(2);
7144
7145     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7146     // shouldn't be necessary except that RFP cannot be live across
7147     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7148     MachineFunction &MF = DAG.getMachineFunction();
7149     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7150     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7151     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7152     Tys = DAG.getVTList(MVT::Other);
7153     SDValue Ops[] = {
7154       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7155     };
7156     MachineMemOperand *MMO =
7157       DAG.getMachineFunction()
7158       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7159                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7160
7161     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7162                                     Ops, array_lengthof(Ops),
7163                                     Op.getValueType(), MMO);
7164     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7165                          MachinePointerInfo::getFixedStack(SSFI),
7166                          false, false, 0);
7167   }
7168
7169   return Result;
7170 }
7171
7172 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7173 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7174                                                SelectionDAG &DAG) const {
7175   // This algorithm is not obvious. Here it is in C code, more or less:
7176   /*
7177     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7178       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7179       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7180
7181       // Copy ints to xmm registers.
7182       __m128i xh = _mm_cvtsi32_si128( hi );
7183       __m128i xl = _mm_cvtsi32_si128( lo );
7184
7185       // Combine into low half of a single xmm register.
7186       __m128i x = _mm_unpacklo_epi32( xh, xl );
7187       __m128d d;
7188       double sd;
7189
7190       // Merge in appropriate exponents to give the integer bits the right
7191       // magnitude.
7192       x = _mm_unpacklo_epi32( x, exp );
7193
7194       // Subtract away the biases to deal with the IEEE-754 double precision
7195       // implicit 1.
7196       d = _mm_sub_pd( (__m128d) x, bias );
7197
7198       // All conversions up to here are exact. The correctly rounded result is
7199       // calculated using the current rounding mode using the following
7200       // horizontal add.
7201       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7202       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7203                                 // store doesn't really need to be here (except
7204                                 // maybe to zero the other double)
7205       return sd;
7206     }
7207   */
7208
7209   DebugLoc dl = Op.getDebugLoc();
7210   LLVMContext *Context = DAG.getContext();
7211
7212   // Build some magic constants.
7213   std::vector<Constant*> CV0;
7214   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7215   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7216   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7217   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7218   Constant *C0 = ConstantVector::get(CV0);
7219   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7220
7221   std::vector<Constant*> CV1;
7222   CV1.push_back(
7223     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7224   CV1.push_back(
7225     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7226   Constant *C1 = ConstantVector::get(CV1);
7227   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7228
7229   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7230                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7231                                         Op.getOperand(0),
7232                                         DAG.getIntPtrConstant(1)));
7233   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7234                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7235                                         Op.getOperand(0),
7236                                         DAG.getIntPtrConstant(0)));
7237   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7238   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7239                               MachinePointerInfo::getConstantPool(),
7240                               false, false, 16);
7241   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7242   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7243   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7244                               MachinePointerInfo::getConstantPool(),
7245                               false, false, 16);
7246   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7247
7248   // Add the halves; easiest way is to swap them into another reg first.
7249   int ShufMask[2] = { 1, -1 };
7250   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7251                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7252   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7253   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7254                      DAG.getIntPtrConstant(0));
7255 }
7256
7257 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7258 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7259                                                SelectionDAG &DAG) const {
7260   DebugLoc dl = Op.getDebugLoc();
7261   // FP constant to bias correct the final result.
7262   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7263                                    MVT::f64);
7264
7265   // Load the 32-bit value into an XMM register.
7266   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7267                              Op.getOperand(0));
7268
7269   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7270                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7271                      DAG.getIntPtrConstant(0));
7272
7273   // Or the load with the bias.
7274   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7275                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7276                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7277                                                    MVT::v2f64, Load)),
7278                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7279                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7280                                                    MVT::v2f64, Bias)));
7281   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7282                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7283                    DAG.getIntPtrConstant(0));
7284
7285   // Subtract the bias.
7286   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7287
7288   // Handle final rounding.
7289   EVT DestVT = Op.getValueType();
7290
7291   if (DestVT.bitsLT(MVT::f64)) {
7292     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7293                        DAG.getIntPtrConstant(0));
7294   } else if (DestVT.bitsGT(MVT::f64)) {
7295     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7296   }
7297
7298   // Handle final rounding.
7299   return Sub;
7300 }
7301
7302 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7303                                            SelectionDAG &DAG) const {
7304   SDValue N0 = Op.getOperand(0);
7305   DebugLoc dl = Op.getDebugLoc();
7306
7307   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7308   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7309   // the optimization here.
7310   if (DAG.SignBitIsZero(N0))
7311     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7312
7313   EVT SrcVT = N0.getValueType();
7314   EVT DstVT = Op.getValueType();
7315   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7316     return LowerUINT_TO_FP_i64(Op, DAG);
7317   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7318     return LowerUINT_TO_FP_i32(Op, DAG);
7319
7320   // Make a 64-bit buffer, and use it to build an FILD.
7321   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7322   if (SrcVT == MVT::i32) {
7323     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7324     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7325                                      getPointerTy(), StackSlot, WordOff);
7326     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7327                                   StackSlot, MachinePointerInfo(),
7328                                   false, false, 0);
7329     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7330                                   OffsetSlot, MachinePointerInfo(),
7331                                   false, false, 0);
7332     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7333     return Fild;
7334   }
7335
7336   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7337   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7338                                 StackSlot, MachinePointerInfo(),
7339                                false, false, 0);
7340   // For i64 source, we need to add the appropriate power of 2 if the input
7341   // was negative.  This is the same as the optimization in
7342   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7343   // we must be careful to do the computation in x87 extended precision, not
7344   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7345   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7346   MachineMemOperand *MMO =
7347     DAG.getMachineFunction()
7348     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7349                           MachineMemOperand::MOLoad, 8, 8);
7350
7351   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7352   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7353   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7354                                          MVT::i64, MMO);
7355
7356   APInt FF(32, 0x5F800000ULL);
7357
7358   // Check whether the sign bit is set.
7359   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7360                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7361                                  ISD::SETLT);
7362
7363   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7364   SDValue FudgePtr = DAG.getConstantPool(
7365                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7366                                          getPointerTy());
7367
7368   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7369   SDValue Zero = DAG.getIntPtrConstant(0);
7370   SDValue Four = DAG.getIntPtrConstant(4);
7371   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7372                                Zero, Four);
7373   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7374
7375   // Load the value out, extending it from f32 to f80.
7376   // FIXME: Avoid the extend by constructing the right constant pool?
7377   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7378                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7379                                  MVT::f32, false, false, 4);
7380   // Extend everything to 80 bits to force it to be done on x87.
7381   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7382   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7383 }
7384
7385 std::pair<SDValue,SDValue> X86TargetLowering::
7386 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7387   DebugLoc DL = Op.getDebugLoc();
7388
7389   EVT DstTy = Op.getValueType();
7390
7391   if (!IsSigned) {
7392     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7393     DstTy = MVT::i64;
7394   }
7395
7396   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7397          DstTy.getSimpleVT() >= MVT::i16 &&
7398          "Unknown FP_TO_SINT to lower!");
7399
7400   // These are really Legal.
7401   if (DstTy == MVT::i32 &&
7402       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7403     return std::make_pair(SDValue(), SDValue());
7404   if (Subtarget->is64Bit() &&
7405       DstTy == MVT::i64 &&
7406       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7407     return std::make_pair(SDValue(), SDValue());
7408
7409   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7410   // stack slot.
7411   MachineFunction &MF = DAG.getMachineFunction();
7412   unsigned MemSize = DstTy.getSizeInBits()/8;
7413   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7414   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7415
7416
7417
7418   unsigned Opc;
7419   switch (DstTy.getSimpleVT().SimpleTy) {
7420   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7421   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7422   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7423   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7424   }
7425
7426   SDValue Chain = DAG.getEntryNode();
7427   SDValue Value = Op.getOperand(0);
7428   EVT TheVT = Op.getOperand(0).getValueType();
7429   if (isScalarFPTypeInSSEReg(TheVT)) {
7430     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7431     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7432                          MachinePointerInfo::getFixedStack(SSFI),
7433                          false, false, 0);
7434     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7435     SDValue Ops[] = {
7436       Chain, StackSlot, DAG.getValueType(TheVT)
7437     };
7438
7439     MachineMemOperand *MMO =
7440       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7441                               MachineMemOperand::MOLoad, MemSize, MemSize);
7442     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7443                                     DstTy, MMO);
7444     Chain = Value.getValue(1);
7445     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7446     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7447   }
7448
7449   MachineMemOperand *MMO =
7450     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7451                             MachineMemOperand::MOStore, MemSize, MemSize);
7452
7453   // Build the FP_TO_INT*_IN_MEM
7454   SDValue Ops[] = { Chain, Value, StackSlot };
7455   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7456                                          Ops, 3, DstTy, MMO);
7457
7458   return std::make_pair(FIST, StackSlot);
7459 }
7460
7461 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7462                                            SelectionDAG &DAG) const {
7463   if (Op.getValueType().isVector())
7464     return SDValue();
7465
7466   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7467   SDValue FIST = Vals.first, StackSlot = Vals.second;
7468   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7469   if (FIST.getNode() == 0) return Op;
7470
7471   // Load the result.
7472   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7473                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7474 }
7475
7476 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7477                                            SelectionDAG &DAG) const {
7478   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7479   SDValue FIST = Vals.first, StackSlot = Vals.second;
7480   assert(FIST.getNode() && "Unexpected failure");
7481
7482   // Load the result.
7483   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7484                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7485 }
7486
7487 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7488                                      SelectionDAG &DAG) const {
7489   LLVMContext *Context = DAG.getContext();
7490   DebugLoc dl = Op.getDebugLoc();
7491   EVT VT = Op.getValueType();
7492   EVT EltVT = VT;
7493   if (VT.isVector())
7494     EltVT = VT.getVectorElementType();
7495   std::vector<Constant*> CV;
7496   if (EltVT == MVT::f64) {
7497     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7498     CV.push_back(C);
7499     CV.push_back(C);
7500   } else {
7501     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7502     CV.push_back(C);
7503     CV.push_back(C);
7504     CV.push_back(C);
7505     CV.push_back(C);
7506   }
7507   Constant *C = ConstantVector::get(CV);
7508   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7509   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7510                              MachinePointerInfo::getConstantPool(),
7511                              false, false, 16);
7512   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7513 }
7514
7515 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7516   LLVMContext *Context = DAG.getContext();
7517   DebugLoc dl = Op.getDebugLoc();
7518   EVT VT = Op.getValueType();
7519   EVT EltVT = VT;
7520   if (VT.isVector())
7521     EltVT = VT.getVectorElementType();
7522   std::vector<Constant*> CV;
7523   if (EltVT == MVT::f64) {
7524     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7525     CV.push_back(C);
7526     CV.push_back(C);
7527   } else {
7528     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7529     CV.push_back(C);
7530     CV.push_back(C);
7531     CV.push_back(C);
7532     CV.push_back(C);
7533   }
7534   Constant *C = ConstantVector::get(CV);
7535   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7536   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7537                              MachinePointerInfo::getConstantPool(),
7538                              false, false, 16);
7539   if (VT.isVector()) {
7540     return DAG.getNode(ISD::BITCAST, dl, VT,
7541                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7542                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7543                                 Op.getOperand(0)),
7544                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7545   } else {
7546     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7547   }
7548 }
7549
7550 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7551   LLVMContext *Context = DAG.getContext();
7552   SDValue Op0 = Op.getOperand(0);
7553   SDValue Op1 = Op.getOperand(1);
7554   DebugLoc dl = Op.getDebugLoc();
7555   EVT VT = Op.getValueType();
7556   EVT SrcVT = Op1.getValueType();
7557
7558   // If second operand is smaller, extend it first.
7559   if (SrcVT.bitsLT(VT)) {
7560     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7561     SrcVT = VT;
7562   }
7563   // And if it is bigger, shrink it first.
7564   if (SrcVT.bitsGT(VT)) {
7565     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7566     SrcVT = VT;
7567   }
7568
7569   // At this point the operands and the result should have the same
7570   // type, and that won't be f80 since that is not custom lowered.
7571
7572   // First get the sign bit of second operand.
7573   std::vector<Constant*> CV;
7574   if (SrcVT == MVT::f64) {
7575     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7576     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7577   } else {
7578     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7579     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7580     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7581     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7582   }
7583   Constant *C = ConstantVector::get(CV);
7584   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7585   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7586                               MachinePointerInfo::getConstantPool(),
7587                               false, false, 16);
7588   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7589
7590   // Shift sign bit right or left if the two operands have different types.
7591   if (SrcVT.bitsGT(VT)) {
7592     // Op0 is MVT::f32, Op1 is MVT::f64.
7593     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7594     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7595                           DAG.getConstant(32, MVT::i32));
7596     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7597     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7598                           DAG.getIntPtrConstant(0));
7599   }
7600
7601   // Clear first operand sign bit.
7602   CV.clear();
7603   if (VT == MVT::f64) {
7604     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7605     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7606   } else {
7607     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7608     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7609     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7610     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7611   }
7612   C = ConstantVector::get(CV);
7613   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7614   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7615                               MachinePointerInfo::getConstantPool(),
7616                               false, false, 16);
7617   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7618
7619   // Or the value with the sign bit.
7620   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7621 }
7622
7623 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7624   SDValue N0 = Op.getOperand(0);
7625   DebugLoc dl = Op.getDebugLoc();
7626   EVT VT = Op.getValueType();
7627
7628   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7629   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7630                                   DAG.getConstant(1, VT));
7631   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7632 }
7633
7634 /// Emit nodes that will be selected as "test Op0,Op0", or something
7635 /// equivalent.
7636 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7637                                     SelectionDAG &DAG) const {
7638   DebugLoc dl = Op.getDebugLoc();
7639
7640   // CF and OF aren't always set the way we want. Determine which
7641   // of these we need.
7642   bool NeedCF = false;
7643   bool NeedOF = false;
7644   switch (X86CC) {
7645   default: break;
7646   case X86::COND_A: case X86::COND_AE:
7647   case X86::COND_B: case X86::COND_BE:
7648     NeedCF = true;
7649     break;
7650   case X86::COND_G: case X86::COND_GE:
7651   case X86::COND_L: case X86::COND_LE:
7652   case X86::COND_O: case X86::COND_NO:
7653     NeedOF = true;
7654     break;
7655   }
7656
7657   // See if we can use the EFLAGS value from the operand instead of
7658   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7659   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7660   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7661     // Emit a CMP with 0, which is the TEST pattern.
7662     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7663                        DAG.getConstant(0, Op.getValueType()));
7664
7665   unsigned Opcode = 0;
7666   unsigned NumOperands = 0;
7667   switch (Op.getNode()->getOpcode()) {
7668   case ISD::ADD:
7669     // Due to an isel shortcoming, be conservative if this add is likely to be
7670     // selected as part of a load-modify-store instruction. When the root node
7671     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7672     // uses of other nodes in the match, such as the ADD in this case. This
7673     // leads to the ADD being left around and reselected, with the result being
7674     // two adds in the output.  Alas, even if none our users are stores, that
7675     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7676     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7677     // climbing the DAG back to the root, and it doesn't seem to be worth the
7678     // effort.
7679     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7680            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7681       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7682         goto default_case;
7683
7684     if (ConstantSDNode *C =
7685         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7686       // An add of one will be selected as an INC.
7687       if (C->getAPIntValue() == 1) {
7688         Opcode = X86ISD::INC;
7689         NumOperands = 1;
7690         break;
7691       }
7692
7693       // An add of negative one (subtract of one) will be selected as a DEC.
7694       if (C->getAPIntValue().isAllOnesValue()) {
7695         Opcode = X86ISD::DEC;
7696         NumOperands = 1;
7697         break;
7698       }
7699     }
7700
7701     // Otherwise use a regular EFLAGS-setting add.
7702     Opcode = X86ISD::ADD;
7703     NumOperands = 2;
7704     break;
7705   case ISD::AND: {
7706     // If the primary and result isn't used, don't bother using X86ISD::AND,
7707     // because a TEST instruction will be better.
7708     bool NonFlagUse = false;
7709     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7710            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7711       SDNode *User = *UI;
7712       unsigned UOpNo = UI.getOperandNo();
7713       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7714         // Look pass truncate.
7715         UOpNo = User->use_begin().getOperandNo();
7716         User = *User->use_begin();
7717       }
7718
7719       if (User->getOpcode() != ISD::BRCOND &&
7720           User->getOpcode() != ISD::SETCC &&
7721           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7722         NonFlagUse = true;
7723         break;
7724       }
7725     }
7726
7727     if (!NonFlagUse)
7728       break;
7729   }
7730     // FALL THROUGH
7731   case ISD::SUB:
7732   case ISD::OR:
7733   case ISD::XOR:
7734     // Due to the ISEL shortcoming noted above, be conservative if this op is
7735     // likely to be selected as part of a load-modify-store instruction.
7736     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7737            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7738       if (UI->getOpcode() == ISD::STORE)
7739         goto default_case;
7740
7741     // Otherwise use a regular EFLAGS-setting instruction.
7742     switch (Op.getNode()->getOpcode()) {
7743     default: llvm_unreachable("unexpected operator!");
7744     case ISD::SUB: Opcode = X86ISD::SUB; break;
7745     case ISD::OR:  Opcode = X86ISD::OR;  break;
7746     case ISD::XOR: Opcode = X86ISD::XOR; break;
7747     case ISD::AND: Opcode = X86ISD::AND; break;
7748     }
7749
7750     NumOperands = 2;
7751     break;
7752   case X86ISD::ADD:
7753   case X86ISD::SUB:
7754   case X86ISD::INC:
7755   case X86ISD::DEC:
7756   case X86ISD::OR:
7757   case X86ISD::XOR:
7758   case X86ISD::AND:
7759     return SDValue(Op.getNode(), 1);
7760   default:
7761   default_case:
7762     break;
7763   }
7764
7765   if (Opcode == 0)
7766     // Emit a CMP with 0, which is the TEST pattern.
7767     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7768                        DAG.getConstant(0, Op.getValueType()));
7769
7770   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7771   SmallVector<SDValue, 4> Ops;
7772   for (unsigned i = 0; i != NumOperands; ++i)
7773     Ops.push_back(Op.getOperand(i));
7774
7775   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7776   DAG.ReplaceAllUsesWith(Op, New);
7777   return SDValue(New.getNode(), 1);
7778 }
7779
7780 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7781 /// equivalent.
7782 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7783                                    SelectionDAG &DAG) const {
7784   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7785     if (C->getAPIntValue() == 0)
7786       return EmitTest(Op0, X86CC, DAG);
7787
7788   DebugLoc dl = Op0.getDebugLoc();
7789   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7790 }
7791
7792 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7793 /// if it's possible.
7794 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7795                                      DebugLoc dl, SelectionDAG &DAG) const {
7796   SDValue Op0 = And.getOperand(0);
7797   SDValue Op1 = And.getOperand(1);
7798   if (Op0.getOpcode() == ISD::TRUNCATE)
7799     Op0 = Op0.getOperand(0);
7800   if (Op1.getOpcode() == ISD::TRUNCATE)
7801     Op1 = Op1.getOperand(0);
7802
7803   SDValue LHS, RHS;
7804   if (Op1.getOpcode() == ISD::SHL)
7805     std::swap(Op0, Op1);
7806   if (Op0.getOpcode() == ISD::SHL) {
7807     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7808       if (And00C->getZExtValue() == 1) {
7809         // If we looked past a truncate, check that it's only truncating away
7810         // known zeros.
7811         unsigned BitWidth = Op0.getValueSizeInBits();
7812         unsigned AndBitWidth = And.getValueSizeInBits();
7813         if (BitWidth > AndBitWidth) {
7814           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7815           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7816           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7817             return SDValue();
7818         }
7819         LHS = Op1;
7820         RHS = Op0.getOperand(1);
7821       }
7822   } else if (Op1.getOpcode() == ISD::Constant) {
7823     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7824     SDValue AndLHS = Op0;
7825     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7826       LHS = AndLHS.getOperand(0);
7827       RHS = AndLHS.getOperand(1);
7828     }
7829   }
7830
7831   if (LHS.getNode()) {
7832     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7833     // instruction.  Since the shift amount is in-range-or-undefined, we know
7834     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7835     // the encoding for the i16 version is larger than the i32 version.
7836     // Also promote i16 to i32 for performance / code size reason.
7837     if (LHS.getValueType() == MVT::i8 ||
7838         LHS.getValueType() == MVT::i16)
7839       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7840
7841     // If the operand types disagree, extend the shift amount to match.  Since
7842     // BT ignores high bits (like shifts) we can use anyextend.
7843     if (LHS.getValueType() != RHS.getValueType())
7844       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7845
7846     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7847     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7848     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7849                        DAG.getConstant(Cond, MVT::i8), BT);
7850   }
7851
7852   return SDValue();
7853 }
7854
7855 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7856   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7857   SDValue Op0 = Op.getOperand(0);
7858   SDValue Op1 = Op.getOperand(1);
7859   DebugLoc dl = Op.getDebugLoc();
7860   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7861
7862   // Optimize to BT if possible.
7863   // Lower (X & (1 << N)) == 0 to BT(X, N).
7864   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7865   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7866   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7867       Op1.getOpcode() == ISD::Constant &&
7868       cast<ConstantSDNode>(Op1)->isNullValue() &&
7869       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7870     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7871     if (NewSetCC.getNode())
7872       return NewSetCC;
7873   }
7874
7875   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7876   // these.
7877   if (Op1.getOpcode() == ISD::Constant &&
7878       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7879        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7880       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7881
7882     // If the input is a setcc, then reuse the input setcc or use a new one with
7883     // the inverted condition.
7884     if (Op0.getOpcode() == X86ISD::SETCC) {
7885       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7886       bool Invert = (CC == ISD::SETNE) ^
7887         cast<ConstantSDNode>(Op1)->isNullValue();
7888       if (!Invert) return Op0;
7889
7890       CCode = X86::GetOppositeBranchCondition(CCode);
7891       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7892                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7893     }
7894   }
7895
7896   bool isFP = Op1.getValueType().isFloatingPoint();
7897   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7898   if (X86CC == X86::COND_INVALID)
7899     return SDValue();
7900
7901   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7902   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7903                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7904 }
7905
7906 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7907   SDValue Cond;
7908   SDValue Op0 = Op.getOperand(0);
7909   SDValue Op1 = Op.getOperand(1);
7910   SDValue CC = Op.getOperand(2);
7911   EVT VT = Op.getValueType();
7912   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7913   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7914   DebugLoc dl = Op.getDebugLoc();
7915
7916   if (isFP) {
7917     unsigned SSECC = 8;
7918     EVT EltVT = Op0.getValueType().getVectorElementType();
7919     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
7920
7921     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7922     bool Swap = false;
7923
7924     switch (SetCCOpcode) {
7925     default: break;
7926     case ISD::SETOEQ:
7927     case ISD::SETEQ:  SSECC = 0; break;
7928     case ISD::SETOGT:
7929     case ISD::SETGT: Swap = true; // Fallthrough
7930     case ISD::SETLT:
7931     case ISD::SETOLT: SSECC = 1; break;
7932     case ISD::SETOGE:
7933     case ISD::SETGE: Swap = true; // Fallthrough
7934     case ISD::SETLE:
7935     case ISD::SETOLE: SSECC = 2; break;
7936     case ISD::SETUO:  SSECC = 3; break;
7937     case ISD::SETUNE:
7938     case ISD::SETNE:  SSECC = 4; break;
7939     case ISD::SETULE: Swap = true;
7940     case ISD::SETUGE: SSECC = 5; break;
7941     case ISD::SETULT: Swap = true;
7942     case ISD::SETUGT: SSECC = 6; break;
7943     case ISD::SETO:   SSECC = 7; break;
7944     }
7945     if (Swap)
7946       std::swap(Op0, Op1);
7947
7948     // In the two special cases we can't handle, emit two comparisons.
7949     if (SSECC == 8) {
7950       if (SetCCOpcode == ISD::SETUEQ) {
7951         SDValue UNORD, EQ;
7952         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7953         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7954         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7955       }
7956       else if (SetCCOpcode == ISD::SETONE) {
7957         SDValue ORD, NEQ;
7958         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7959         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7960         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7961       }
7962       llvm_unreachable("Illegal FP comparison");
7963     }
7964     // Handle all other FP comparisons here.
7965     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7966   }
7967
7968   if (!isFP && VT.getSizeInBits() == 256)
7969     return SDValue();
7970
7971   // We are handling one of the integer comparisons here.  Since SSE only has
7972   // GT and EQ comparisons for integer, swapping operands and multiple
7973   // operations may be required for some comparisons.
7974   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7975   bool Swap = false, Invert = false, FlipSigns = false;
7976
7977   switch (VT.getSimpleVT().SimpleTy) {
7978   default: break;
7979   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7980   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7981   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7982   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7983   }
7984
7985   switch (SetCCOpcode) {
7986   default: break;
7987   case ISD::SETNE:  Invert = true;
7988   case ISD::SETEQ:  Opc = EQOpc; break;
7989   case ISD::SETLT:  Swap = true;
7990   case ISD::SETGT:  Opc = GTOpc; break;
7991   case ISD::SETGE:  Swap = true;
7992   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7993   case ISD::SETULT: Swap = true;
7994   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7995   case ISD::SETUGE: Swap = true;
7996   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7997   }
7998   if (Swap)
7999     std::swap(Op0, Op1);
8000
8001   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8002   // bits of the inputs before performing those operations.
8003   if (FlipSigns) {
8004     EVT EltVT = VT.getVectorElementType();
8005     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8006                                       EltVT);
8007     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8008     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8009                                     SignBits.size());
8010     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8011     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8012   }
8013
8014   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8015
8016   // If the logical-not of the result is required, perform that now.
8017   if (Invert)
8018     Result = DAG.getNOT(dl, Result, VT);
8019
8020   return Result;
8021 }
8022
8023 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8024 static bool isX86LogicalCmp(SDValue Op) {
8025   unsigned Opc = Op.getNode()->getOpcode();
8026   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8027     return true;
8028   if (Op.getResNo() == 1 &&
8029       (Opc == X86ISD::ADD ||
8030        Opc == X86ISD::SUB ||
8031        Opc == X86ISD::ADC ||
8032        Opc == X86ISD::SBB ||
8033        Opc == X86ISD::SMUL ||
8034        Opc == X86ISD::UMUL ||
8035        Opc == X86ISD::INC ||
8036        Opc == X86ISD::DEC ||
8037        Opc == X86ISD::OR ||
8038        Opc == X86ISD::XOR ||
8039        Opc == X86ISD::AND))
8040     return true;
8041
8042   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8043     return true;
8044
8045   return false;
8046 }
8047
8048 static bool isZero(SDValue V) {
8049   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8050   return C && C->isNullValue();
8051 }
8052
8053 static bool isAllOnes(SDValue V) {
8054   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8055   return C && C->isAllOnesValue();
8056 }
8057
8058 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8059   bool addTest = true;
8060   SDValue Cond  = Op.getOperand(0);
8061   SDValue Op1 = Op.getOperand(1);
8062   SDValue Op2 = Op.getOperand(2);
8063   DebugLoc DL = Op.getDebugLoc();
8064   SDValue CC;
8065
8066   if (Cond.getOpcode() == ISD::SETCC) {
8067     SDValue NewCond = LowerSETCC(Cond, DAG);
8068     if (NewCond.getNode())
8069       Cond = NewCond;
8070   }
8071
8072   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8073   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8074   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8075   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8076   if (Cond.getOpcode() == X86ISD::SETCC &&
8077       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8078       isZero(Cond.getOperand(1).getOperand(1))) {
8079     SDValue Cmp = Cond.getOperand(1);
8080
8081     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8082
8083     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8084         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8085       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8086
8087       SDValue CmpOp0 = Cmp.getOperand(0);
8088       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8089                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8090
8091       SDValue Res =   // Res = 0 or -1.
8092         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8093                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8094
8095       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8096         Res = DAG.getNOT(DL, Res, Res.getValueType());
8097
8098       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8099       if (N2C == 0 || !N2C->isNullValue())
8100         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8101       return Res;
8102     }
8103   }
8104
8105   // Look past (and (setcc_carry (cmp ...)), 1).
8106   if (Cond.getOpcode() == ISD::AND &&
8107       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8108     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8109     if (C && C->getAPIntValue() == 1)
8110       Cond = Cond.getOperand(0);
8111   }
8112
8113   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8114   // setting operand in place of the X86ISD::SETCC.
8115   if (Cond.getOpcode() == X86ISD::SETCC ||
8116       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8117     CC = Cond.getOperand(0);
8118
8119     SDValue Cmp = Cond.getOperand(1);
8120     unsigned Opc = Cmp.getOpcode();
8121     EVT VT = Op.getValueType();
8122
8123     bool IllegalFPCMov = false;
8124     if (VT.isFloatingPoint() && !VT.isVector() &&
8125         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8126       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8127
8128     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8129         Opc == X86ISD::BT) { // FIXME
8130       Cond = Cmp;
8131       addTest = false;
8132     }
8133   }
8134
8135   if (addTest) {
8136     // Look pass the truncate.
8137     if (Cond.getOpcode() == ISD::TRUNCATE)
8138       Cond = Cond.getOperand(0);
8139
8140     // We know the result of AND is compared against zero. Try to match
8141     // it to BT.
8142     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8143       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8144       if (NewSetCC.getNode()) {
8145         CC = NewSetCC.getOperand(0);
8146         Cond = NewSetCC.getOperand(1);
8147         addTest = false;
8148       }
8149     }
8150   }
8151
8152   if (addTest) {
8153     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8154     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8155   }
8156
8157   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8158   // a <  b ?  0 : -1 -> RES = setcc_carry
8159   // a >= b ? -1 :  0 -> RES = setcc_carry
8160   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8161   if (Cond.getOpcode() == X86ISD::CMP) {
8162     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8163
8164     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8165         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8166       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8167                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8168       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8169         return DAG.getNOT(DL, Res, Res.getValueType());
8170       return Res;
8171     }
8172   }
8173
8174   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8175   // condition is true.
8176   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8177   SDValue Ops[] = { Op2, Op1, CC, Cond };
8178   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8179 }
8180
8181 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8182 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8183 // from the AND / OR.
8184 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8185   Opc = Op.getOpcode();
8186   if (Opc != ISD::OR && Opc != ISD::AND)
8187     return false;
8188   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8189           Op.getOperand(0).hasOneUse() &&
8190           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8191           Op.getOperand(1).hasOneUse());
8192 }
8193
8194 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8195 // 1 and that the SETCC node has a single use.
8196 static bool isXor1OfSetCC(SDValue Op) {
8197   if (Op.getOpcode() != ISD::XOR)
8198     return false;
8199   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8200   if (N1C && N1C->getAPIntValue() == 1) {
8201     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8202       Op.getOperand(0).hasOneUse();
8203   }
8204   return false;
8205 }
8206
8207 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8208   bool addTest = true;
8209   SDValue Chain = Op.getOperand(0);
8210   SDValue Cond  = Op.getOperand(1);
8211   SDValue Dest  = Op.getOperand(2);
8212   DebugLoc dl = Op.getDebugLoc();
8213   SDValue CC;
8214
8215   if (Cond.getOpcode() == ISD::SETCC) {
8216     SDValue NewCond = LowerSETCC(Cond, DAG);
8217     if (NewCond.getNode())
8218       Cond = NewCond;
8219   }
8220 #if 0
8221   // FIXME: LowerXALUO doesn't handle these!!
8222   else if (Cond.getOpcode() == X86ISD::ADD  ||
8223            Cond.getOpcode() == X86ISD::SUB  ||
8224            Cond.getOpcode() == X86ISD::SMUL ||
8225            Cond.getOpcode() == X86ISD::UMUL)
8226     Cond = LowerXALUO(Cond, DAG);
8227 #endif
8228
8229   // Look pass (and (setcc_carry (cmp ...)), 1).
8230   if (Cond.getOpcode() == ISD::AND &&
8231       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8232     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8233     if (C && C->getAPIntValue() == 1)
8234       Cond = Cond.getOperand(0);
8235   }
8236
8237   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8238   // setting operand in place of the X86ISD::SETCC.
8239   if (Cond.getOpcode() == X86ISD::SETCC ||
8240       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8241     CC = Cond.getOperand(0);
8242
8243     SDValue Cmp = Cond.getOperand(1);
8244     unsigned Opc = Cmp.getOpcode();
8245     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8246     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8247       Cond = Cmp;
8248       addTest = false;
8249     } else {
8250       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8251       default: break;
8252       case X86::COND_O:
8253       case X86::COND_B:
8254         // These can only come from an arithmetic instruction with overflow,
8255         // e.g. SADDO, UADDO.
8256         Cond = Cond.getNode()->getOperand(1);
8257         addTest = false;
8258         break;
8259       }
8260     }
8261   } else {
8262     unsigned CondOpc;
8263     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8264       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8265       if (CondOpc == ISD::OR) {
8266         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8267         // two branches instead of an explicit OR instruction with a
8268         // separate test.
8269         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8270             isX86LogicalCmp(Cmp)) {
8271           CC = Cond.getOperand(0).getOperand(0);
8272           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8273                               Chain, Dest, CC, Cmp);
8274           CC = Cond.getOperand(1).getOperand(0);
8275           Cond = Cmp;
8276           addTest = false;
8277         }
8278       } else { // ISD::AND
8279         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8280         // two branches instead of an explicit AND instruction with a
8281         // separate test. However, we only do this if this block doesn't
8282         // have a fall-through edge, because this requires an explicit
8283         // jmp when the condition is false.
8284         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8285             isX86LogicalCmp(Cmp) &&
8286             Op.getNode()->hasOneUse()) {
8287           X86::CondCode CCode =
8288             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8289           CCode = X86::GetOppositeBranchCondition(CCode);
8290           CC = DAG.getConstant(CCode, MVT::i8);
8291           SDNode *User = *Op.getNode()->use_begin();
8292           // Look for an unconditional branch following this conditional branch.
8293           // We need this because we need to reverse the successors in order
8294           // to implement FCMP_OEQ.
8295           if (User->getOpcode() == ISD::BR) {
8296             SDValue FalseBB = User->getOperand(1);
8297             SDNode *NewBR =
8298               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8299             assert(NewBR == User);
8300             (void)NewBR;
8301             Dest = FalseBB;
8302
8303             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8304                                 Chain, Dest, CC, Cmp);
8305             X86::CondCode CCode =
8306               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8307             CCode = X86::GetOppositeBranchCondition(CCode);
8308             CC = DAG.getConstant(CCode, MVT::i8);
8309             Cond = Cmp;
8310             addTest = false;
8311           }
8312         }
8313       }
8314     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8315       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8316       // It should be transformed during dag combiner except when the condition
8317       // is set by a arithmetics with overflow node.
8318       X86::CondCode CCode =
8319         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8320       CCode = X86::GetOppositeBranchCondition(CCode);
8321       CC = DAG.getConstant(CCode, MVT::i8);
8322       Cond = Cond.getOperand(0).getOperand(1);
8323       addTest = false;
8324     }
8325   }
8326
8327   if (addTest) {
8328     // Look pass the truncate.
8329     if (Cond.getOpcode() == ISD::TRUNCATE)
8330       Cond = Cond.getOperand(0);
8331
8332     // We know the result of AND is compared against zero. Try to match
8333     // it to BT.
8334     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8335       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8336       if (NewSetCC.getNode()) {
8337         CC = NewSetCC.getOperand(0);
8338         Cond = NewSetCC.getOperand(1);
8339         addTest = false;
8340       }
8341     }
8342   }
8343
8344   if (addTest) {
8345     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8346     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8347   }
8348   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8349                      Chain, Dest, CC, Cond);
8350 }
8351
8352
8353 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8354 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8355 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8356 // that the guard pages used by the OS virtual memory manager are allocated in
8357 // correct sequence.
8358 SDValue
8359 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8360                                            SelectionDAG &DAG) const {
8361   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8362          "This should be used only on Windows targets");
8363   assert(!Subtarget->isTargetEnvMacho());
8364   DebugLoc dl = Op.getDebugLoc();
8365
8366   // Get the inputs.
8367   SDValue Chain = Op.getOperand(0);
8368   SDValue Size  = Op.getOperand(1);
8369   // FIXME: Ensure alignment here
8370
8371   SDValue Flag;
8372
8373   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8374   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8375
8376   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8377   Flag = Chain.getValue(1);
8378
8379   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8380
8381   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8382   Flag = Chain.getValue(1);
8383
8384   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8385
8386   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8387   return DAG.getMergeValues(Ops1, 2, dl);
8388 }
8389
8390 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8391   MachineFunction &MF = DAG.getMachineFunction();
8392   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8393
8394   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8395   DebugLoc DL = Op.getDebugLoc();
8396
8397   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8398     // vastart just stores the address of the VarArgsFrameIndex slot into the
8399     // memory location argument.
8400     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8401                                    getPointerTy());
8402     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8403                         MachinePointerInfo(SV), false, false, 0);
8404   }
8405
8406   // __va_list_tag:
8407   //   gp_offset         (0 - 6 * 8)
8408   //   fp_offset         (48 - 48 + 8 * 16)
8409   //   overflow_arg_area (point to parameters coming in memory).
8410   //   reg_save_area
8411   SmallVector<SDValue, 8> MemOps;
8412   SDValue FIN = Op.getOperand(1);
8413   // Store gp_offset
8414   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8415                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8416                                                MVT::i32),
8417                                FIN, MachinePointerInfo(SV), false, false, 0);
8418   MemOps.push_back(Store);
8419
8420   // Store fp_offset
8421   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8422                     FIN, DAG.getIntPtrConstant(4));
8423   Store = DAG.getStore(Op.getOperand(0), DL,
8424                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8425                                        MVT::i32),
8426                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8427   MemOps.push_back(Store);
8428
8429   // Store ptr to overflow_arg_area
8430   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8431                     FIN, DAG.getIntPtrConstant(4));
8432   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8433                                     getPointerTy());
8434   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8435                        MachinePointerInfo(SV, 8),
8436                        false, false, 0);
8437   MemOps.push_back(Store);
8438
8439   // Store ptr to reg_save_area.
8440   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8441                     FIN, DAG.getIntPtrConstant(8));
8442   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8443                                     getPointerTy());
8444   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8445                        MachinePointerInfo(SV, 16), false, false, 0);
8446   MemOps.push_back(Store);
8447   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8448                      &MemOps[0], MemOps.size());
8449 }
8450
8451 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8452   assert(Subtarget->is64Bit() &&
8453          "LowerVAARG only handles 64-bit va_arg!");
8454   assert((Subtarget->isTargetLinux() ||
8455           Subtarget->isTargetDarwin()) &&
8456           "Unhandled target in LowerVAARG");
8457   assert(Op.getNode()->getNumOperands() == 4);
8458   SDValue Chain = Op.getOperand(0);
8459   SDValue SrcPtr = Op.getOperand(1);
8460   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8461   unsigned Align = Op.getConstantOperandVal(3);
8462   DebugLoc dl = Op.getDebugLoc();
8463
8464   EVT ArgVT = Op.getNode()->getValueType(0);
8465   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8466   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8467   uint8_t ArgMode;
8468
8469   // Decide which area this value should be read from.
8470   // TODO: Implement the AMD64 ABI in its entirety. This simple
8471   // selection mechanism works only for the basic types.
8472   if (ArgVT == MVT::f80) {
8473     llvm_unreachable("va_arg for f80 not yet implemented");
8474   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8475     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8476   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8477     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8478   } else {
8479     llvm_unreachable("Unhandled argument type in LowerVAARG");
8480   }
8481
8482   if (ArgMode == 2) {
8483     // Sanity Check: Make sure using fp_offset makes sense.
8484     assert(!UseSoftFloat &&
8485            !(DAG.getMachineFunction()
8486                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8487            Subtarget->hasXMM());
8488   }
8489
8490   // Insert VAARG_64 node into the DAG
8491   // VAARG_64 returns two values: Variable Argument Address, Chain
8492   SmallVector<SDValue, 11> InstOps;
8493   InstOps.push_back(Chain);
8494   InstOps.push_back(SrcPtr);
8495   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8496   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8497   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8498   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8499   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8500                                           VTs, &InstOps[0], InstOps.size(),
8501                                           MVT::i64,
8502                                           MachinePointerInfo(SV),
8503                                           /*Align=*/0,
8504                                           /*Volatile=*/false,
8505                                           /*ReadMem=*/true,
8506                                           /*WriteMem=*/true);
8507   Chain = VAARG.getValue(1);
8508
8509   // Load the next argument and return it
8510   return DAG.getLoad(ArgVT, dl,
8511                      Chain,
8512                      VAARG,
8513                      MachinePointerInfo(),
8514                      false, false, 0);
8515 }
8516
8517 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8518   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8519   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8520   SDValue Chain = Op.getOperand(0);
8521   SDValue DstPtr = Op.getOperand(1);
8522   SDValue SrcPtr = Op.getOperand(2);
8523   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8524   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8525   DebugLoc DL = Op.getDebugLoc();
8526
8527   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8528                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8529                        false,
8530                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8531 }
8532
8533 SDValue
8534 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8535   DebugLoc dl = Op.getDebugLoc();
8536   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8537   switch (IntNo) {
8538   default: return SDValue();    // Don't custom lower most intrinsics.
8539   // Comparison intrinsics.
8540   case Intrinsic::x86_sse_comieq_ss:
8541   case Intrinsic::x86_sse_comilt_ss:
8542   case Intrinsic::x86_sse_comile_ss:
8543   case Intrinsic::x86_sse_comigt_ss:
8544   case Intrinsic::x86_sse_comige_ss:
8545   case Intrinsic::x86_sse_comineq_ss:
8546   case Intrinsic::x86_sse_ucomieq_ss:
8547   case Intrinsic::x86_sse_ucomilt_ss:
8548   case Intrinsic::x86_sse_ucomile_ss:
8549   case Intrinsic::x86_sse_ucomigt_ss:
8550   case Intrinsic::x86_sse_ucomige_ss:
8551   case Intrinsic::x86_sse_ucomineq_ss:
8552   case Intrinsic::x86_sse2_comieq_sd:
8553   case Intrinsic::x86_sse2_comilt_sd:
8554   case Intrinsic::x86_sse2_comile_sd:
8555   case Intrinsic::x86_sse2_comigt_sd:
8556   case Intrinsic::x86_sse2_comige_sd:
8557   case Intrinsic::x86_sse2_comineq_sd:
8558   case Intrinsic::x86_sse2_ucomieq_sd:
8559   case Intrinsic::x86_sse2_ucomilt_sd:
8560   case Intrinsic::x86_sse2_ucomile_sd:
8561   case Intrinsic::x86_sse2_ucomigt_sd:
8562   case Intrinsic::x86_sse2_ucomige_sd:
8563   case Intrinsic::x86_sse2_ucomineq_sd: {
8564     unsigned Opc = 0;
8565     ISD::CondCode CC = ISD::SETCC_INVALID;
8566     switch (IntNo) {
8567     default: break;
8568     case Intrinsic::x86_sse_comieq_ss:
8569     case Intrinsic::x86_sse2_comieq_sd:
8570       Opc = X86ISD::COMI;
8571       CC = ISD::SETEQ;
8572       break;
8573     case Intrinsic::x86_sse_comilt_ss:
8574     case Intrinsic::x86_sse2_comilt_sd:
8575       Opc = X86ISD::COMI;
8576       CC = ISD::SETLT;
8577       break;
8578     case Intrinsic::x86_sse_comile_ss:
8579     case Intrinsic::x86_sse2_comile_sd:
8580       Opc = X86ISD::COMI;
8581       CC = ISD::SETLE;
8582       break;
8583     case Intrinsic::x86_sse_comigt_ss:
8584     case Intrinsic::x86_sse2_comigt_sd:
8585       Opc = X86ISD::COMI;
8586       CC = ISD::SETGT;
8587       break;
8588     case Intrinsic::x86_sse_comige_ss:
8589     case Intrinsic::x86_sse2_comige_sd:
8590       Opc = X86ISD::COMI;
8591       CC = ISD::SETGE;
8592       break;
8593     case Intrinsic::x86_sse_comineq_ss:
8594     case Intrinsic::x86_sse2_comineq_sd:
8595       Opc = X86ISD::COMI;
8596       CC = ISD::SETNE;
8597       break;
8598     case Intrinsic::x86_sse_ucomieq_ss:
8599     case Intrinsic::x86_sse2_ucomieq_sd:
8600       Opc = X86ISD::UCOMI;
8601       CC = ISD::SETEQ;
8602       break;
8603     case Intrinsic::x86_sse_ucomilt_ss:
8604     case Intrinsic::x86_sse2_ucomilt_sd:
8605       Opc = X86ISD::UCOMI;
8606       CC = ISD::SETLT;
8607       break;
8608     case Intrinsic::x86_sse_ucomile_ss:
8609     case Intrinsic::x86_sse2_ucomile_sd:
8610       Opc = X86ISD::UCOMI;
8611       CC = ISD::SETLE;
8612       break;
8613     case Intrinsic::x86_sse_ucomigt_ss:
8614     case Intrinsic::x86_sse2_ucomigt_sd:
8615       Opc = X86ISD::UCOMI;
8616       CC = ISD::SETGT;
8617       break;
8618     case Intrinsic::x86_sse_ucomige_ss:
8619     case Intrinsic::x86_sse2_ucomige_sd:
8620       Opc = X86ISD::UCOMI;
8621       CC = ISD::SETGE;
8622       break;
8623     case Intrinsic::x86_sse_ucomineq_ss:
8624     case Intrinsic::x86_sse2_ucomineq_sd:
8625       Opc = X86ISD::UCOMI;
8626       CC = ISD::SETNE;
8627       break;
8628     }
8629
8630     SDValue LHS = Op.getOperand(1);
8631     SDValue RHS = Op.getOperand(2);
8632     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8633     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8634     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8635     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8636                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8637     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8638   }
8639   // ptest and testp intrinsics. The intrinsic these come from are designed to
8640   // return an integer value, not just an instruction so lower it to the ptest
8641   // or testp pattern and a setcc for the result.
8642   case Intrinsic::x86_sse41_ptestz:
8643   case Intrinsic::x86_sse41_ptestc:
8644   case Intrinsic::x86_sse41_ptestnzc:
8645   case Intrinsic::x86_avx_ptestz_256:
8646   case Intrinsic::x86_avx_ptestc_256:
8647   case Intrinsic::x86_avx_ptestnzc_256:
8648   case Intrinsic::x86_avx_vtestz_ps:
8649   case Intrinsic::x86_avx_vtestc_ps:
8650   case Intrinsic::x86_avx_vtestnzc_ps:
8651   case Intrinsic::x86_avx_vtestz_pd:
8652   case Intrinsic::x86_avx_vtestc_pd:
8653   case Intrinsic::x86_avx_vtestnzc_pd:
8654   case Intrinsic::x86_avx_vtestz_ps_256:
8655   case Intrinsic::x86_avx_vtestc_ps_256:
8656   case Intrinsic::x86_avx_vtestnzc_ps_256:
8657   case Intrinsic::x86_avx_vtestz_pd_256:
8658   case Intrinsic::x86_avx_vtestc_pd_256:
8659   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8660     bool IsTestPacked = false;
8661     unsigned X86CC = 0;
8662     switch (IntNo) {
8663     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8664     case Intrinsic::x86_avx_vtestz_ps:
8665     case Intrinsic::x86_avx_vtestz_pd:
8666     case Intrinsic::x86_avx_vtestz_ps_256:
8667     case Intrinsic::x86_avx_vtestz_pd_256:
8668       IsTestPacked = true; // Fallthrough
8669     case Intrinsic::x86_sse41_ptestz:
8670     case Intrinsic::x86_avx_ptestz_256:
8671       // ZF = 1
8672       X86CC = X86::COND_E;
8673       break;
8674     case Intrinsic::x86_avx_vtestc_ps:
8675     case Intrinsic::x86_avx_vtestc_pd:
8676     case Intrinsic::x86_avx_vtestc_ps_256:
8677     case Intrinsic::x86_avx_vtestc_pd_256:
8678       IsTestPacked = true; // Fallthrough
8679     case Intrinsic::x86_sse41_ptestc:
8680     case Intrinsic::x86_avx_ptestc_256:
8681       // CF = 1
8682       X86CC = X86::COND_B;
8683       break;
8684     case Intrinsic::x86_avx_vtestnzc_ps:
8685     case Intrinsic::x86_avx_vtestnzc_pd:
8686     case Intrinsic::x86_avx_vtestnzc_ps_256:
8687     case Intrinsic::x86_avx_vtestnzc_pd_256:
8688       IsTestPacked = true; // Fallthrough
8689     case Intrinsic::x86_sse41_ptestnzc:
8690     case Intrinsic::x86_avx_ptestnzc_256:
8691       // ZF and CF = 0
8692       X86CC = X86::COND_A;
8693       break;
8694     }
8695
8696     SDValue LHS = Op.getOperand(1);
8697     SDValue RHS = Op.getOperand(2);
8698     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8699     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8700     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8701     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8702     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8703   }
8704
8705   // Fix vector shift instructions where the last operand is a non-immediate
8706   // i32 value.
8707   case Intrinsic::x86_sse2_pslli_w:
8708   case Intrinsic::x86_sse2_pslli_d:
8709   case Intrinsic::x86_sse2_pslli_q:
8710   case Intrinsic::x86_sse2_psrli_w:
8711   case Intrinsic::x86_sse2_psrli_d:
8712   case Intrinsic::x86_sse2_psrli_q:
8713   case Intrinsic::x86_sse2_psrai_w:
8714   case Intrinsic::x86_sse2_psrai_d:
8715   case Intrinsic::x86_mmx_pslli_w:
8716   case Intrinsic::x86_mmx_pslli_d:
8717   case Intrinsic::x86_mmx_pslli_q:
8718   case Intrinsic::x86_mmx_psrli_w:
8719   case Intrinsic::x86_mmx_psrli_d:
8720   case Intrinsic::x86_mmx_psrli_q:
8721   case Intrinsic::x86_mmx_psrai_w:
8722   case Intrinsic::x86_mmx_psrai_d: {
8723     SDValue ShAmt = Op.getOperand(2);
8724     if (isa<ConstantSDNode>(ShAmt))
8725       return SDValue();
8726
8727     unsigned NewIntNo = 0;
8728     EVT ShAmtVT = MVT::v4i32;
8729     switch (IntNo) {
8730     case Intrinsic::x86_sse2_pslli_w:
8731       NewIntNo = Intrinsic::x86_sse2_psll_w;
8732       break;
8733     case Intrinsic::x86_sse2_pslli_d:
8734       NewIntNo = Intrinsic::x86_sse2_psll_d;
8735       break;
8736     case Intrinsic::x86_sse2_pslli_q:
8737       NewIntNo = Intrinsic::x86_sse2_psll_q;
8738       break;
8739     case Intrinsic::x86_sse2_psrli_w:
8740       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8741       break;
8742     case Intrinsic::x86_sse2_psrli_d:
8743       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8744       break;
8745     case Intrinsic::x86_sse2_psrli_q:
8746       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8747       break;
8748     case Intrinsic::x86_sse2_psrai_w:
8749       NewIntNo = Intrinsic::x86_sse2_psra_w;
8750       break;
8751     case Intrinsic::x86_sse2_psrai_d:
8752       NewIntNo = Intrinsic::x86_sse2_psra_d;
8753       break;
8754     default: {
8755       ShAmtVT = MVT::v2i32;
8756       switch (IntNo) {
8757       case Intrinsic::x86_mmx_pslli_w:
8758         NewIntNo = Intrinsic::x86_mmx_psll_w;
8759         break;
8760       case Intrinsic::x86_mmx_pslli_d:
8761         NewIntNo = Intrinsic::x86_mmx_psll_d;
8762         break;
8763       case Intrinsic::x86_mmx_pslli_q:
8764         NewIntNo = Intrinsic::x86_mmx_psll_q;
8765         break;
8766       case Intrinsic::x86_mmx_psrli_w:
8767         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8768         break;
8769       case Intrinsic::x86_mmx_psrli_d:
8770         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8771         break;
8772       case Intrinsic::x86_mmx_psrli_q:
8773         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8774         break;
8775       case Intrinsic::x86_mmx_psrai_w:
8776         NewIntNo = Intrinsic::x86_mmx_psra_w;
8777         break;
8778       case Intrinsic::x86_mmx_psrai_d:
8779         NewIntNo = Intrinsic::x86_mmx_psra_d;
8780         break;
8781       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8782       }
8783       break;
8784     }
8785     }
8786
8787     // The vector shift intrinsics with scalars uses 32b shift amounts but
8788     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8789     // to be zero.
8790     SDValue ShOps[4];
8791     ShOps[0] = ShAmt;
8792     ShOps[1] = DAG.getConstant(0, MVT::i32);
8793     if (ShAmtVT == MVT::v4i32) {
8794       ShOps[2] = DAG.getUNDEF(MVT::i32);
8795       ShOps[3] = DAG.getUNDEF(MVT::i32);
8796       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8797     } else {
8798       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8799 // FIXME this must be lowered to get rid of the invalid type.
8800     }
8801
8802     EVT VT = Op.getValueType();
8803     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8804     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8805                        DAG.getConstant(NewIntNo, MVT::i32),
8806                        Op.getOperand(1), ShAmt);
8807   }
8808   }
8809 }
8810
8811 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8812                                            SelectionDAG &DAG) const {
8813   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8814   MFI->setReturnAddressIsTaken(true);
8815
8816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8817   DebugLoc dl = Op.getDebugLoc();
8818
8819   if (Depth > 0) {
8820     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8821     SDValue Offset =
8822       DAG.getConstant(TD->getPointerSize(),
8823                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8824     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8825                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8826                                    FrameAddr, Offset),
8827                        MachinePointerInfo(), false, false, 0);
8828   }
8829
8830   // Just load the return address.
8831   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8832   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8833                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8834 }
8835
8836 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8837   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8838   MFI->setFrameAddressIsTaken(true);
8839
8840   EVT VT = Op.getValueType();
8841   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8842   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8843   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8844   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8845   while (Depth--)
8846     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8847                             MachinePointerInfo(),
8848                             false, false, 0);
8849   return FrameAddr;
8850 }
8851
8852 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8853                                                      SelectionDAG &DAG) const {
8854   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8855 }
8856
8857 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8858   MachineFunction &MF = DAG.getMachineFunction();
8859   SDValue Chain     = Op.getOperand(0);
8860   SDValue Offset    = Op.getOperand(1);
8861   SDValue Handler   = Op.getOperand(2);
8862   DebugLoc dl       = Op.getDebugLoc();
8863
8864   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8865                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8866                                      getPointerTy());
8867   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8868
8869   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8870                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8871   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8872   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8873                        false, false, 0);
8874   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8875   MF.getRegInfo().addLiveOut(StoreAddrReg);
8876
8877   return DAG.getNode(X86ISD::EH_RETURN, dl,
8878                      MVT::Other,
8879                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8880 }
8881
8882 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8883                                              SelectionDAG &DAG) const {
8884   SDValue Root = Op.getOperand(0);
8885   SDValue Trmp = Op.getOperand(1); // trampoline
8886   SDValue FPtr = Op.getOperand(2); // nested function
8887   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8888   DebugLoc dl  = Op.getDebugLoc();
8889
8890   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8891
8892   if (Subtarget->is64Bit()) {
8893     SDValue OutChains[6];
8894
8895     // Large code-model.
8896     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8897     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8898
8899     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8900     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8901
8902     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8903
8904     // Load the pointer to the nested function into R11.
8905     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8906     SDValue Addr = Trmp;
8907     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8908                                 Addr, MachinePointerInfo(TrmpAddr),
8909                                 false, false, 0);
8910
8911     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8912                        DAG.getConstant(2, MVT::i64));
8913     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8914                                 MachinePointerInfo(TrmpAddr, 2),
8915                                 false, false, 2);
8916
8917     // Load the 'nest' parameter value into R10.
8918     // R10 is specified in X86CallingConv.td
8919     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8920     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8921                        DAG.getConstant(10, MVT::i64));
8922     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8923                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8924                                 false, false, 0);
8925
8926     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8927                        DAG.getConstant(12, MVT::i64));
8928     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8929                                 MachinePointerInfo(TrmpAddr, 12),
8930                                 false, false, 2);
8931
8932     // Jump to the nested function.
8933     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8934     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8935                        DAG.getConstant(20, MVT::i64));
8936     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8937                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8938                                 false, false, 0);
8939
8940     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8941     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8942                        DAG.getConstant(22, MVT::i64));
8943     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8944                                 MachinePointerInfo(TrmpAddr, 22),
8945                                 false, false, 0);
8946
8947     SDValue Ops[] =
8948       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8949     return DAG.getMergeValues(Ops, 2, dl);
8950   } else {
8951     const Function *Func =
8952       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8953     CallingConv::ID CC = Func->getCallingConv();
8954     unsigned NestReg;
8955
8956     switch (CC) {
8957     default:
8958       llvm_unreachable("Unsupported calling convention");
8959     case CallingConv::C:
8960     case CallingConv::X86_StdCall: {
8961       // Pass 'nest' parameter in ECX.
8962       // Must be kept in sync with X86CallingConv.td
8963       NestReg = X86::ECX;
8964
8965       // Check that ECX wasn't needed by an 'inreg' parameter.
8966       FunctionType *FTy = Func->getFunctionType();
8967       const AttrListPtr &Attrs = Func->getAttributes();
8968
8969       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8970         unsigned InRegCount = 0;
8971         unsigned Idx = 1;
8972
8973         for (FunctionType::param_iterator I = FTy->param_begin(),
8974              E = FTy->param_end(); I != E; ++I, ++Idx)
8975           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8976             // FIXME: should only count parameters that are lowered to integers.
8977             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8978
8979         if (InRegCount > 2) {
8980           report_fatal_error("Nest register in use - reduce number of inreg"
8981                              " parameters!");
8982         }
8983       }
8984       break;
8985     }
8986     case CallingConv::X86_FastCall:
8987     case CallingConv::X86_ThisCall:
8988     case CallingConv::Fast:
8989       // Pass 'nest' parameter in EAX.
8990       // Must be kept in sync with X86CallingConv.td
8991       NestReg = X86::EAX;
8992       break;
8993     }
8994
8995     SDValue OutChains[4];
8996     SDValue Addr, Disp;
8997
8998     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8999                        DAG.getConstant(10, MVT::i32));
9000     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9001
9002     // This is storing the opcode for MOV32ri.
9003     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9004     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9005     OutChains[0] = DAG.getStore(Root, dl,
9006                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9007                                 Trmp, MachinePointerInfo(TrmpAddr),
9008                                 false, false, 0);
9009
9010     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9011                        DAG.getConstant(1, MVT::i32));
9012     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9013                                 MachinePointerInfo(TrmpAddr, 1),
9014                                 false, false, 1);
9015
9016     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9017     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9018                        DAG.getConstant(5, MVT::i32));
9019     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9020                                 MachinePointerInfo(TrmpAddr, 5),
9021                                 false, false, 1);
9022
9023     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9024                        DAG.getConstant(6, MVT::i32));
9025     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9026                                 MachinePointerInfo(TrmpAddr, 6),
9027                                 false, false, 1);
9028
9029     SDValue Ops[] =
9030       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
9031     return DAG.getMergeValues(Ops, 2, dl);
9032   }
9033 }
9034
9035 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9036                                             SelectionDAG &DAG) const {
9037   /*
9038    The rounding mode is in bits 11:10 of FPSR, and has the following
9039    settings:
9040      00 Round to nearest
9041      01 Round to -inf
9042      10 Round to +inf
9043      11 Round to 0
9044
9045   FLT_ROUNDS, on the other hand, expects the following:
9046     -1 Undefined
9047      0 Round to 0
9048      1 Round to nearest
9049      2 Round to +inf
9050      3 Round to -inf
9051
9052   To perform the conversion, we do:
9053     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9054   */
9055
9056   MachineFunction &MF = DAG.getMachineFunction();
9057   const TargetMachine &TM = MF.getTarget();
9058   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9059   unsigned StackAlignment = TFI.getStackAlignment();
9060   EVT VT = Op.getValueType();
9061   DebugLoc DL = Op.getDebugLoc();
9062
9063   // Save FP Control Word to stack slot
9064   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9065   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9066
9067
9068   MachineMemOperand *MMO =
9069    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9070                            MachineMemOperand::MOStore, 2, 2);
9071
9072   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9073   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9074                                           DAG.getVTList(MVT::Other),
9075                                           Ops, 2, MVT::i16, MMO);
9076
9077   // Load FP Control Word from stack slot
9078   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9079                             MachinePointerInfo(), false, false, 0);
9080
9081   // Transform as necessary
9082   SDValue CWD1 =
9083     DAG.getNode(ISD::SRL, DL, MVT::i16,
9084                 DAG.getNode(ISD::AND, DL, MVT::i16,
9085                             CWD, DAG.getConstant(0x800, MVT::i16)),
9086                 DAG.getConstant(11, MVT::i8));
9087   SDValue CWD2 =
9088     DAG.getNode(ISD::SRL, DL, MVT::i16,
9089                 DAG.getNode(ISD::AND, DL, MVT::i16,
9090                             CWD, DAG.getConstant(0x400, MVT::i16)),
9091                 DAG.getConstant(9, MVT::i8));
9092
9093   SDValue RetVal =
9094     DAG.getNode(ISD::AND, DL, MVT::i16,
9095                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9096                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9097                             DAG.getConstant(1, MVT::i16)),
9098                 DAG.getConstant(3, MVT::i16));
9099
9100
9101   return DAG.getNode((VT.getSizeInBits() < 16 ?
9102                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9103 }
9104
9105 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9106   EVT VT = Op.getValueType();
9107   EVT OpVT = VT;
9108   unsigned NumBits = VT.getSizeInBits();
9109   DebugLoc dl = Op.getDebugLoc();
9110
9111   Op = Op.getOperand(0);
9112   if (VT == MVT::i8) {
9113     // Zero extend to i32 since there is not an i8 bsr.
9114     OpVT = MVT::i32;
9115     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9116   }
9117
9118   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9119   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9120   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9121
9122   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9123   SDValue Ops[] = {
9124     Op,
9125     DAG.getConstant(NumBits+NumBits-1, OpVT),
9126     DAG.getConstant(X86::COND_E, MVT::i8),
9127     Op.getValue(1)
9128   };
9129   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9130
9131   // Finally xor with NumBits-1.
9132   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9133
9134   if (VT == MVT::i8)
9135     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9136   return Op;
9137 }
9138
9139 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9140   EVT VT = Op.getValueType();
9141   EVT OpVT = VT;
9142   unsigned NumBits = VT.getSizeInBits();
9143   DebugLoc dl = Op.getDebugLoc();
9144
9145   Op = Op.getOperand(0);
9146   if (VT == MVT::i8) {
9147     OpVT = MVT::i32;
9148     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9149   }
9150
9151   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9152   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9153   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9154
9155   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9156   SDValue Ops[] = {
9157     Op,
9158     DAG.getConstant(NumBits, OpVT),
9159     DAG.getConstant(X86::COND_E, MVT::i8),
9160     Op.getValue(1)
9161   };
9162   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9163
9164   if (VT == MVT::i8)
9165     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9166   return Op;
9167 }
9168
9169 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
9170   EVT VT = Op.getValueType();
9171   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9172   DebugLoc dl = Op.getDebugLoc();
9173
9174   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9175   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9176   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9177   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9178   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9179   //
9180   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9181   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9182   //  return AloBlo + AloBhi + AhiBlo;
9183
9184   SDValue A = Op.getOperand(0);
9185   SDValue B = Op.getOperand(1);
9186
9187   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9188                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9189                        A, DAG.getConstant(32, MVT::i32));
9190   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9191                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9192                        B, DAG.getConstant(32, MVT::i32));
9193   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9194                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9195                        A, B);
9196   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9197                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9198                        A, Bhi);
9199   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9200                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9201                        Ahi, B);
9202   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9203                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9204                        AloBhi, DAG.getConstant(32, MVT::i32));
9205   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9206                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9207                        AhiBlo, DAG.getConstant(32, MVT::i32));
9208   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9209   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9210   return Res;
9211 }
9212
9213 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9214
9215   EVT VT = Op.getValueType();
9216   DebugLoc dl = Op.getDebugLoc();
9217   SDValue R = Op.getOperand(0);
9218   SDValue Amt = Op.getOperand(1);
9219   LLVMContext *Context = DAG.getContext();
9220
9221   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9222     return SDValue();
9223
9224   // Decompose 256-bit shifts into smaller 128-bit shifts.
9225   if (VT.getSizeInBits() == 256) {
9226     int NumElems = VT.getVectorNumElements();
9227     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9228     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9229
9230     // Extract the two vectors
9231     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9232     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9233                                      DAG, dl);
9234
9235     // Recreate the shift amount vectors
9236     SmallVector<SDValue, 4> Amt1Csts;
9237     SmallVector<SDValue, 4> Amt2Csts;
9238     for (int i = 0; i < NumElems/2; ++i)
9239       Amt1Csts.push_back(Amt->getOperand(i));
9240     for (int i = NumElems/2; i < NumElems; ++i)
9241       Amt2Csts.push_back(Amt->getOperand(i));
9242
9243     SDValue Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9244                                &Amt1Csts[0], NumElems/2);
9245     SDValue Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9246                                &Amt2Csts[0], NumElems/2);
9247
9248     // Issue new vector shifts for the smaller types
9249     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9250     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9251
9252     // Concatenate the result back
9253     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9254   }
9255
9256   // Optimize shl/srl/sra with constant shift amount.
9257   if (isSplatVector(Amt.getNode())) {
9258     SDValue SclrAmt = Amt->getOperand(0);
9259     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9260       uint64_t ShiftAmt = C->getZExtValue();
9261
9262       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9263        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9264                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9265                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9266
9267       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9268        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9269                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9270                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9271
9272       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9273        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9274                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9275                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9276
9277       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9278        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9279                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9280                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9281
9282       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9283        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9284                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9285                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9286
9287       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9288        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9289                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9290                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9291
9292       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9293        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9294                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9295                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9296
9297       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9298        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9299                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9300                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9301     }
9302   }
9303
9304   // Lower SHL with variable shift amount.
9305   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9306     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9307                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9308                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9309
9310     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9311
9312     std::vector<Constant*> CV(4, CI);
9313     Constant *C = ConstantVector::get(CV);
9314     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9315     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9316                                  MachinePointerInfo::getConstantPool(),
9317                                  false, false, 16);
9318
9319     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9320     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9321     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9322     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9323   }
9324   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9325     // a = a << 5;
9326     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9327                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9328                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9329
9330     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9331     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9332
9333     std::vector<Constant*> CVM1(16, CM1);
9334     std::vector<Constant*> CVM2(16, CM2);
9335     Constant *C = ConstantVector::get(CVM1);
9336     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9337     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9338                             MachinePointerInfo::getConstantPool(),
9339                             false, false, 16);
9340
9341     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9342     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9343     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9344                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9345                     DAG.getConstant(4, MVT::i32));
9346     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9347     // a += a
9348     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9349
9350     C = ConstantVector::get(CVM2);
9351     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9352     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9353                     MachinePointerInfo::getConstantPool(),
9354                     false, false, 16);
9355
9356     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9357     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9358     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9359                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9360                     DAG.getConstant(2, MVT::i32));
9361     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9362     // a += a
9363     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9364
9365     // return pblendv(r, r+r, a);
9366     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9367                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9368     return R;
9369   }
9370   return SDValue();
9371 }
9372
9373 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9374   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9375   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9376   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9377   // has only one use.
9378   SDNode *N = Op.getNode();
9379   SDValue LHS = N->getOperand(0);
9380   SDValue RHS = N->getOperand(1);
9381   unsigned BaseOp = 0;
9382   unsigned Cond = 0;
9383   DebugLoc DL = Op.getDebugLoc();
9384   switch (Op.getOpcode()) {
9385   default: llvm_unreachable("Unknown ovf instruction!");
9386   case ISD::SADDO:
9387     // A subtract of one will be selected as a INC. Note that INC doesn't
9388     // set CF, so we can't do this for UADDO.
9389     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9390       if (C->isOne()) {
9391         BaseOp = X86ISD::INC;
9392         Cond = X86::COND_O;
9393         break;
9394       }
9395     BaseOp = X86ISD::ADD;
9396     Cond = X86::COND_O;
9397     break;
9398   case ISD::UADDO:
9399     BaseOp = X86ISD::ADD;
9400     Cond = X86::COND_B;
9401     break;
9402   case ISD::SSUBO:
9403     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9404     // set CF, so we can't do this for USUBO.
9405     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9406       if (C->isOne()) {
9407         BaseOp = X86ISD::DEC;
9408         Cond = X86::COND_O;
9409         break;
9410       }
9411     BaseOp = X86ISD::SUB;
9412     Cond = X86::COND_O;
9413     break;
9414   case ISD::USUBO:
9415     BaseOp = X86ISD::SUB;
9416     Cond = X86::COND_B;
9417     break;
9418   case ISD::SMULO:
9419     BaseOp = X86ISD::SMUL;
9420     Cond = X86::COND_O;
9421     break;
9422   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9423     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9424                                  MVT::i32);
9425     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9426
9427     SDValue SetCC =
9428       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9429                   DAG.getConstant(X86::COND_O, MVT::i32),
9430                   SDValue(Sum.getNode(), 2));
9431
9432     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9433   }
9434   }
9435
9436   // Also sets EFLAGS.
9437   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9438   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9439
9440   SDValue SetCC =
9441     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9442                 DAG.getConstant(Cond, MVT::i32),
9443                 SDValue(Sum.getNode(), 1));
9444
9445   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9446 }
9447
9448 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9449   DebugLoc dl = Op.getDebugLoc();
9450   SDNode* Node = Op.getNode();
9451   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9452   EVT VT = Node->getValueType(0);
9453
9454   if (Subtarget->hasSSE2() && VT.isVector()) {
9455     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9456                         ExtraVT.getScalarType().getSizeInBits();
9457     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9458
9459     unsigned SHLIntrinsicsID = 0;
9460     unsigned SRAIntrinsicsID = 0;
9461     switch (VT.getSimpleVT().SimpleTy) {
9462       default:
9463         return SDValue();
9464       case MVT::v2i64: {
9465         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9466         SRAIntrinsicsID = 0;
9467         break;
9468       }
9469       case MVT::v4i32: {
9470         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9471         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9472         break;
9473       }
9474       case MVT::v8i16: {
9475         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9476         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9477         break;
9478       }
9479     }
9480
9481     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9482                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9483                          Node->getOperand(0), ShAmt);
9484
9485     // In case of 1 bit sext, no need to shr
9486     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9487
9488     if (SRAIntrinsicsID) {
9489       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9490                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9491                          Tmp1, ShAmt);
9492     }
9493     return Tmp1;
9494   }
9495
9496   return SDValue();
9497 }
9498
9499
9500 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9501   DebugLoc dl = Op.getDebugLoc();
9502
9503   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9504   // There isn't any reason to disable it if the target processor supports it.
9505   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9506     SDValue Chain = Op.getOperand(0);
9507     SDValue Zero = DAG.getConstant(0, MVT::i32);
9508     SDValue Ops[] = {
9509       DAG.getRegister(X86::ESP, MVT::i32), // Base
9510       DAG.getTargetConstant(1, MVT::i8),   // Scale
9511       DAG.getRegister(0, MVT::i32),        // Index
9512       DAG.getTargetConstant(0, MVT::i32),  // Disp
9513       DAG.getRegister(0, MVT::i32),        // Segment.
9514       Zero,
9515       Chain
9516     };
9517     SDNode *Res =
9518       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9519                           array_lengthof(Ops));
9520     return SDValue(Res, 0);
9521   }
9522
9523   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9524   if (!isDev)
9525     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9526
9527   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9528   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9529   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9530   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9531
9532   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9533   if (!Op1 && !Op2 && !Op3 && Op4)
9534     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9535
9536   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9537   if (Op1 && !Op2 && !Op3 && !Op4)
9538     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9539
9540   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9541   //           (MFENCE)>;
9542   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9543 }
9544
9545 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
9546                                              SelectionDAG &DAG) const {
9547   DebugLoc dl = Op.getDebugLoc();
9548   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
9549     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
9550   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
9551     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9552
9553   // The only fence that needs an instruction is a sequentially-consistent
9554   // cross-thread fence.
9555   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
9556     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
9557     // no-sse2). There isn't any reason to disable it if the target processor
9558     // supports it.
9559     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
9560       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9561
9562     SDValue Chain = Op.getOperand(0);
9563     SDValue Zero = DAG.getConstant(0, MVT::i32);
9564     SDValue Ops[] = {
9565       DAG.getRegister(X86::ESP, MVT::i32), // Base
9566       DAG.getTargetConstant(1, MVT::i8),   // Scale
9567       DAG.getRegister(0, MVT::i32),        // Index
9568       DAG.getTargetConstant(0, MVT::i32),  // Disp
9569       DAG.getRegister(0, MVT::i32),        // Segment.
9570       Zero,
9571       Chain
9572     };
9573     SDNode *Res =
9574       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9575                          array_lengthof(Ops));
9576     return SDValue(Res, 0);
9577   }
9578
9579   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
9580   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9581 }
9582
9583
9584 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9585   EVT T = Op.getValueType();
9586   DebugLoc DL = Op.getDebugLoc();
9587   unsigned Reg = 0;
9588   unsigned size = 0;
9589   switch(T.getSimpleVT().SimpleTy) {
9590   default:
9591     assert(false && "Invalid value type!");
9592   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9593   case MVT::i16: Reg = X86::AX;  size = 2; break;
9594   case MVT::i32: Reg = X86::EAX; size = 4; break;
9595   case MVT::i64:
9596     assert(Subtarget->is64Bit() && "Node not type legal!");
9597     Reg = X86::RAX; size = 8;
9598     break;
9599   }
9600   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9601                                     Op.getOperand(2), SDValue());
9602   SDValue Ops[] = { cpIn.getValue(0),
9603                     Op.getOperand(1),
9604                     Op.getOperand(3),
9605                     DAG.getTargetConstant(size, MVT::i8),
9606                     cpIn.getValue(1) };
9607   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9608   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9609   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9610                                            Ops, 5, T, MMO);
9611   SDValue cpOut =
9612     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9613   return cpOut;
9614 }
9615
9616 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9617                                                  SelectionDAG &DAG) const {
9618   assert(Subtarget->is64Bit() && "Result not type legalized?");
9619   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9620   SDValue TheChain = Op.getOperand(0);
9621   DebugLoc dl = Op.getDebugLoc();
9622   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9623   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9624   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9625                                    rax.getValue(2));
9626   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9627                             DAG.getConstant(32, MVT::i8));
9628   SDValue Ops[] = {
9629     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9630     rdx.getValue(1)
9631   };
9632   return DAG.getMergeValues(Ops, 2, dl);
9633 }
9634
9635 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9636                                             SelectionDAG &DAG) const {
9637   EVT SrcVT = Op.getOperand(0).getValueType();
9638   EVT DstVT = Op.getValueType();
9639   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9640          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9641   assert((DstVT == MVT::i64 ||
9642           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9643          "Unexpected custom BITCAST");
9644   // i64 <=> MMX conversions are Legal.
9645   if (SrcVT==MVT::i64 && DstVT.isVector())
9646     return Op;
9647   if (DstVT==MVT::i64 && SrcVT.isVector())
9648     return Op;
9649   // MMX <=> MMX conversions are Legal.
9650   if (SrcVT.isVector() && DstVT.isVector())
9651     return Op;
9652   // All other conversions need to be expanded.
9653   return SDValue();
9654 }
9655
9656 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9657   SDNode *Node = Op.getNode();
9658   DebugLoc dl = Node->getDebugLoc();
9659   EVT T = Node->getValueType(0);
9660   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9661                               DAG.getConstant(0, T), Node->getOperand(2));
9662   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9663                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9664                        Node->getOperand(0),
9665                        Node->getOperand(1), negOp,
9666                        cast<AtomicSDNode>(Node)->getSrcValue(),
9667                        cast<AtomicSDNode>(Node)->getAlignment(),
9668                        cast<AtomicSDNode>(Node)->getOrdering(),
9669                        cast<AtomicSDNode>(Node)->getSynchScope());
9670 }
9671
9672 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9673   EVT VT = Op.getNode()->getValueType(0);
9674
9675   // Let legalize expand this if it isn't a legal type yet.
9676   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9677     return SDValue();
9678
9679   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9680
9681   unsigned Opc;
9682   bool ExtraOp = false;
9683   switch (Op.getOpcode()) {
9684   default: assert(0 && "Invalid code");
9685   case ISD::ADDC: Opc = X86ISD::ADD; break;
9686   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9687   case ISD::SUBC: Opc = X86ISD::SUB; break;
9688   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9689   }
9690
9691   if (!ExtraOp)
9692     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9693                        Op.getOperand(1));
9694   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9695                      Op.getOperand(1), Op.getOperand(2));
9696 }
9697
9698 /// LowerOperation - Provide custom lowering hooks for some operations.
9699 ///
9700 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9701   switch (Op.getOpcode()) {
9702   default: llvm_unreachable("Should not custom lower this!");
9703   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
9704   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9705   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
9706   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9707   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9708   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9709   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9710   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9711   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9712   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9713   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9714   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9715   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9716   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9717   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9718   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9719   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9720   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9721   case ISD::SHL_PARTS:
9722   case ISD::SRA_PARTS:
9723   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9724   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9725   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9726   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9727   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9728   case ISD::FABS:               return LowerFABS(Op, DAG);
9729   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9730   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9731   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9732   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9733   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9734   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9735   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9736   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9737   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9738   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9739   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9740   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9741   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9742   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9743   case ISD::FRAME_TO_ARGS_OFFSET:
9744                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9745   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9746   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9747   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9748   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9749   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9750   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9751   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9752   case ISD::SRA:
9753   case ISD::SRL:
9754   case ISD::SHL:                return LowerShift(Op, DAG);
9755   case ISD::SADDO:
9756   case ISD::UADDO:
9757   case ISD::SSUBO:
9758   case ISD::USUBO:
9759   case ISD::SMULO:
9760   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9761   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9762   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9763   case ISD::ADDC:
9764   case ISD::ADDE:
9765   case ISD::SUBC:
9766   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9767   }
9768 }
9769
9770 void X86TargetLowering::
9771 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9772                         SelectionDAG &DAG, unsigned NewOp) const {
9773   EVT T = Node->getValueType(0);
9774   DebugLoc dl = Node->getDebugLoc();
9775   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9776
9777   SDValue Chain = Node->getOperand(0);
9778   SDValue In1 = Node->getOperand(1);
9779   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9780                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9781   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9782                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9783   SDValue Ops[] = { Chain, In1, In2L, In2H };
9784   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9785   SDValue Result =
9786     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9787                             cast<MemSDNode>(Node)->getMemOperand());
9788   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9789   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9790   Results.push_back(Result.getValue(2));
9791 }
9792
9793 /// ReplaceNodeResults - Replace a node with an illegal result type
9794 /// with a new node built out of custom code.
9795 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9796                                            SmallVectorImpl<SDValue>&Results,
9797                                            SelectionDAG &DAG) const {
9798   DebugLoc dl = N->getDebugLoc();
9799   switch (N->getOpcode()) {
9800   default:
9801     assert(false && "Do not know how to custom type legalize this operation!");
9802     return;
9803   case ISD::SIGN_EXTEND_INREG:
9804   case ISD::ADDC:
9805   case ISD::ADDE:
9806   case ISD::SUBC:
9807   case ISD::SUBE:
9808     // We don't want to expand or promote these.
9809     return;
9810   case ISD::FP_TO_SINT: {
9811     std::pair<SDValue,SDValue> Vals =
9812         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9813     SDValue FIST = Vals.first, StackSlot = Vals.second;
9814     if (FIST.getNode() != 0) {
9815       EVT VT = N->getValueType(0);
9816       // Return a load from the stack slot.
9817       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9818                                     MachinePointerInfo(), false, false, 0));
9819     }
9820     return;
9821   }
9822   case ISD::READCYCLECOUNTER: {
9823     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9824     SDValue TheChain = N->getOperand(0);
9825     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9826     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9827                                      rd.getValue(1));
9828     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9829                                      eax.getValue(2));
9830     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9831     SDValue Ops[] = { eax, edx };
9832     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9833     Results.push_back(edx.getValue(1));
9834     return;
9835   }
9836   case ISD::ATOMIC_CMP_SWAP: {
9837     EVT T = N->getValueType(0);
9838     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9839     SDValue cpInL, cpInH;
9840     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9841                         DAG.getConstant(0, MVT::i32));
9842     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9843                         DAG.getConstant(1, MVT::i32));
9844     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9845     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9846                              cpInL.getValue(1));
9847     SDValue swapInL, swapInH;
9848     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9849                           DAG.getConstant(0, MVT::i32));
9850     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9851                           DAG.getConstant(1, MVT::i32));
9852     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9853                                cpInH.getValue(1));
9854     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9855                                swapInL.getValue(1));
9856     SDValue Ops[] = { swapInH.getValue(0),
9857                       N->getOperand(1),
9858                       swapInH.getValue(1) };
9859     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9860     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9861     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9862                                              Ops, 3, T, MMO);
9863     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9864                                         MVT::i32, Result.getValue(1));
9865     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9866                                         MVT::i32, cpOutL.getValue(2));
9867     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9868     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9869     Results.push_back(cpOutH.getValue(1));
9870     return;
9871   }
9872   case ISD::ATOMIC_LOAD_ADD:
9873     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9874     return;
9875   case ISD::ATOMIC_LOAD_AND:
9876     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9877     return;
9878   case ISD::ATOMIC_LOAD_NAND:
9879     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9880     return;
9881   case ISD::ATOMIC_LOAD_OR:
9882     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9883     return;
9884   case ISD::ATOMIC_LOAD_SUB:
9885     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9886     return;
9887   case ISD::ATOMIC_LOAD_XOR:
9888     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9889     return;
9890   case ISD::ATOMIC_SWAP:
9891     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9892     return;
9893   }
9894 }
9895
9896 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9897   switch (Opcode) {
9898   default: return NULL;
9899   case X86ISD::BSF:                return "X86ISD::BSF";
9900   case X86ISD::BSR:                return "X86ISD::BSR";
9901   case X86ISD::SHLD:               return "X86ISD::SHLD";
9902   case X86ISD::SHRD:               return "X86ISD::SHRD";
9903   case X86ISD::FAND:               return "X86ISD::FAND";
9904   case X86ISD::FOR:                return "X86ISD::FOR";
9905   case X86ISD::FXOR:               return "X86ISD::FXOR";
9906   case X86ISD::FSRL:               return "X86ISD::FSRL";
9907   case X86ISD::FILD:               return "X86ISD::FILD";
9908   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9909   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9910   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9911   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9912   case X86ISD::FLD:                return "X86ISD::FLD";
9913   case X86ISD::FST:                return "X86ISD::FST";
9914   case X86ISD::CALL:               return "X86ISD::CALL";
9915   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9916   case X86ISD::BT:                 return "X86ISD::BT";
9917   case X86ISD::CMP:                return "X86ISD::CMP";
9918   case X86ISD::COMI:               return "X86ISD::COMI";
9919   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9920   case X86ISD::SETCC:              return "X86ISD::SETCC";
9921   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9922   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9923   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9924   case X86ISD::CMOV:               return "X86ISD::CMOV";
9925   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9926   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9927   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9928   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9929   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9930   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9931   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9932   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9933   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9934   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9935   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9936   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9937   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9938   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9939   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9940   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9941   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9942   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9943   case X86ISD::FMAX:               return "X86ISD::FMAX";
9944   case X86ISD::FMIN:               return "X86ISD::FMIN";
9945   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9946   case X86ISD::FRCP:               return "X86ISD::FRCP";
9947   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9948   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9949   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9950   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9951   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9952   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9953   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9954   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9955   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9956   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9957   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9958   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9959   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9960   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9961   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9962   case X86ISD::VSHL:               return "X86ISD::VSHL";
9963   case X86ISD::VSRL:               return "X86ISD::VSRL";
9964   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9965   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9966   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9967   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9968   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9969   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9970   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9971   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9972   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9973   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9974   case X86ISD::ADD:                return "X86ISD::ADD";
9975   case X86ISD::SUB:                return "X86ISD::SUB";
9976   case X86ISD::ADC:                return "X86ISD::ADC";
9977   case X86ISD::SBB:                return "X86ISD::SBB";
9978   case X86ISD::SMUL:               return "X86ISD::SMUL";
9979   case X86ISD::UMUL:               return "X86ISD::UMUL";
9980   case X86ISD::INC:                return "X86ISD::INC";
9981   case X86ISD::DEC:                return "X86ISD::DEC";
9982   case X86ISD::OR:                 return "X86ISD::OR";
9983   case X86ISD::XOR:                return "X86ISD::XOR";
9984   case X86ISD::AND:                return "X86ISD::AND";
9985   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9986   case X86ISD::PTEST:              return "X86ISD::PTEST";
9987   case X86ISD::TESTP:              return "X86ISD::TESTP";
9988   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9989   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9990   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9991   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9992   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9993   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9994   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9995   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9996   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9997   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9998   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9999   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10000   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10001   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10002   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10003   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10004   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10005   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10006   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10007   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10008   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10009   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10010   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10011   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10012   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10013   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10014   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10015   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10016   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10017   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10018   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10019   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10020   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10021   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10022   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10023   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10024   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10025   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10026   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10027   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10028   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10029   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10030   }
10031 }
10032
10033 // isLegalAddressingMode - Return true if the addressing mode represented
10034 // by AM is legal for this target, for a load/store of the specified type.
10035 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10036                                               Type *Ty) const {
10037   // X86 supports extremely general addressing modes.
10038   CodeModel::Model M = getTargetMachine().getCodeModel();
10039   Reloc::Model R = getTargetMachine().getRelocationModel();
10040
10041   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10042   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10043     return false;
10044
10045   if (AM.BaseGV) {
10046     unsigned GVFlags =
10047       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10048
10049     // If a reference to this global requires an extra load, we can't fold it.
10050     if (isGlobalStubReference(GVFlags))
10051       return false;
10052
10053     // If BaseGV requires a register for the PIC base, we cannot also have a
10054     // BaseReg specified.
10055     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10056       return false;
10057
10058     // If lower 4G is not available, then we must use rip-relative addressing.
10059     if ((M != CodeModel::Small || R != Reloc::Static) &&
10060         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10061       return false;
10062   }
10063
10064   switch (AM.Scale) {
10065   case 0:
10066   case 1:
10067   case 2:
10068   case 4:
10069   case 8:
10070     // These scales always work.
10071     break;
10072   case 3:
10073   case 5:
10074   case 9:
10075     // These scales are formed with basereg+scalereg.  Only accept if there is
10076     // no basereg yet.
10077     if (AM.HasBaseReg)
10078       return false;
10079     break;
10080   default:  // Other stuff never works.
10081     return false;
10082   }
10083
10084   return true;
10085 }
10086
10087
10088 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10089   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10090     return false;
10091   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10092   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10093   if (NumBits1 <= NumBits2)
10094     return false;
10095   return true;
10096 }
10097
10098 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10099   if (!VT1.isInteger() || !VT2.isInteger())
10100     return false;
10101   unsigned NumBits1 = VT1.getSizeInBits();
10102   unsigned NumBits2 = VT2.getSizeInBits();
10103   if (NumBits1 <= NumBits2)
10104     return false;
10105   return true;
10106 }
10107
10108 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10109   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10110   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10111 }
10112
10113 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10114   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10115   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10116 }
10117
10118 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10119   // i16 instructions are longer (0x66 prefix) and potentially slower.
10120   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10121 }
10122
10123 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10124 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10125 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10126 /// are assumed to be legal.
10127 bool
10128 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10129                                       EVT VT) const {
10130   // Very little shuffling can be done for 64-bit vectors right now.
10131   if (VT.getSizeInBits() == 64)
10132     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10133
10134   // FIXME: pshufb, blends, shifts.
10135   return (VT.getVectorNumElements() == 2 ||
10136           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10137           isMOVLMask(M, VT) ||
10138           isSHUFPMask(M, VT) ||
10139           isPSHUFDMask(M, VT) ||
10140           isPSHUFHWMask(M, VT) ||
10141           isPSHUFLWMask(M, VT) ||
10142           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10143           isUNPCKLMask(M, VT) ||
10144           isUNPCKHMask(M, VT) ||
10145           isUNPCKL_v_undef_Mask(M, VT) ||
10146           isUNPCKH_v_undef_Mask(M, VT));
10147 }
10148
10149 bool
10150 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10151                                           EVT VT) const {
10152   unsigned NumElts = VT.getVectorNumElements();
10153   // FIXME: This collection of masks seems suspect.
10154   if (NumElts == 2)
10155     return true;
10156   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10157     return (isMOVLMask(Mask, VT)  ||
10158             isCommutedMOVLMask(Mask, VT, true) ||
10159             isSHUFPMask(Mask, VT) ||
10160             isCommutedSHUFPMask(Mask, VT));
10161   }
10162   return false;
10163 }
10164
10165 //===----------------------------------------------------------------------===//
10166 //                           X86 Scheduler Hooks
10167 //===----------------------------------------------------------------------===//
10168
10169 // private utility function
10170 MachineBasicBlock *
10171 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10172                                                        MachineBasicBlock *MBB,
10173                                                        unsigned regOpc,
10174                                                        unsigned immOpc,
10175                                                        unsigned LoadOpc,
10176                                                        unsigned CXchgOpc,
10177                                                        unsigned notOpc,
10178                                                        unsigned EAXreg,
10179                                                        TargetRegisterClass *RC,
10180                                                        bool invSrc) const {
10181   // For the atomic bitwise operator, we generate
10182   //   thisMBB:
10183   //   newMBB:
10184   //     ld  t1 = [bitinstr.addr]
10185   //     op  t2 = t1, [bitinstr.val]
10186   //     mov EAX = t1
10187   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10188   //     bz  newMBB
10189   //     fallthrough -->nextMBB
10190   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10191   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10192   MachineFunction::iterator MBBIter = MBB;
10193   ++MBBIter;
10194
10195   /// First build the CFG
10196   MachineFunction *F = MBB->getParent();
10197   MachineBasicBlock *thisMBB = MBB;
10198   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10199   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10200   F->insert(MBBIter, newMBB);
10201   F->insert(MBBIter, nextMBB);
10202
10203   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10204   nextMBB->splice(nextMBB->begin(), thisMBB,
10205                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10206                   thisMBB->end());
10207   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10208
10209   // Update thisMBB to fall through to newMBB
10210   thisMBB->addSuccessor(newMBB);
10211
10212   // newMBB jumps to itself and fall through to nextMBB
10213   newMBB->addSuccessor(nextMBB);
10214   newMBB->addSuccessor(newMBB);
10215
10216   // Insert instructions into newMBB based on incoming instruction
10217   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10218          "unexpected number of operands");
10219   DebugLoc dl = bInstr->getDebugLoc();
10220   MachineOperand& destOper = bInstr->getOperand(0);
10221   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10222   int numArgs = bInstr->getNumOperands() - 1;
10223   for (int i=0; i < numArgs; ++i)
10224     argOpers[i] = &bInstr->getOperand(i+1);
10225
10226   // x86 address has 4 operands: base, index, scale, and displacement
10227   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10228   int valArgIndx = lastAddrIndx + 1;
10229
10230   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10231   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10232   for (int i=0; i <= lastAddrIndx; ++i)
10233     (*MIB).addOperand(*argOpers[i]);
10234
10235   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10236   if (invSrc) {
10237     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10238   }
10239   else
10240     tt = t1;
10241
10242   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10243   assert((argOpers[valArgIndx]->isReg() ||
10244           argOpers[valArgIndx]->isImm()) &&
10245          "invalid operand");
10246   if (argOpers[valArgIndx]->isReg())
10247     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10248   else
10249     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10250   MIB.addReg(tt);
10251   (*MIB).addOperand(*argOpers[valArgIndx]);
10252
10253   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10254   MIB.addReg(t1);
10255
10256   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10257   for (int i=0; i <= lastAddrIndx; ++i)
10258     (*MIB).addOperand(*argOpers[i]);
10259   MIB.addReg(t2);
10260   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10261   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10262                     bInstr->memoperands_end());
10263
10264   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10265   MIB.addReg(EAXreg);
10266
10267   // insert branch
10268   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10269
10270   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10271   return nextMBB;
10272 }
10273
10274 // private utility function:  64 bit atomics on 32 bit host.
10275 MachineBasicBlock *
10276 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10277                                                        MachineBasicBlock *MBB,
10278                                                        unsigned regOpcL,
10279                                                        unsigned regOpcH,
10280                                                        unsigned immOpcL,
10281                                                        unsigned immOpcH,
10282                                                        bool invSrc) const {
10283   // For the atomic bitwise operator, we generate
10284   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10285   //     ld t1,t2 = [bitinstr.addr]
10286   //   newMBB:
10287   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10288   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10289   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10290   //     mov ECX, EBX <- t5, t6
10291   //     mov EAX, EDX <- t1, t2
10292   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10293   //     mov t3, t4 <- EAX, EDX
10294   //     bz  newMBB
10295   //     result in out1, out2
10296   //     fallthrough -->nextMBB
10297
10298   const TargetRegisterClass *RC = X86::GR32RegisterClass;
10299   const unsigned LoadOpc = X86::MOV32rm;
10300   const unsigned NotOpc = X86::NOT32r;
10301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10302   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10303   MachineFunction::iterator MBBIter = MBB;
10304   ++MBBIter;
10305
10306   /// First build the CFG
10307   MachineFunction *F = MBB->getParent();
10308   MachineBasicBlock *thisMBB = MBB;
10309   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10310   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10311   F->insert(MBBIter, newMBB);
10312   F->insert(MBBIter, nextMBB);
10313
10314   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10315   nextMBB->splice(nextMBB->begin(), thisMBB,
10316                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10317                   thisMBB->end());
10318   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10319
10320   // Update thisMBB to fall through to newMBB
10321   thisMBB->addSuccessor(newMBB);
10322
10323   // newMBB jumps to itself and fall through to nextMBB
10324   newMBB->addSuccessor(nextMBB);
10325   newMBB->addSuccessor(newMBB);
10326
10327   DebugLoc dl = bInstr->getDebugLoc();
10328   // Insert instructions into newMBB based on incoming instruction
10329   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10330   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10331          "unexpected number of operands");
10332   MachineOperand& dest1Oper = bInstr->getOperand(0);
10333   MachineOperand& dest2Oper = bInstr->getOperand(1);
10334   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10335   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10336     argOpers[i] = &bInstr->getOperand(i+2);
10337
10338     // We use some of the operands multiple times, so conservatively just
10339     // clear any kill flags that might be present.
10340     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10341       argOpers[i]->setIsKill(false);
10342   }
10343
10344   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10345   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10346
10347   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10348   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10349   for (int i=0; i <= lastAddrIndx; ++i)
10350     (*MIB).addOperand(*argOpers[i]);
10351   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10352   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10353   // add 4 to displacement.
10354   for (int i=0; i <= lastAddrIndx-2; ++i)
10355     (*MIB).addOperand(*argOpers[i]);
10356   MachineOperand newOp3 = *(argOpers[3]);
10357   if (newOp3.isImm())
10358     newOp3.setImm(newOp3.getImm()+4);
10359   else
10360     newOp3.setOffset(newOp3.getOffset()+4);
10361   (*MIB).addOperand(newOp3);
10362   (*MIB).addOperand(*argOpers[lastAddrIndx]);
10363
10364   // t3/4 are defined later, at the bottom of the loop
10365   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10366   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10367   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10368     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10369   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10370     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10371
10372   // The subsequent operations should be using the destination registers of
10373   //the PHI instructions.
10374   if (invSrc) {
10375     t1 = F->getRegInfo().createVirtualRegister(RC);
10376     t2 = F->getRegInfo().createVirtualRegister(RC);
10377     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10378     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10379   } else {
10380     t1 = dest1Oper.getReg();
10381     t2 = dest2Oper.getReg();
10382   }
10383
10384   int valArgIndx = lastAddrIndx + 1;
10385   assert((argOpers[valArgIndx]->isReg() ||
10386           argOpers[valArgIndx]->isImm()) &&
10387          "invalid operand");
10388   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10389   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10390   if (argOpers[valArgIndx]->isReg())
10391     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10392   else
10393     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10394   if (regOpcL != X86::MOV32rr)
10395     MIB.addReg(t1);
10396   (*MIB).addOperand(*argOpers[valArgIndx]);
10397   assert(argOpers[valArgIndx + 1]->isReg() ==
10398          argOpers[valArgIndx]->isReg());
10399   assert(argOpers[valArgIndx + 1]->isImm() ==
10400          argOpers[valArgIndx]->isImm());
10401   if (argOpers[valArgIndx + 1]->isReg())
10402     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10403   else
10404     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10405   if (regOpcH != X86::MOV32rr)
10406     MIB.addReg(t2);
10407   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10408
10409   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10410   MIB.addReg(t1);
10411   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10412   MIB.addReg(t2);
10413
10414   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10415   MIB.addReg(t5);
10416   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10417   MIB.addReg(t6);
10418
10419   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10420   for (int i=0; i <= lastAddrIndx; ++i)
10421     (*MIB).addOperand(*argOpers[i]);
10422
10423   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10424   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10425                     bInstr->memoperands_end());
10426
10427   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10428   MIB.addReg(X86::EAX);
10429   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10430   MIB.addReg(X86::EDX);
10431
10432   // insert branch
10433   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10434
10435   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10436   return nextMBB;
10437 }
10438
10439 // private utility function
10440 MachineBasicBlock *
10441 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10442                                                       MachineBasicBlock *MBB,
10443                                                       unsigned cmovOpc) const {
10444   // For the atomic min/max operator, we generate
10445   //   thisMBB:
10446   //   newMBB:
10447   //     ld t1 = [min/max.addr]
10448   //     mov t2 = [min/max.val]
10449   //     cmp  t1, t2
10450   //     cmov[cond] t2 = t1
10451   //     mov EAX = t1
10452   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10453   //     bz   newMBB
10454   //     fallthrough -->nextMBB
10455   //
10456   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10457   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10458   MachineFunction::iterator MBBIter = MBB;
10459   ++MBBIter;
10460
10461   /// First build the CFG
10462   MachineFunction *F = MBB->getParent();
10463   MachineBasicBlock *thisMBB = MBB;
10464   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10465   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10466   F->insert(MBBIter, newMBB);
10467   F->insert(MBBIter, nextMBB);
10468
10469   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10470   nextMBB->splice(nextMBB->begin(), thisMBB,
10471                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10472                   thisMBB->end());
10473   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10474
10475   // Update thisMBB to fall through to newMBB
10476   thisMBB->addSuccessor(newMBB);
10477
10478   // newMBB jumps to newMBB and fall through to nextMBB
10479   newMBB->addSuccessor(nextMBB);
10480   newMBB->addSuccessor(newMBB);
10481
10482   DebugLoc dl = mInstr->getDebugLoc();
10483   // Insert instructions into newMBB based on incoming instruction
10484   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10485          "unexpected number of operands");
10486   MachineOperand& destOper = mInstr->getOperand(0);
10487   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10488   int numArgs = mInstr->getNumOperands() - 1;
10489   for (int i=0; i < numArgs; ++i)
10490     argOpers[i] = &mInstr->getOperand(i+1);
10491
10492   // x86 address has 4 operands: base, index, scale, and displacement
10493   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10494   int valArgIndx = lastAddrIndx + 1;
10495
10496   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10497   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10498   for (int i=0; i <= lastAddrIndx; ++i)
10499     (*MIB).addOperand(*argOpers[i]);
10500
10501   // We only support register and immediate values
10502   assert((argOpers[valArgIndx]->isReg() ||
10503           argOpers[valArgIndx]->isImm()) &&
10504          "invalid operand");
10505
10506   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10507   if (argOpers[valArgIndx]->isReg())
10508     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10509   else
10510     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10511   (*MIB).addOperand(*argOpers[valArgIndx]);
10512
10513   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10514   MIB.addReg(t1);
10515
10516   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10517   MIB.addReg(t1);
10518   MIB.addReg(t2);
10519
10520   // Generate movc
10521   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10522   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10523   MIB.addReg(t2);
10524   MIB.addReg(t1);
10525
10526   // Cmp and exchange if none has modified the memory location
10527   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10528   for (int i=0; i <= lastAddrIndx; ++i)
10529     (*MIB).addOperand(*argOpers[i]);
10530   MIB.addReg(t3);
10531   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10532   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10533                     mInstr->memoperands_end());
10534
10535   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10536   MIB.addReg(X86::EAX);
10537
10538   // insert branch
10539   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10540
10541   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10542   return nextMBB;
10543 }
10544
10545 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10546 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10547 // in the .td file.
10548 MachineBasicBlock *
10549 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10550                             unsigned numArgs, bool memArg) const {
10551   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10552          "Target must have SSE4.2 or AVX features enabled");
10553
10554   DebugLoc dl = MI->getDebugLoc();
10555   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10556   unsigned Opc;
10557   if (!Subtarget->hasAVX()) {
10558     if (memArg)
10559       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10560     else
10561       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10562   } else {
10563     if (memArg)
10564       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10565     else
10566       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10567   }
10568
10569   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10570   for (unsigned i = 0; i < numArgs; ++i) {
10571     MachineOperand &Op = MI->getOperand(i+1);
10572     if (!(Op.isReg() && Op.isImplicit()))
10573       MIB.addOperand(Op);
10574   }
10575   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10576     .addReg(X86::XMM0);
10577
10578   MI->eraseFromParent();
10579   return BB;
10580 }
10581
10582 MachineBasicBlock *
10583 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10584   DebugLoc dl = MI->getDebugLoc();
10585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10586
10587   // Address into RAX/EAX, other two args into ECX, EDX.
10588   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10589   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10590   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10591   for (int i = 0; i < X86::AddrNumOperands; ++i)
10592     MIB.addOperand(MI->getOperand(i));
10593
10594   unsigned ValOps = X86::AddrNumOperands;
10595   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10596     .addReg(MI->getOperand(ValOps).getReg());
10597   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10598     .addReg(MI->getOperand(ValOps+1).getReg());
10599
10600   // The instruction doesn't actually take any operands though.
10601   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10602
10603   MI->eraseFromParent(); // The pseudo is gone now.
10604   return BB;
10605 }
10606
10607 MachineBasicBlock *
10608 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10609   DebugLoc dl = MI->getDebugLoc();
10610   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10611
10612   // First arg in ECX, the second in EAX.
10613   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10614     .addReg(MI->getOperand(0).getReg());
10615   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10616     .addReg(MI->getOperand(1).getReg());
10617
10618   // The instruction doesn't actually take any operands though.
10619   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10620
10621   MI->eraseFromParent(); // The pseudo is gone now.
10622   return BB;
10623 }
10624
10625 MachineBasicBlock *
10626 X86TargetLowering::EmitVAARG64WithCustomInserter(
10627                    MachineInstr *MI,
10628                    MachineBasicBlock *MBB) const {
10629   // Emit va_arg instruction on X86-64.
10630
10631   // Operands to this pseudo-instruction:
10632   // 0  ) Output        : destination address (reg)
10633   // 1-5) Input         : va_list address (addr, i64mem)
10634   // 6  ) ArgSize       : Size (in bytes) of vararg type
10635   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10636   // 8  ) Align         : Alignment of type
10637   // 9  ) EFLAGS (implicit-def)
10638
10639   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10640   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10641
10642   unsigned DestReg = MI->getOperand(0).getReg();
10643   MachineOperand &Base = MI->getOperand(1);
10644   MachineOperand &Scale = MI->getOperand(2);
10645   MachineOperand &Index = MI->getOperand(3);
10646   MachineOperand &Disp = MI->getOperand(4);
10647   MachineOperand &Segment = MI->getOperand(5);
10648   unsigned ArgSize = MI->getOperand(6).getImm();
10649   unsigned ArgMode = MI->getOperand(7).getImm();
10650   unsigned Align = MI->getOperand(8).getImm();
10651
10652   // Memory Reference
10653   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10654   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10655   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10656
10657   // Machine Information
10658   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10659   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10660   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10661   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10662   DebugLoc DL = MI->getDebugLoc();
10663
10664   // struct va_list {
10665   //   i32   gp_offset
10666   //   i32   fp_offset
10667   //   i64   overflow_area (address)
10668   //   i64   reg_save_area (address)
10669   // }
10670   // sizeof(va_list) = 24
10671   // alignment(va_list) = 8
10672
10673   unsigned TotalNumIntRegs = 6;
10674   unsigned TotalNumXMMRegs = 8;
10675   bool UseGPOffset = (ArgMode == 1);
10676   bool UseFPOffset = (ArgMode == 2);
10677   unsigned MaxOffset = TotalNumIntRegs * 8 +
10678                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10679
10680   /* Align ArgSize to a multiple of 8 */
10681   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10682   bool NeedsAlign = (Align > 8);
10683
10684   MachineBasicBlock *thisMBB = MBB;
10685   MachineBasicBlock *overflowMBB;
10686   MachineBasicBlock *offsetMBB;
10687   MachineBasicBlock *endMBB;
10688
10689   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10690   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10691   unsigned OffsetReg = 0;
10692
10693   if (!UseGPOffset && !UseFPOffset) {
10694     // If we only pull from the overflow region, we don't create a branch.
10695     // We don't need to alter control flow.
10696     OffsetDestReg = 0; // unused
10697     OverflowDestReg = DestReg;
10698
10699     offsetMBB = NULL;
10700     overflowMBB = thisMBB;
10701     endMBB = thisMBB;
10702   } else {
10703     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10704     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10705     // If not, pull from overflow_area. (branch to overflowMBB)
10706     //
10707     //       thisMBB
10708     //         |     .
10709     //         |        .
10710     //     offsetMBB   overflowMBB
10711     //         |        .
10712     //         |     .
10713     //        endMBB
10714
10715     // Registers for the PHI in endMBB
10716     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10717     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10718
10719     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10720     MachineFunction *MF = MBB->getParent();
10721     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10722     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10723     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10724
10725     MachineFunction::iterator MBBIter = MBB;
10726     ++MBBIter;
10727
10728     // Insert the new basic blocks
10729     MF->insert(MBBIter, offsetMBB);
10730     MF->insert(MBBIter, overflowMBB);
10731     MF->insert(MBBIter, endMBB);
10732
10733     // Transfer the remainder of MBB and its successor edges to endMBB.
10734     endMBB->splice(endMBB->begin(), thisMBB,
10735                     llvm::next(MachineBasicBlock::iterator(MI)),
10736                     thisMBB->end());
10737     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10738
10739     // Make offsetMBB and overflowMBB successors of thisMBB
10740     thisMBB->addSuccessor(offsetMBB);
10741     thisMBB->addSuccessor(overflowMBB);
10742
10743     // endMBB is a successor of both offsetMBB and overflowMBB
10744     offsetMBB->addSuccessor(endMBB);
10745     overflowMBB->addSuccessor(endMBB);
10746
10747     // Load the offset value into a register
10748     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10749     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10750       .addOperand(Base)
10751       .addOperand(Scale)
10752       .addOperand(Index)
10753       .addDisp(Disp, UseFPOffset ? 4 : 0)
10754       .addOperand(Segment)
10755       .setMemRefs(MMOBegin, MMOEnd);
10756
10757     // Check if there is enough room left to pull this argument.
10758     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10759       .addReg(OffsetReg)
10760       .addImm(MaxOffset + 8 - ArgSizeA8);
10761
10762     // Branch to "overflowMBB" if offset >= max
10763     // Fall through to "offsetMBB" otherwise
10764     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10765       .addMBB(overflowMBB);
10766   }
10767
10768   // In offsetMBB, emit code to use the reg_save_area.
10769   if (offsetMBB) {
10770     assert(OffsetReg != 0);
10771
10772     // Read the reg_save_area address.
10773     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10774     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10775       .addOperand(Base)
10776       .addOperand(Scale)
10777       .addOperand(Index)
10778       .addDisp(Disp, 16)
10779       .addOperand(Segment)
10780       .setMemRefs(MMOBegin, MMOEnd);
10781
10782     // Zero-extend the offset
10783     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10784       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10785         .addImm(0)
10786         .addReg(OffsetReg)
10787         .addImm(X86::sub_32bit);
10788
10789     // Add the offset to the reg_save_area to get the final address.
10790     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10791       .addReg(OffsetReg64)
10792       .addReg(RegSaveReg);
10793
10794     // Compute the offset for the next argument
10795     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10796     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10797       .addReg(OffsetReg)
10798       .addImm(UseFPOffset ? 16 : 8);
10799
10800     // Store it back into the va_list.
10801     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10802       .addOperand(Base)
10803       .addOperand(Scale)
10804       .addOperand(Index)
10805       .addDisp(Disp, UseFPOffset ? 4 : 0)
10806       .addOperand(Segment)
10807       .addReg(NextOffsetReg)
10808       .setMemRefs(MMOBegin, MMOEnd);
10809
10810     // Jump to endMBB
10811     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10812       .addMBB(endMBB);
10813   }
10814
10815   //
10816   // Emit code to use overflow area
10817   //
10818
10819   // Load the overflow_area address into a register.
10820   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10821   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10822     .addOperand(Base)
10823     .addOperand(Scale)
10824     .addOperand(Index)
10825     .addDisp(Disp, 8)
10826     .addOperand(Segment)
10827     .setMemRefs(MMOBegin, MMOEnd);
10828
10829   // If we need to align it, do so. Otherwise, just copy the address
10830   // to OverflowDestReg.
10831   if (NeedsAlign) {
10832     // Align the overflow address
10833     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10834     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10835
10836     // aligned_addr = (addr + (align-1)) & ~(align-1)
10837     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10838       .addReg(OverflowAddrReg)
10839       .addImm(Align-1);
10840
10841     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10842       .addReg(TmpReg)
10843       .addImm(~(uint64_t)(Align-1));
10844   } else {
10845     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10846       .addReg(OverflowAddrReg);
10847   }
10848
10849   // Compute the next overflow address after this argument.
10850   // (the overflow address should be kept 8-byte aligned)
10851   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10852   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10853     .addReg(OverflowDestReg)
10854     .addImm(ArgSizeA8);
10855
10856   // Store the new overflow address.
10857   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10858     .addOperand(Base)
10859     .addOperand(Scale)
10860     .addOperand(Index)
10861     .addDisp(Disp, 8)
10862     .addOperand(Segment)
10863     .addReg(NextAddrReg)
10864     .setMemRefs(MMOBegin, MMOEnd);
10865
10866   // If we branched, emit the PHI to the front of endMBB.
10867   if (offsetMBB) {
10868     BuildMI(*endMBB, endMBB->begin(), DL,
10869             TII->get(X86::PHI), DestReg)
10870       .addReg(OffsetDestReg).addMBB(offsetMBB)
10871       .addReg(OverflowDestReg).addMBB(overflowMBB);
10872   }
10873
10874   // Erase the pseudo instruction
10875   MI->eraseFromParent();
10876
10877   return endMBB;
10878 }
10879
10880 MachineBasicBlock *
10881 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10882                                                  MachineInstr *MI,
10883                                                  MachineBasicBlock *MBB) const {
10884   // Emit code to save XMM registers to the stack. The ABI says that the
10885   // number of registers to save is given in %al, so it's theoretically
10886   // possible to do an indirect jump trick to avoid saving all of them,
10887   // however this code takes a simpler approach and just executes all
10888   // of the stores if %al is non-zero. It's less code, and it's probably
10889   // easier on the hardware branch predictor, and stores aren't all that
10890   // expensive anyway.
10891
10892   // Create the new basic blocks. One block contains all the XMM stores,
10893   // and one block is the final destination regardless of whether any
10894   // stores were performed.
10895   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10896   MachineFunction *F = MBB->getParent();
10897   MachineFunction::iterator MBBIter = MBB;
10898   ++MBBIter;
10899   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10900   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10901   F->insert(MBBIter, XMMSaveMBB);
10902   F->insert(MBBIter, EndMBB);
10903
10904   // Transfer the remainder of MBB and its successor edges to EndMBB.
10905   EndMBB->splice(EndMBB->begin(), MBB,
10906                  llvm::next(MachineBasicBlock::iterator(MI)),
10907                  MBB->end());
10908   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10909
10910   // The original block will now fall through to the XMM save block.
10911   MBB->addSuccessor(XMMSaveMBB);
10912   // The XMMSaveMBB will fall through to the end block.
10913   XMMSaveMBB->addSuccessor(EndMBB);
10914
10915   // Now add the instructions.
10916   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10917   DebugLoc DL = MI->getDebugLoc();
10918
10919   unsigned CountReg = MI->getOperand(0).getReg();
10920   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10921   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10922
10923   if (!Subtarget->isTargetWin64()) {
10924     // If %al is 0, branch around the XMM save block.
10925     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10926     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10927     MBB->addSuccessor(EndMBB);
10928   }
10929
10930   // In the XMM save block, save all the XMM argument registers.
10931   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10932     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10933     MachineMemOperand *MMO =
10934       F->getMachineMemOperand(
10935           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10936         MachineMemOperand::MOStore,
10937         /*Size=*/16, /*Align=*/16);
10938     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10939       .addFrameIndex(RegSaveFrameIndex)
10940       .addImm(/*Scale=*/1)
10941       .addReg(/*IndexReg=*/0)
10942       .addImm(/*Disp=*/Offset)
10943       .addReg(/*Segment=*/0)
10944       .addReg(MI->getOperand(i).getReg())
10945       .addMemOperand(MMO);
10946   }
10947
10948   MI->eraseFromParent();   // The pseudo instruction is gone now.
10949
10950   return EndMBB;
10951 }
10952
10953 MachineBasicBlock *
10954 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10955                                      MachineBasicBlock *BB) const {
10956   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10957   DebugLoc DL = MI->getDebugLoc();
10958
10959   // To "insert" a SELECT_CC instruction, we actually have to insert the
10960   // diamond control-flow pattern.  The incoming instruction knows the
10961   // destination vreg to set, the condition code register to branch on, the
10962   // true/false values to select between, and a branch opcode to use.
10963   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10964   MachineFunction::iterator It = BB;
10965   ++It;
10966
10967   //  thisMBB:
10968   //  ...
10969   //   TrueVal = ...
10970   //   cmpTY ccX, r1, r2
10971   //   bCC copy1MBB
10972   //   fallthrough --> copy0MBB
10973   MachineBasicBlock *thisMBB = BB;
10974   MachineFunction *F = BB->getParent();
10975   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10976   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10977   F->insert(It, copy0MBB);
10978   F->insert(It, sinkMBB);
10979
10980   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10981   // live into the sink and copy blocks.
10982   const MachineFunction *MF = BB->getParent();
10983   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10984   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10985
10986   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10987     const MachineOperand &MO = MI->getOperand(I);
10988     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10989     unsigned Reg = MO.getReg();
10990     if (Reg != X86::EFLAGS) continue;
10991     copy0MBB->addLiveIn(Reg);
10992     sinkMBB->addLiveIn(Reg);
10993   }
10994
10995   // Transfer the remainder of BB and its successor edges to sinkMBB.
10996   sinkMBB->splice(sinkMBB->begin(), BB,
10997                   llvm::next(MachineBasicBlock::iterator(MI)),
10998                   BB->end());
10999   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11000
11001   // Add the true and fallthrough blocks as its successors.
11002   BB->addSuccessor(copy0MBB);
11003   BB->addSuccessor(sinkMBB);
11004
11005   // Create the conditional branch instruction.
11006   unsigned Opc =
11007     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11008   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11009
11010   //  copy0MBB:
11011   //   %FalseValue = ...
11012   //   # fallthrough to sinkMBB
11013   copy0MBB->addSuccessor(sinkMBB);
11014
11015   //  sinkMBB:
11016   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11017   //  ...
11018   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11019           TII->get(X86::PHI), MI->getOperand(0).getReg())
11020     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11021     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11022
11023   MI->eraseFromParent();   // The pseudo instruction is gone now.
11024   return sinkMBB;
11025 }
11026
11027 MachineBasicBlock *
11028 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11029                                           MachineBasicBlock *BB) const {
11030   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11031   DebugLoc DL = MI->getDebugLoc();
11032
11033   assert(!Subtarget->isTargetEnvMacho());
11034
11035   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11036   // non-trivial part is impdef of ESP.
11037
11038   if (Subtarget->isTargetWin64()) {
11039     if (Subtarget->isTargetCygMing()) {
11040       // ___chkstk(Mingw64):
11041       // Clobbers R10, R11, RAX and EFLAGS.
11042       // Updates RSP.
11043       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11044         .addExternalSymbol("___chkstk")
11045         .addReg(X86::RAX, RegState::Implicit)
11046         .addReg(X86::RSP, RegState::Implicit)
11047         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11048         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11049         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11050     } else {
11051       // __chkstk(MSVCRT): does not update stack pointer.
11052       // Clobbers R10, R11 and EFLAGS.
11053       // FIXME: RAX(allocated size) might be reused and not killed.
11054       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11055         .addExternalSymbol("__chkstk")
11056         .addReg(X86::RAX, RegState::Implicit)
11057         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11058       // RAX has the offset to subtracted from RSP.
11059       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11060         .addReg(X86::RSP)
11061         .addReg(X86::RAX);
11062     }
11063   } else {
11064     const char *StackProbeSymbol =
11065       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11066
11067     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11068       .addExternalSymbol(StackProbeSymbol)
11069       .addReg(X86::EAX, RegState::Implicit)
11070       .addReg(X86::ESP, RegState::Implicit)
11071       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11072       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11073       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11074   }
11075
11076   MI->eraseFromParent();   // The pseudo instruction is gone now.
11077   return BB;
11078 }
11079
11080 MachineBasicBlock *
11081 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11082                                       MachineBasicBlock *BB) const {
11083   // This is pretty easy.  We're taking the value that we received from
11084   // our load from the relocation, sticking it in either RDI (x86-64)
11085   // or EAX and doing an indirect call.  The return value will then
11086   // be in the normal return register.
11087   const X86InstrInfo *TII
11088     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11089   DebugLoc DL = MI->getDebugLoc();
11090   MachineFunction *F = BB->getParent();
11091
11092   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11093   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11094
11095   if (Subtarget->is64Bit()) {
11096     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11097                                       TII->get(X86::MOV64rm), X86::RDI)
11098     .addReg(X86::RIP)
11099     .addImm(0).addReg(0)
11100     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11101                       MI->getOperand(3).getTargetFlags())
11102     .addReg(0);
11103     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11104     addDirectMem(MIB, X86::RDI);
11105   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11106     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11107                                       TII->get(X86::MOV32rm), X86::EAX)
11108     .addReg(0)
11109     .addImm(0).addReg(0)
11110     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11111                       MI->getOperand(3).getTargetFlags())
11112     .addReg(0);
11113     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11114     addDirectMem(MIB, X86::EAX);
11115   } else {
11116     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11117                                       TII->get(X86::MOV32rm), X86::EAX)
11118     .addReg(TII->getGlobalBaseReg(F))
11119     .addImm(0).addReg(0)
11120     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11121                       MI->getOperand(3).getTargetFlags())
11122     .addReg(0);
11123     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11124     addDirectMem(MIB, X86::EAX);
11125   }
11126
11127   MI->eraseFromParent(); // The pseudo instruction is gone now.
11128   return BB;
11129 }
11130
11131 MachineBasicBlock *
11132 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11133                                                MachineBasicBlock *BB) const {
11134   switch (MI->getOpcode()) {
11135   default: assert(false && "Unexpected instr type to insert");
11136   case X86::TAILJMPd64:
11137   case X86::TAILJMPr64:
11138   case X86::TAILJMPm64:
11139     assert(!"TAILJMP64 would not be touched here.");
11140   case X86::TCRETURNdi64:
11141   case X86::TCRETURNri64:
11142   case X86::TCRETURNmi64:
11143     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11144     // On AMD64, additional defs should be added before register allocation.
11145     if (!Subtarget->isTargetWin64()) {
11146       MI->addRegisterDefined(X86::RSI);
11147       MI->addRegisterDefined(X86::RDI);
11148       MI->addRegisterDefined(X86::XMM6);
11149       MI->addRegisterDefined(X86::XMM7);
11150       MI->addRegisterDefined(X86::XMM8);
11151       MI->addRegisterDefined(X86::XMM9);
11152       MI->addRegisterDefined(X86::XMM10);
11153       MI->addRegisterDefined(X86::XMM11);
11154       MI->addRegisterDefined(X86::XMM12);
11155       MI->addRegisterDefined(X86::XMM13);
11156       MI->addRegisterDefined(X86::XMM14);
11157       MI->addRegisterDefined(X86::XMM15);
11158     }
11159     return BB;
11160   case X86::WIN_ALLOCA:
11161     return EmitLoweredWinAlloca(MI, BB);
11162   case X86::TLSCall_32:
11163   case X86::TLSCall_64:
11164     return EmitLoweredTLSCall(MI, BB);
11165   case X86::CMOV_GR8:
11166   case X86::CMOV_FR32:
11167   case X86::CMOV_FR64:
11168   case X86::CMOV_V4F32:
11169   case X86::CMOV_V2F64:
11170   case X86::CMOV_V2I64:
11171   case X86::CMOV_GR16:
11172   case X86::CMOV_GR32:
11173   case X86::CMOV_RFP32:
11174   case X86::CMOV_RFP64:
11175   case X86::CMOV_RFP80:
11176     return EmitLoweredSelect(MI, BB);
11177
11178   case X86::FP32_TO_INT16_IN_MEM:
11179   case X86::FP32_TO_INT32_IN_MEM:
11180   case X86::FP32_TO_INT64_IN_MEM:
11181   case X86::FP64_TO_INT16_IN_MEM:
11182   case X86::FP64_TO_INT32_IN_MEM:
11183   case X86::FP64_TO_INT64_IN_MEM:
11184   case X86::FP80_TO_INT16_IN_MEM:
11185   case X86::FP80_TO_INT32_IN_MEM:
11186   case X86::FP80_TO_INT64_IN_MEM: {
11187     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11188     DebugLoc DL = MI->getDebugLoc();
11189
11190     // Change the floating point control register to use "round towards zero"
11191     // mode when truncating to an integer value.
11192     MachineFunction *F = BB->getParent();
11193     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11194     addFrameReference(BuildMI(*BB, MI, DL,
11195                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
11196
11197     // Load the old value of the high byte of the control word...
11198     unsigned OldCW =
11199       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11200     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11201                       CWFrameIdx);
11202
11203     // Set the high part to be round to zero...
11204     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11205       .addImm(0xC7F);
11206
11207     // Reload the modified control word now...
11208     addFrameReference(BuildMI(*BB, MI, DL,
11209                               TII->get(X86::FLDCW16m)), CWFrameIdx);
11210
11211     // Restore the memory image of control word to original value
11212     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
11213       .addReg(OldCW);
11214
11215     // Get the X86 opcode to use.
11216     unsigned Opc;
11217     switch (MI->getOpcode()) {
11218     default: llvm_unreachable("illegal opcode!");
11219     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
11220     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
11221     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
11222     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
11223     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
11224     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
11225     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
11226     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
11227     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
11228     }
11229
11230     X86AddressMode AM;
11231     MachineOperand &Op = MI->getOperand(0);
11232     if (Op.isReg()) {
11233       AM.BaseType = X86AddressMode::RegBase;
11234       AM.Base.Reg = Op.getReg();
11235     } else {
11236       AM.BaseType = X86AddressMode::FrameIndexBase;
11237       AM.Base.FrameIndex = Op.getIndex();
11238     }
11239     Op = MI->getOperand(1);
11240     if (Op.isImm())
11241       AM.Scale = Op.getImm();
11242     Op = MI->getOperand(2);
11243     if (Op.isImm())
11244       AM.IndexReg = Op.getImm();
11245     Op = MI->getOperand(3);
11246     if (Op.isGlobal()) {
11247       AM.GV = Op.getGlobal();
11248     } else {
11249       AM.Disp = Op.getImm();
11250     }
11251     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
11252                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
11253
11254     // Reload the original control word now.
11255     addFrameReference(BuildMI(*BB, MI, DL,
11256                               TII->get(X86::FLDCW16m)), CWFrameIdx);
11257
11258     MI->eraseFromParent();   // The pseudo instruction is gone now.
11259     return BB;
11260   }
11261     // String/text processing lowering.
11262   case X86::PCMPISTRM128REG:
11263   case X86::VPCMPISTRM128REG:
11264     return EmitPCMP(MI, BB, 3, false /* in-mem */);
11265   case X86::PCMPISTRM128MEM:
11266   case X86::VPCMPISTRM128MEM:
11267     return EmitPCMP(MI, BB, 3, true /* in-mem */);
11268   case X86::PCMPESTRM128REG:
11269   case X86::VPCMPESTRM128REG:
11270     return EmitPCMP(MI, BB, 5, false /* in mem */);
11271   case X86::PCMPESTRM128MEM:
11272   case X86::VPCMPESTRM128MEM:
11273     return EmitPCMP(MI, BB, 5, true /* in mem */);
11274
11275     // Thread synchronization.
11276   case X86::MONITOR:
11277     return EmitMonitor(MI, BB);
11278   case X86::MWAIT:
11279     return EmitMwait(MI, BB);
11280
11281     // Atomic Lowering.
11282   case X86::ATOMAND32:
11283     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11284                                                X86::AND32ri, X86::MOV32rm,
11285                                                X86::LCMPXCHG32,
11286                                                X86::NOT32r, X86::EAX,
11287                                                X86::GR32RegisterClass);
11288   case X86::ATOMOR32:
11289     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
11290                                                X86::OR32ri, X86::MOV32rm,
11291                                                X86::LCMPXCHG32,
11292                                                X86::NOT32r, X86::EAX,
11293                                                X86::GR32RegisterClass);
11294   case X86::ATOMXOR32:
11295     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
11296                                                X86::XOR32ri, X86::MOV32rm,
11297                                                X86::LCMPXCHG32,
11298                                                X86::NOT32r, X86::EAX,
11299                                                X86::GR32RegisterClass);
11300   case X86::ATOMNAND32:
11301     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11302                                                X86::AND32ri, X86::MOV32rm,
11303                                                X86::LCMPXCHG32,
11304                                                X86::NOT32r, X86::EAX,
11305                                                X86::GR32RegisterClass, true);
11306   case X86::ATOMMIN32:
11307     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11308   case X86::ATOMMAX32:
11309     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11310   case X86::ATOMUMIN32:
11311     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11312   case X86::ATOMUMAX32:
11313     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11314
11315   case X86::ATOMAND16:
11316     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11317                                                X86::AND16ri, X86::MOV16rm,
11318                                                X86::LCMPXCHG16,
11319                                                X86::NOT16r, X86::AX,
11320                                                X86::GR16RegisterClass);
11321   case X86::ATOMOR16:
11322     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11323                                                X86::OR16ri, X86::MOV16rm,
11324                                                X86::LCMPXCHG16,
11325                                                X86::NOT16r, X86::AX,
11326                                                X86::GR16RegisterClass);
11327   case X86::ATOMXOR16:
11328     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11329                                                X86::XOR16ri, X86::MOV16rm,
11330                                                X86::LCMPXCHG16,
11331                                                X86::NOT16r, X86::AX,
11332                                                X86::GR16RegisterClass);
11333   case X86::ATOMNAND16:
11334     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11335                                                X86::AND16ri, X86::MOV16rm,
11336                                                X86::LCMPXCHG16,
11337                                                X86::NOT16r, X86::AX,
11338                                                X86::GR16RegisterClass, true);
11339   case X86::ATOMMIN16:
11340     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11341   case X86::ATOMMAX16:
11342     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11343   case X86::ATOMUMIN16:
11344     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11345   case X86::ATOMUMAX16:
11346     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11347
11348   case X86::ATOMAND8:
11349     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11350                                                X86::AND8ri, X86::MOV8rm,
11351                                                X86::LCMPXCHG8,
11352                                                X86::NOT8r, X86::AL,
11353                                                X86::GR8RegisterClass);
11354   case X86::ATOMOR8:
11355     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11356                                                X86::OR8ri, X86::MOV8rm,
11357                                                X86::LCMPXCHG8,
11358                                                X86::NOT8r, X86::AL,
11359                                                X86::GR8RegisterClass);
11360   case X86::ATOMXOR8:
11361     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11362                                                X86::XOR8ri, X86::MOV8rm,
11363                                                X86::LCMPXCHG8,
11364                                                X86::NOT8r, X86::AL,
11365                                                X86::GR8RegisterClass);
11366   case X86::ATOMNAND8:
11367     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11368                                                X86::AND8ri, X86::MOV8rm,
11369                                                X86::LCMPXCHG8,
11370                                                X86::NOT8r, X86::AL,
11371                                                X86::GR8RegisterClass, true);
11372   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11373   // This group is for 64-bit host.
11374   case X86::ATOMAND64:
11375     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11376                                                X86::AND64ri32, X86::MOV64rm,
11377                                                X86::LCMPXCHG64,
11378                                                X86::NOT64r, X86::RAX,
11379                                                X86::GR64RegisterClass);
11380   case X86::ATOMOR64:
11381     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11382                                                X86::OR64ri32, X86::MOV64rm,
11383                                                X86::LCMPXCHG64,
11384                                                X86::NOT64r, X86::RAX,
11385                                                X86::GR64RegisterClass);
11386   case X86::ATOMXOR64:
11387     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11388                                                X86::XOR64ri32, X86::MOV64rm,
11389                                                X86::LCMPXCHG64,
11390                                                X86::NOT64r, X86::RAX,
11391                                                X86::GR64RegisterClass);
11392   case X86::ATOMNAND64:
11393     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11394                                                X86::AND64ri32, X86::MOV64rm,
11395                                                X86::LCMPXCHG64,
11396                                                X86::NOT64r, X86::RAX,
11397                                                X86::GR64RegisterClass, true);
11398   case X86::ATOMMIN64:
11399     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11400   case X86::ATOMMAX64:
11401     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11402   case X86::ATOMUMIN64:
11403     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11404   case X86::ATOMUMAX64:
11405     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11406
11407   // This group does 64-bit operations on a 32-bit host.
11408   case X86::ATOMAND6432:
11409     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11410                                                X86::AND32rr, X86::AND32rr,
11411                                                X86::AND32ri, X86::AND32ri,
11412                                                false);
11413   case X86::ATOMOR6432:
11414     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11415                                                X86::OR32rr, X86::OR32rr,
11416                                                X86::OR32ri, X86::OR32ri,
11417                                                false);
11418   case X86::ATOMXOR6432:
11419     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11420                                                X86::XOR32rr, X86::XOR32rr,
11421                                                X86::XOR32ri, X86::XOR32ri,
11422                                                false);
11423   case X86::ATOMNAND6432:
11424     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11425                                                X86::AND32rr, X86::AND32rr,
11426                                                X86::AND32ri, X86::AND32ri,
11427                                                true);
11428   case X86::ATOMADD6432:
11429     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11430                                                X86::ADD32rr, X86::ADC32rr,
11431                                                X86::ADD32ri, X86::ADC32ri,
11432                                                false);
11433   case X86::ATOMSUB6432:
11434     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11435                                                X86::SUB32rr, X86::SBB32rr,
11436                                                X86::SUB32ri, X86::SBB32ri,
11437                                                false);
11438   case X86::ATOMSWAP6432:
11439     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11440                                                X86::MOV32rr, X86::MOV32rr,
11441                                                X86::MOV32ri, X86::MOV32ri,
11442                                                false);
11443   case X86::VASTART_SAVE_XMM_REGS:
11444     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11445
11446   case X86::VAARG_64:
11447     return EmitVAARG64WithCustomInserter(MI, BB);
11448   }
11449 }
11450
11451 //===----------------------------------------------------------------------===//
11452 //                           X86 Optimization Hooks
11453 //===----------------------------------------------------------------------===//
11454
11455 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11456                                                        const APInt &Mask,
11457                                                        APInt &KnownZero,
11458                                                        APInt &KnownOne,
11459                                                        const SelectionDAG &DAG,
11460                                                        unsigned Depth) const {
11461   unsigned Opc = Op.getOpcode();
11462   assert((Opc >= ISD::BUILTIN_OP_END ||
11463           Opc == ISD::INTRINSIC_WO_CHAIN ||
11464           Opc == ISD::INTRINSIC_W_CHAIN ||
11465           Opc == ISD::INTRINSIC_VOID) &&
11466          "Should use MaskedValueIsZero if you don't know whether Op"
11467          " is a target node!");
11468
11469   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11470   switch (Opc) {
11471   default: break;
11472   case X86ISD::ADD:
11473   case X86ISD::SUB:
11474   case X86ISD::ADC:
11475   case X86ISD::SBB:
11476   case X86ISD::SMUL:
11477   case X86ISD::UMUL:
11478   case X86ISD::INC:
11479   case X86ISD::DEC:
11480   case X86ISD::OR:
11481   case X86ISD::XOR:
11482   case X86ISD::AND:
11483     // These nodes' second result is a boolean.
11484     if (Op.getResNo() == 0)
11485       break;
11486     // Fallthrough
11487   case X86ISD::SETCC:
11488     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11489                                        Mask.getBitWidth() - 1);
11490     break;
11491   }
11492 }
11493
11494 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11495                                                          unsigned Depth) const {
11496   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11497   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11498     return Op.getValueType().getScalarType().getSizeInBits();
11499
11500   // Fallback case.
11501   return 1;
11502 }
11503
11504 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11505 /// node is a GlobalAddress + offset.
11506 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11507                                        const GlobalValue* &GA,
11508                                        int64_t &Offset) const {
11509   if (N->getOpcode() == X86ISD::Wrapper) {
11510     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11511       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11512       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11513       return true;
11514     }
11515   }
11516   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11517 }
11518
11519 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
11520 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
11521                                         TargetLowering::DAGCombinerInfo &DCI) {
11522   DebugLoc dl = N->getDebugLoc();
11523   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
11524   SDValue V1 = SVOp->getOperand(0);
11525   SDValue V2 = SVOp->getOperand(1);
11526   EVT VT = SVOp->getValueType(0);
11527
11528   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
11529       V2.getOpcode() == ISD::CONCAT_VECTORS) {
11530     //
11531     //                   0,0,0,...
11532     //                      |
11533     //    V      UNDEF    BUILD_VECTOR    UNDEF
11534     //     \      /           \           /
11535     //  CONCAT_VECTOR         CONCAT_VECTOR
11536     //         \                  /
11537     //          \                /
11538     //          RESULT: V + zero extended
11539     //
11540     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
11541         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
11542         V1.getOperand(1).getOpcode() != ISD::UNDEF)
11543       return SDValue();
11544
11545     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
11546       return SDValue();
11547
11548     // To match the shuffle mask, the first half of the mask should
11549     // be exactly the first vector, and all the rest a splat with the
11550     // first element of the second one.
11551     int NumElems = VT.getVectorNumElements();
11552     for (int i = 0; i < NumElems/2; ++i)
11553       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
11554           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
11555         return SDValue();
11556
11557     // Emit a zeroed vector and insert the desired subvector on its
11558     // first half.
11559     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
11560     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
11561                          DAG.getConstant(0, MVT::i32), DAG, dl);
11562     return DCI.CombineTo(N, InsV);
11563   }
11564
11565   return SDValue();
11566 }
11567
11568 /// PerformShuffleCombine - Performs several different shuffle combines.
11569 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11570                                      TargetLowering::DAGCombinerInfo &DCI) {
11571   DebugLoc dl = N->getDebugLoc();
11572   EVT VT = N->getValueType(0);
11573
11574   // Don't create instructions with illegal types after legalize types has run.
11575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11576   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11577     return SDValue();
11578
11579   // Only handle pure VECTOR_SHUFFLE nodes.
11580   if (VT.getSizeInBits() == 256 && N->getOpcode() == ISD::VECTOR_SHUFFLE)
11581     return PerformShuffleCombine256(N, DAG, DCI);
11582
11583   // Only handle 128 wide vector from here on.
11584   if (VT.getSizeInBits() != 128)
11585     return SDValue();
11586
11587   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
11588   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
11589   // consecutive, non-overlapping, and in the right order.
11590   SmallVector<SDValue, 16> Elts;
11591   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11592     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11593
11594   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11595 }
11596
11597 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11598 /// generation and convert it from being a bunch of shuffles and extracts
11599 /// to a simple store and scalar loads to extract the elements.
11600 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11601                                                 const TargetLowering &TLI) {
11602   SDValue InputVector = N->getOperand(0);
11603
11604   // Only operate on vectors of 4 elements, where the alternative shuffling
11605   // gets to be more expensive.
11606   if (InputVector.getValueType() != MVT::v4i32)
11607     return SDValue();
11608
11609   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11610   // single use which is a sign-extend or zero-extend, and all elements are
11611   // used.
11612   SmallVector<SDNode *, 4> Uses;
11613   unsigned ExtractedElements = 0;
11614   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11615        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11616     if (UI.getUse().getResNo() != InputVector.getResNo())
11617       return SDValue();
11618
11619     SDNode *Extract = *UI;
11620     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11621       return SDValue();
11622
11623     if (Extract->getValueType(0) != MVT::i32)
11624       return SDValue();
11625     if (!Extract->hasOneUse())
11626       return SDValue();
11627     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11628         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11629       return SDValue();
11630     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11631       return SDValue();
11632
11633     // Record which element was extracted.
11634     ExtractedElements |=
11635       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11636
11637     Uses.push_back(Extract);
11638   }
11639
11640   // If not all the elements were used, this may not be worthwhile.
11641   if (ExtractedElements != 15)
11642     return SDValue();
11643
11644   // Ok, we've now decided to do the transformation.
11645   DebugLoc dl = InputVector.getDebugLoc();
11646
11647   // Store the value to a temporary stack slot.
11648   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11649   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11650                             MachinePointerInfo(), false, false, 0);
11651
11652   // Replace each use (extract) with a load of the appropriate element.
11653   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11654        UE = Uses.end(); UI != UE; ++UI) {
11655     SDNode *Extract = *UI;
11656
11657     // cOMpute the element's address.
11658     SDValue Idx = Extract->getOperand(1);
11659     unsigned EltSize =
11660         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11661     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11662     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11663
11664     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11665                                      StackPtr, OffsetVal);
11666
11667     // Load the scalar.
11668     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11669                                      ScalarAddr, MachinePointerInfo(),
11670                                      false, false, 0);
11671
11672     // Replace the exact with the load.
11673     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11674   }
11675
11676   // The replacement was made in place; don't return anything.
11677   return SDValue();
11678 }
11679
11680 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11681 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11682                                     const X86Subtarget *Subtarget) {
11683   DebugLoc DL = N->getDebugLoc();
11684   SDValue Cond = N->getOperand(0);
11685   // Get the LHS/RHS of the select.
11686   SDValue LHS = N->getOperand(1);
11687   SDValue RHS = N->getOperand(2);
11688
11689   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11690   // instructions match the semantics of the common C idiom x<y?x:y but not
11691   // x<=y?x:y, because of how they handle negative zero (which can be
11692   // ignored in unsafe-math mode).
11693   if (Subtarget->hasSSE2() &&
11694       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11695       Cond.getOpcode() == ISD::SETCC) {
11696     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11697
11698     unsigned Opcode = 0;
11699     // Check for x CC y ? x : y.
11700     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11701         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11702       switch (CC) {
11703       default: break;
11704       case ISD::SETULT:
11705         // Converting this to a min would handle NaNs incorrectly, and swapping
11706         // the operands would cause it to handle comparisons between positive
11707         // and negative zero incorrectly.
11708         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11709           if (!UnsafeFPMath &&
11710               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11711             break;
11712           std::swap(LHS, RHS);
11713         }
11714         Opcode = X86ISD::FMIN;
11715         break;
11716       case ISD::SETOLE:
11717         // Converting this to a min would handle comparisons between positive
11718         // and negative zero incorrectly.
11719         if (!UnsafeFPMath &&
11720             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11721           break;
11722         Opcode = X86ISD::FMIN;
11723         break;
11724       case ISD::SETULE:
11725         // Converting this to a min would handle both negative zeros and NaNs
11726         // incorrectly, but we can swap the operands to fix both.
11727         std::swap(LHS, RHS);
11728       case ISD::SETOLT:
11729       case ISD::SETLT:
11730       case ISD::SETLE:
11731         Opcode = X86ISD::FMIN;
11732         break;
11733
11734       case ISD::SETOGE:
11735         // Converting this to a max would handle comparisons between positive
11736         // and negative zero incorrectly.
11737         if (!UnsafeFPMath &&
11738             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11739           break;
11740         Opcode = X86ISD::FMAX;
11741         break;
11742       case ISD::SETUGT:
11743         // Converting this to a max would handle NaNs incorrectly, and swapping
11744         // the operands would cause it to handle comparisons between positive
11745         // and negative zero incorrectly.
11746         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11747           if (!UnsafeFPMath &&
11748               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11749             break;
11750           std::swap(LHS, RHS);
11751         }
11752         Opcode = X86ISD::FMAX;
11753         break;
11754       case ISD::SETUGE:
11755         // Converting this to a max would handle both negative zeros and NaNs
11756         // incorrectly, but we can swap the operands to fix both.
11757         std::swap(LHS, RHS);
11758       case ISD::SETOGT:
11759       case ISD::SETGT:
11760       case ISD::SETGE:
11761         Opcode = X86ISD::FMAX;
11762         break;
11763       }
11764     // Check for x CC y ? y : x -- a min/max with reversed arms.
11765     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11766                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11767       switch (CC) {
11768       default: break;
11769       case ISD::SETOGE:
11770         // Converting this to a min would handle comparisons between positive
11771         // and negative zero incorrectly, and swapping the operands would
11772         // cause it to handle NaNs incorrectly.
11773         if (!UnsafeFPMath &&
11774             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11775           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11776             break;
11777           std::swap(LHS, RHS);
11778         }
11779         Opcode = X86ISD::FMIN;
11780         break;
11781       case ISD::SETUGT:
11782         // Converting this to a min would handle NaNs incorrectly.
11783         if (!UnsafeFPMath &&
11784             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11785           break;
11786         Opcode = X86ISD::FMIN;
11787         break;
11788       case ISD::SETUGE:
11789         // Converting this to a min would handle both negative zeros and NaNs
11790         // incorrectly, but we can swap the operands to fix both.
11791         std::swap(LHS, RHS);
11792       case ISD::SETOGT:
11793       case ISD::SETGT:
11794       case ISD::SETGE:
11795         Opcode = X86ISD::FMIN;
11796         break;
11797
11798       case ISD::SETULT:
11799         // Converting this to a max would handle NaNs incorrectly.
11800         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11801           break;
11802         Opcode = X86ISD::FMAX;
11803         break;
11804       case ISD::SETOLE:
11805         // Converting this to a max would handle comparisons between positive
11806         // and negative zero incorrectly, and swapping the operands would
11807         // cause it to handle NaNs incorrectly.
11808         if (!UnsafeFPMath &&
11809             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11810           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11811             break;
11812           std::swap(LHS, RHS);
11813         }
11814         Opcode = X86ISD::FMAX;
11815         break;
11816       case ISD::SETULE:
11817         // Converting this to a max would handle both negative zeros and NaNs
11818         // incorrectly, but we can swap the operands to fix both.
11819         std::swap(LHS, RHS);
11820       case ISD::SETOLT:
11821       case ISD::SETLT:
11822       case ISD::SETLE:
11823         Opcode = X86ISD::FMAX;
11824         break;
11825       }
11826     }
11827
11828     if (Opcode)
11829       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11830   }
11831
11832   // If this is a select between two integer constants, try to do some
11833   // optimizations.
11834   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11835     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11836       // Don't do this for crazy integer types.
11837       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11838         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11839         // so that TrueC (the true value) is larger than FalseC.
11840         bool NeedsCondInvert = false;
11841
11842         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11843             // Efficiently invertible.
11844             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11845              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11846               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11847           NeedsCondInvert = true;
11848           std::swap(TrueC, FalseC);
11849         }
11850
11851         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11852         if (FalseC->getAPIntValue() == 0 &&
11853             TrueC->getAPIntValue().isPowerOf2()) {
11854           if (NeedsCondInvert) // Invert the condition if needed.
11855             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11856                                DAG.getConstant(1, Cond.getValueType()));
11857
11858           // Zero extend the condition if needed.
11859           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11860
11861           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11862           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11863                              DAG.getConstant(ShAmt, MVT::i8));
11864         }
11865
11866         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11867         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11868           if (NeedsCondInvert) // Invert the condition if needed.
11869             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11870                                DAG.getConstant(1, Cond.getValueType()));
11871
11872           // Zero extend the condition if needed.
11873           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11874                              FalseC->getValueType(0), Cond);
11875           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11876                              SDValue(FalseC, 0));
11877         }
11878
11879         // Optimize cases that will turn into an LEA instruction.  This requires
11880         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11881         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11882           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11883           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11884
11885           bool isFastMultiplier = false;
11886           if (Diff < 10) {
11887             switch ((unsigned char)Diff) {
11888               default: break;
11889               case 1:  // result = add base, cond
11890               case 2:  // result = lea base(    , cond*2)
11891               case 3:  // result = lea base(cond, cond*2)
11892               case 4:  // result = lea base(    , cond*4)
11893               case 5:  // result = lea base(cond, cond*4)
11894               case 8:  // result = lea base(    , cond*8)
11895               case 9:  // result = lea base(cond, cond*8)
11896                 isFastMultiplier = true;
11897                 break;
11898             }
11899           }
11900
11901           if (isFastMultiplier) {
11902             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11903             if (NeedsCondInvert) // Invert the condition if needed.
11904               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11905                                  DAG.getConstant(1, Cond.getValueType()));
11906
11907             // Zero extend the condition if needed.
11908             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11909                                Cond);
11910             // Scale the condition by the difference.
11911             if (Diff != 1)
11912               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11913                                  DAG.getConstant(Diff, Cond.getValueType()));
11914
11915             // Add the base if non-zero.
11916             if (FalseC->getAPIntValue() != 0)
11917               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11918                                  SDValue(FalseC, 0));
11919             return Cond;
11920           }
11921         }
11922       }
11923   }
11924
11925   return SDValue();
11926 }
11927
11928 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11929 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11930                                   TargetLowering::DAGCombinerInfo &DCI) {
11931   DebugLoc DL = N->getDebugLoc();
11932
11933   // If the flag operand isn't dead, don't touch this CMOV.
11934   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11935     return SDValue();
11936
11937   SDValue FalseOp = N->getOperand(0);
11938   SDValue TrueOp = N->getOperand(1);
11939   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11940   SDValue Cond = N->getOperand(3);
11941   if (CC == X86::COND_E || CC == X86::COND_NE) {
11942     switch (Cond.getOpcode()) {
11943     default: break;
11944     case X86ISD::BSR:
11945     case X86ISD::BSF:
11946       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11947       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11948         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11949     }
11950   }
11951
11952   // If this is a select between two integer constants, try to do some
11953   // optimizations.  Note that the operands are ordered the opposite of SELECT
11954   // operands.
11955   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11956     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11957       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11958       // larger than FalseC (the false value).
11959       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11960         CC = X86::GetOppositeBranchCondition(CC);
11961         std::swap(TrueC, FalseC);
11962       }
11963
11964       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11965       // This is efficient for any integer data type (including i8/i16) and
11966       // shift amount.
11967       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11968         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11969                            DAG.getConstant(CC, MVT::i8), Cond);
11970
11971         // Zero extend the condition if needed.
11972         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11973
11974         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11975         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11976                            DAG.getConstant(ShAmt, MVT::i8));
11977         if (N->getNumValues() == 2)  // Dead flag value?
11978           return DCI.CombineTo(N, Cond, SDValue());
11979         return Cond;
11980       }
11981
11982       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11983       // for any integer data type, including i8/i16.
11984       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11985         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11986                            DAG.getConstant(CC, MVT::i8), Cond);
11987
11988         // Zero extend the condition if needed.
11989         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11990                            FalseC->getValueType(0), Cond);
11991         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11992                            SDValue(FalseC, 0));
11993
11994         if (N->getNumValues() == 2)  // Dead flag value?
11995           return DCI.CombineTo(N, Cond, SDValue());
11996         return Cond;
11997       }
11998
11999       // Optimize cases that will turn into an LEA instruction.  This requires
12000       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12001       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12002         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12003         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12004
12005         bool isFastMultiplier = false;
12006         if (Diff < 10) {
12007           switch ((unsigned char)Diff) {
12008           default: break;
12009           case 1:  // result = add base, cond
12010           case 2:  // result = lea base(    , cond*2)
12011           case 3:  // result = lea base(cond, cond*2)
12012           case 4:  // result = lea base(    , cond*4)
12013           case 5:  // result = lea base(cond, cond*4)
12014           case 8:  // result = lea base(    , cond*8)
12015           case 9:  // result = lea base(cond, cond*8)
12016             isFastMultiplier = true;
12017             break;
12018           }
12019         }
12020
12021         if (isFastMultiplier) {
12022           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12023           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12024                              DAG.getConstant(CC, MVT::i8), Cond);
12025           // Zero extend the condition if needed.
12026           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12027                              Cond);
12028           // Scale the condition by the difference.
12029           if (Diff != 1)
12030             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12031                                DAG.getConstant(Diff, Cond.getValueType()));
12032
12033           // Add the base if non-zero.
12034           if (FalseC->getAPIntValue() != 0)
12035             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12036                                SDValue(FalseC, 0));
12037           if (N->getNumValues() == 2)  // Dead flag value?
12038             return DCI.CombineTo(N, Cond, SDValue());
12039           return Cond;
12040         }
12041       }
12042     }
12043   }
12044   return SDValue();
12045 }
12046
12047
12048 /// PerformMulCombine - Optimize a single multiply with constant into two
12049 /// in order to implement it with two cheaper instructions, e.g.
12050 /// LEA + SHL, LEA + LEA.
12051 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12052                                  TargetLowering::DAGCombinerInfo &DCI) {
12053   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12054     return SDValue();
12055
12056   EVT VT = N->getValueType(0);
12057   if (VT != MVT::i64)
12058     return SDValue();
12059
12060   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12061   if (!C)
12062     return SDValue();
12063   uint64_t MulAmt = C->getZExtValue();
12064   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12065     return SDValue();
12066
12067   uint64_t MulAmt1 = 0;
12068   uint64_t MulAmt2 = 0;
12069   if ((MulAmt % 9) == 0) {
12070     MulAmt1 = 9;
12071     MulAmt2 = MulAmt / 9;
12072   } else if ((MulAmt % 5) == 0) {
12073     MulAmt1 = 5;
12074     MulAmt2 = MulAmt / 5;
12075   } else if ((MulAmt % 3) == 0) {
12076     MulAmt1 = 3;
12077     MulAmt2 = MulAmt / 3;
12078   }
12079   if (MulAmt2 &&
12080       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12081     DebugLoc DL = N->getDebugLoc();
12082
12083     if (isPowerOf2_64(MulAmt2) &&
12084         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12085       // If second multiplifer is pow2, issue it first. We want the multiply by
12086       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12087       // is an add.
12088       std::swap(MulAmt1, MulAmt2);
12089
12090     SDValue NewMul;
12091     if (isPowerOf2_64(MulAmt1))
12092       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12093                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12094     else
12095       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12096                            DAG.getConstant(MulAmt1, VT));
12097
12098     if (isPowerOf2_64(MulAmt2))
12099       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12100                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12101     else
12102       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12103                            DAG.getConstant(MulAmt2, VT));
12104
12105     // Do not add new nodes to DAG combiner worklist.
12106     DCI.CombineTo(N, NewMul, false);
12107   }
12108   return SDValue();
12109 }
12110
12111 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12112   SDValue N0 = N->getOperand(0);
12113   SDValue N1 = N->getOperand(1);
12114   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12115   EVT VT = N0.getValueType();
12116
12117   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12118   // since the result of setcc_c is all zero's or all ones.
12119   if (N1C && N0.getOpcode() == ISD::AND &&
12120       N0.getOperand(1).getOpcode() == ISD::Constant) {
12121     SDValue N00 = N0.getOperand(0);
12122     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12123         ((N00.getOpcode() == ISD::ANY_EXTEND ||
12124           N00.getOpcode() == ISD::ZERO_EXTEND) &&
12125          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12126       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12127       APInt ShAmt = N1C->getAPIntValue();
12128       Mask = Mask.shl(ShAmt);
12129       if (Mask != 0)
12130         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12131                            N00, DAG.getConstant(Mask, VT));
12132     }
12133   }
12134
12135   return SDValue();
12136 }
12137
12138 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12139 ///                       when possible.
12140 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12141                                    const X86Subtarget *Subtarget) {
12142   EVT VT = N->getValueType(0);
12143   if (!VT.isVector() && VT.isInteger() &&
12144       N->getOpcode() == ISD::SHL)
12145     return PerformSHLCombine(N, DAG);
12146
12147   // On X86 with SSE2 support, we can transform this to a vector shift if
12148   // all elements are shifted by the same amount.  We can't do this in legalize
12149   // because the a constant vector is typically transformed to a constant pool
12150   // so we have no knowledge of the shift amount.
12151   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12152     return SDValue();
12153
12154   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
12155     return SDValue();
12156
12157   SDValue ShAmtOp = N->getOperand(1);
12158   EVT EltVT = VT.getVectorElementType();
12159   DebugLoc DL = N->getDebugLoc();
12160   SDValue BaseShAmt = SDValue();
12161   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
12162     unsigned NumElts = VT.getVectorNumElements();
12163     unsigned i = 0;
12164     for (; i != NumElts; ++i) {
12165       SDValue Arg = ShAmtOp.getOperand(i);
12166       if (Arg.getOpcode() == ISD::UNDEF) continue;
12167       BaseShAmt = Arg;
12168       break;
12169     }
12170     for (; i != NumElts; ++i) {
12171       SDValue Arg = ShAmtOp.getOperand(i);
12172       if (Arg.getOpcode() == ISD::UNDEF) continue;
12173       if (Arg != BaseShAmt) {
12174         return SDValue();
12175       }
12176     }
12177   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
12178              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
12179     SDValue InVec = ShAmtOp.getOperand(0);
12180     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12181       unsigned NumElts = InVec.getValueType().getVectorNumElements();
12182       unsigned i = 0;
12183       for (; i != NumElts; ++i) {
12184         SDValue Arg = InVec.getOperand(i);
12185         if (Arg.getOpcode() == ISD::UNDEF) continue;
12186         BaseShAmt = Arg;
12187         break;
12188       }
12189     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12190        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12191          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
12192          if (C->getZExtValue() == SplatIdx)
12193            BaseShAmt = InVec.getOperand(1);
12194        }
12195     }
12196     if (BaseShAmt.getNode() == 0)
12197       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
12198                               DAG.getIntPtrConstant(0));
12199   } else
12200     return SDValue();
12201
12202   // The shift amount is an i32.
12203   if (EltVT.bitsGT(MVT::i32))
12204     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
12205   else if (EltVT.bitsLT(MVT::i32))
12206     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
12207
12208   // The shift amount is identical so we can do a vector shift.
12209   SDValue  ValOp = N->getOperand(0);
12210   switch (N->getOpcode()) {
12211   default:
12212     llvm_unreachable("Unknown shift opcode!");
12213     break;
12214   case ISD::SHL:
12215     if (VT == MVT::v2i64)
12216       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12217                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
12218                          ValOp, BaseShAmt);
12219     if (VT == MVT::v4i32)
12220       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12221                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
12222                          ValOp, BaseShAmt);
12223     if (VT == MVT::v8i16)
12224       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12225                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
12226                          ValOp, BaseShAmt);
12227     break;
12228   case ISD::SRA:
12229     if (VT == MVT::v4i32)
12230       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12231                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
12232                          ValOp, BaseShAmt);
12233     if (VT == MVT::v8i16)
12234       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12235                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
12236                          ValOp, BaseShAmt);
12237     break;
12238   case ISD::SRL:
12239     if (VT == MVT::v2i64)
12240       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12241                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
12242                          ValOp, BaseShAmt);
12243     if (VT == MVT::v4i32)
12244       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12245                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
12246                          ValOp, BaseShAmt);
12247     if (VT ==  MVT::v8i16)
12248       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12249                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
12250                          ValOp, BaseShAmt);
12251     break;
12252   }
12253   return SDValue();
12254 }
12255
12256
12257 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
12258 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
12259 // and friends.  Likewise for OR -> CMPNEQSS.
12260 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
12261                             TargetLowering::DAGCombinerInfo &DCI,
12262                             const X86Subtarget *Subtarget) {
12263   unsigned opcode;
12264
12265   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
12266   // we're requiring SSE2 for both.
12267   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
12268     SDValue N0 = N->getOperand(0);
12269     SDValue N1 = N->getOperand(1);
12270     SDValue CMP0 = N0->getOperand(1);
12271     SDValue CMP1 = N1->getOperand(1);
12272     DebugLoc DL = N->getDebugLoc();
12273
12274     // The SETCCs should both refer to the same CMP.
12275     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
12276       return SDValue();
12277
12278     SDValue CMP00 = CMP0->getOperand(0);
12279     SDValue CMP01 = CMP0->getOperand(1);
12280     EVT     VT    = CMP00.getValueType();
12281
12282     if (VT == MVT::f32 || VT == MVT::f64) {
12283       bool ExpectingFlags = false;
12284       // Check for any users that want flags:
12285       for (SDNode::use_iterator UI = N->use_begin(),
12286              UE = N->use_end();
12287            !ExpectingFlags && UI != UE; ++UI)
12288         switch (UI->getOpcode()) {
12289         default:
12290         case ISD::BR_CC:
12291         case ISD::BRCOND:
12292         case ISD::SELECT:
12293           ExpectingFlags = true;
12294           break;
12295         case ISD::CopyToReg:
12296         case ISD::SIGN_EXTEND:
12297         case ISD::ZERO_EXTEND:
12298         case ISD::ANY_EXTEND:
12299           break;
12300         }
12301
12302       if (!ExpectingFlags) {
12303         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
12304         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
12305
12306         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
12307           X86::CondCode tmp = cc0;
12308           cc0 = cc1;
12309           cc1 = tmp;
12310         }
12311
12312         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
12313             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
12314           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
12315           X86ISD::NodeType NTOperator = is64BitFP ?
12316             X86ISD::FSETCCsd : X86ISD::FSETCCss;
12317           // FIXME: need symbolic constants for these magic numbers.
12318           // See X86ATTInstPrinter.cpp:printSSECC().
12319           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
12320           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
12321                                               DAG.getConstant(x86cc, MVT::i8));
12322           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
12323                                               OnesOrZeroesF);
12324           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
12325                                       DAG.getConstant(1, MVT::i32));
12326           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
12327           return OneBitOfTruth;
12328         }
12329       }
12330     }
12331   }
12332   return SDValue();
12333 }
12334
12335 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
12336 /// so it can be folded inside ANDNP.
12337 static bool CanFoldXORWithAllOnes(const SDNode *N) {
12338   EVT VT = N->getValueType(0);
12339
12340   // Match direct AllOnes for 128 and 256-bit vectors
12341   if (ISD::isBuildVectorAllOnes(N))
12342     return true;
12343
12344   // Look through a bit convert.
12345   if (N->getOpcode() == ISD::BITCAST)
12346     N = N->getOperand(0).getNode();
12347
12348   // Sometimes the operand may come from a insert_subvector building a 256-bit
12349   // allones vector
12350   if (VT.getSizeInBits() == 256 &&
12351       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
12352     SDValue V1 = N->getOperand(0);
12353     SDValue V2 = N->getOperand(1);
12354
12355     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
12356         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
12357         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
12358         ISD::isBuildVectorAllOnes(V2.getNode()))
12359       return true;
12360   }
12361
12362   return false;
12363 }
12364
12365 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
12366                                  TargetLowering::DAGCombinerInfo &DCI,
12367                                  const X86Subtarget *Subtarget) {
12368   if (DCI.isBeforeLegalizeOps())
12369     return SDValue();
12370
12371   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12372   if (R.getNode())
12373     return R;
12374
12375   // Want to form ANDNP nodes:
12376   // 1) In the hopes of then easily combining them with OR and AND nodes
12377   //    to form PBLEND/PSIGN.
12378   // 2) To match ANDN packed intrinsics
12379   EVT VT = N->getValueType(0);
12380   if (VT != MVT::v2i64 && VT != MVT::v4i64)
12381     return SDValue();
12382
12383   SDValue N0 = N->getOperand(0);
12384   SDValue N1 = N->getOperand(1);
12385   DebugLoc DL = N->getDebugLoc();
12386
12387   // Check LHS for vnot
12388   if (N0.getOpcode() == ISD::XOR &&
12389       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12390       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
12391     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12392
12393   // Check RHS for vnot
12394   if (N1.getOpcode() == ISD::XOR &&
12395       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12396       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
12397     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12398
12399   return SDValue();
12400 }
12401
12402 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12403                                 TargetLowering::DAGCombinerInfo &DCI,
12404                                 const X86Subtarget *Subtarget) {
12405   if (DCI.isBeforeLegalizeOps())
12406     return SDValue();
12407
12408   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12409   if (R.getNode())
12410     return R;
12411
12412   EVT VT = N->getValueType(0);
12413   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12414     return SDValue();
12415
12416   SDValue N0 = N->getOperand(0);
12417   SDValue N1 = N->getOperand(1);
12418
12419   // look for psign/blend
12420   if (Subtarget->hasSSSE3()) {
12421     if (VT == MVT::v2i64) {
12422       // Canonicalize pandn to RHS
12423       if (N0.getOpcode() == X86ISD::ANDNP)
12424         std::swap(N0, N1);
12425       // or (and (m, x), (pandn m, y))
12426       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12427         SDValue Mask = N1.getOperand(0);
12428         SDValue X    = N1.getOperand(1);
12429         SDValue Y;
12430         if (N0.getOperand(0) == Mask)
12431           Y = N0.getOperand(1);
12432         if (N0.getOperand(1) == Mask)
12433           Y = N0.getOperand(0);
12434
12435         // Check to see if the mask appeared in both the AND and ANDNP and
12436         if (!Y.getNode())
12437           return SDValue();
12438
12439         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12440         if (Mask.getOpcode() != ISD::BITCAST ||
12441             X.getOpcode() != ISD::BITCAST ||
12442             Y.getOpcode() != ISD::BITCAST)
12443           return SDValue();
12444
12445         // Look through mask bitcast.
12446         Mask = Mask.getOperand(0);
12447         EVT MaskVT = Mask.getValueType();
12448
12449         // Validate that the Mask operand is a vector sra node.  The sra node
12450         // will be an intrinsic.
12451         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12452           return SDValue();
12453
12454         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12455         // there is no psrai.b
12456         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12457         case Intrinsic::x86_sse2_psrai_w:
12458         case Intrinsic::x86_sse2_psrai_d:
12459           break;
12460         default: return SDValue();
12461         }
12462
12463         // Check that the SRA is all signbits.
12464         SDValue SraC = Mask.getOperand(2);
12465         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
12466         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12467         if ((SraAmt + 1) != EltBits)
12468           return SDValue();
12469
12470         DebugLoc DL = N->getDebugLoc();
12471
12472         // Now we know we at least have a plendvb with the mask val.  See if
12473         // we can form a psignb/w/d.
12474         // psign = x.type == y.type == mask.type && y = sub(0, x);
12475         X = X.getOperand(0);
12476         Y = Y.getOperand(0);
12477         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12478             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12479             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12480           unsigned Opc = 0;
12481           switch (EltBits) {
12482           case 8: Opc = X86ISD::PSIGNB; break;
12483           case 16: Opc = X86ISD::PSIGNW; break;
12484           case 32: Opc = X86ISD::PSIGND; break;
12485           default: break;
12486           }
12487           if (Opc) {
12488             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12489             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12490           }
12491         }
12492         // PBLENDVB only available on SSE 4.1
12493         if (!Subtarget->hasSSE41())
12494           return SDValue();
12495
12496         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12497         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12498         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12499         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12500         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12501       }
12502     }
12503   }
12504
12505   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12506   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12507     std::swap(N0, N1);
12508   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12509     return SDValue();
12510   if (!N0.hasOneUse() || !N1.hasOneUse())
12511     return SDValue();
12512
12513   SDValue ShAmt0 = N0.getOperand(1);
12514   if (ShAmt0.getValueType() != MVT::i8)
12515     return SDValue();
12516   SDValue ShAmt1 = N1.getOperand(1);
12517   if (ShAmt1.getValueType() != MVT::i8)
12518     return SDValue();
12519   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12520     ShAmt0 = ShAmt0.getOperand(0);
12521   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12522     ShAmt1 = ShAmt1.getOperand(0);
12523
12524   DebugLoc DL = N->getDebugLoc();
12525   unsigned Opc = X86ISD::SHLD;
12526   SDValue Op0 = N0.getOperand(0);
12527   SDValue Op1 = N1.getOperand(0);
12528   if (ShAmt0.getOpcode() == ISD::SUB) {
12529     Opc = X86ISD::SHRD;
12530     std::swap(Op0, Op1);
12531     std::swap(ShAmt0, ShAmt1);
12532   }
12533
12534   unsigned Bits = VT.getSizeInBits();
12535   if (ShAmt1.getOpcode() == ISD::SUB) {
12536     SDValue Sum = ShAmt1.getOperand(0);
12537     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12538       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12539       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12540         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12541       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12542         return DAG.getNode(Opc, DL, VT,
12543                            Op0, Op1,
12544                            DAG.getNode(ISD::TRUNCATE, DL,
12545                                        MVT::i8, ShAmt0));
12546     }
12547   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12548     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12549     if (ShAmt0C &&
12550         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12551       return DAG.getNode(Opc, DL, VT,
12552                          N0.getOperand(0), N1.getOperand(0),
12553                          DAG.getNode(ISD::TRUNCATE, DL,
12554                                        MVT::i8, ShAmt0));
12555   }
12556
12557   return SDValue();
12558 }
12559
12560 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12561 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12562                                    const X86Subtarget *Subtarget) {
12563   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12564   // the FP state in cases where an emms may be missing.
12565   // A preferable solution to the general problem is to figure out the right
12566   // places to insert EMMS.  This qualifies as a quick hack.
12567
12568   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12569   StoreSDNode *St = cast<StoreSDNode>(N);
12570   EVT VT = St->getValue().getValueType();
12571   if (VT.getSizeInBits() != 64)
12572     return SDValue();
12573
12574   const Function *F = DAG.getMachineFunction().getFunction();
12575   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12576   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12577     && Subtarget->hasSSE2();
12578   if ((VT.isVector() ||
12579        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12580       isa<LoadSDNode>(St->getValue()) &&
12581       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12582       St->getChain().hasOneUse() && !St->isVolatile()) {
12583     SDNode* LdVal = St->getValue().getNode();
12584     LoadSDNode *Ld = 0;
12585     int TokenFactorIndex = -1;
12586     SmallVector<SDValue, 8> Ops;
12587     SDNode* ChainVal = St->getChain().getNode();
12588     // Must be a store of a load.  We currently handle two cases:  the load
12589     // is a direct child, and it's under an intervening TokenFactor.  It is
12590     // possible to dig deeper under nested TokenFactors.
12591     if (ChainVal == LdVal)
12592       Ld = cast<LoadSDNode>(St->getChain());
12593     else if (St->getValue().hasOneUse() &&
12594              ChainVal->getOpcode() == ISD::TokenFactor) {
12595       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12596         if (ChainVal->getOperand(i).getNode() == LdVal) {
12597           TokenFactorIndex = i;
12598           Ld = cast<LoadSDNode>(St->getValue());
12599         } else
12600           Ops.push_back(ChainVal->getOperand(i));
12601       }
12602     }
12603
12604     if (!Ld || !ISD::isNormalLoad(Ld))
12605       return SDValue();
12606
12607     // If this is not the MMX case, i.e. we are just turning i64 load/store
12608     // into f64 load/store, avoid the transformation if there are multiple
12609     // uses of the loaded value.
12610     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12611       return SDValue();
12612
12613     DebugLoc LdDL = Ld->getDebugLoc();
12614     DebugLoc StDL = N->getDebugLoc();
12615     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12616     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12617     // pair instead.
12618     if (Subtarget->is64Bit() || F64IsLegal) {
12619       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12620       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12621                                   Ld->getPointerInfo(), Ld->isVolatile(),
12622                                   Ld->isNonTemporal(), Ld->getAlignment());
12623       SDValue NewChain = NewLd.getValue(1);
12624       if (TokenFactorIndex != -1) {
12625         Ops.push_back(NewChain);
12626         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12627                                Ops.size());
12628       }
12629       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12630                           St->getPointerInfo(),
12631                           St->isVolatile(), St->isNonTemporal(),
12632                           St->getAlignment());
12633     }
12634
12635     // Otherwise, lower to two pairs of 32-bit loads / stores.
12636     SDValue LoAddr = Ld->getBasePtr();
12637     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12638                                  DAG.getConstant(4, MVT::i32));
12639
12640     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12641                                Ld->getPointerInfo(),
12642                                Ld->isVolatile(), Ld->isNonTemporal(),
12643                                Ld->getAlignment());
12644     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12645                                Ld->getPointerInfo().getWithOffset(4),
12646                                Ld->isVolatile(), Ld->isNonTemporal(),
12647                                MinAlign(Ld->getAlignment(), 4));
12648
12649     SDValue NewChain = LoLd.getValue(1);
12650     if (TokenFactorIndex != -1) {
12651       Ops.push_back(LoLd);
12652       Ops.push_back(HiLd);
12653       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12654                              Ops.size());
12655     }
12656
12657     LoAddr = St->getBasePtr();
12658     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12659                          DAG.getConstant(4, MVT::i32));
12660
12661     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12662                                 St->getPointerInfo(),
12663                                 St->isVolatile(), St->isNonTemporal(),
12664                                 St->getAlignment());
12665     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12666                                 St->getPointerInfo().getWithOffset(4),
12667                                 St->isVolatile(),
12668                                 St->isNonTemporal(),
12669                                 MinAlign(St->getAlignment(), 4));
12670     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12671   }
12672   return SDValue();
12673 }
12674
12675 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12676 /// X86ISD::FXOR nodes.
12677 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12678   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12679   // F[X]OR(0.0, x) -> x
12680   // F[X]OR(x, 0.0) -> x
12681   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12682     if (C->getValueAPF().isPosZero())
12683       return N->getOperand(1);
12684   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12685     if (C->getValueAPF().isPosZero())
12686       return N->getOperand(0);
12687   return SDValue();
12688 }
12689
12690 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12691 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12692   // FAND(0.0, x) -> 0.0
12693   // FAND(x, 0.0) -> 0.0
12694   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12695     if (C->getValueAPF().isPosZero())
12696       return N->getOperand(0);
12697   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12698     if (C->getValueAPF().isPosZero())
12699       return N->getOperand(1);
12700   return SDValue();
12701 }
12702
12703 static SDValue PerformBTCombine(SDNode *N,
12704                                 SelectionDAG &DAG,
12705                                 TargetLowering::DAGCombinerInfo &DCI) {
12706   // BT ignores high bits in the bit index operand.
12707   SDValue Op1 = N->getOperand(1);
12708   if (Op1.hasOneUse()) {
12709     unsigned BitWidth = Op1.getValueSizeInBits();
12710     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12711     APInt KnownZero, KnownOne;
12712     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12713                                           !DCI.isBeforeLegalizeOps());
12714     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12715     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12716         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12717       DCI.CommitTargetLoweringOpt(TLO);
12718   }
12719   return SDValue();
12720 }
12721
12722 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12723   SDValue Op = N->getOperand(0);
12724   if (Op.getOpcode() == ISD::BITCAST)
12725     Op = Op.getOperand(0);
12726   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12727   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12728       VT.getVectorElementType().getSizeInBits() ==
12729       OpVT.getVectorElementType().getSizeInBits()) {
12730     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12731   }
12732   return SDValue();
12733 }
12734
12735 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12736   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12737   //           (and (i32 x86isd::setcc_carry), 1)
12738   // This eliminates the zext. This transformation is necessary because
12739   // ISD::SETCC is always legalized to i8.
12740   DebugLoc dl = N->getDebugLoc();
12741   SDValue N0 = N->getOperand(0);
12742   EVT VT = N->getValueType(0);
12743   if (N0.getOpcode() == ISD::AND &&
12744       N0.hasOneUse() &&
12745       N0.getOperand(0).hasOneUse()) {
12746     SDValue N00 = N0.getOperand(0);
12747     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12748       return SDValue();
12749     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12750     if (!C || C->getZExtValue() != 1)
12751       return SDValue();
12752     return DAG.getNode(ISD::AND, dl, VT,
12753                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12754                                    N00.getOperand(0), N00.getOperand(1)),
12755                        DAG.getConstant(1, VT));
12756   }
12757
12758   return SDValue();
12759 }
12760
12761 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12762 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12763   unsigned X86CC = N->getConstantOperandVal(0);
12764   SDValue EFLAG = N->getOperand(1);
12765   DebugLoc DL = N->getDebugLoc();
12766
12767   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12768   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12769   // cases.
12770   if (X86CC == X86::COND_B)
12771     return DAG.getNode(ISD::AND, DL, MVT::i8,
12772                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12773                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12774                        DAG.getConstant(1, MVT::i8));
12775
12776   return SDValue();
12777 }
12778
12779 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12780                                         const X86TargetLowering *XTLI) {
12781   SDValue Op0 = N->getOperand(0);
12782   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12783   // a 32-bit target where SSE doesn't support i64->FP operations.
12784   if (Op0.getOpcode() == ISD::LOAD) {
12785     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12786     EVT VT = Ld->getValueType(0);
12787     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12788         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12789         !XTLI->getSubtarget()->is64Bit() &&
12790         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12791       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12792                                           Ld->getChain(), Op0, DAG);
12793       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12794       return FILDChain;
12795     }
12796   }
12797   return SDValue();
12798 }
12799
12800 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12801 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12802                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12803   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12804   // the result is either zero or one (depending on the input carry bit).
12805   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12806   if (X86::isZeroNode(N->getOperand(0)) &&
12807       X86::isZeroNode(N->getOperand(1)) &&
12808       // We don't have a good way to replace an EFLAGS use, so only do this when
12809       // dead right now.
12810       SDValue(N, 1).use_empty()) {
12811     DebugLoc DL = N->getDebugLoc();
12812     EVT VT = N->getValueType(0);
12813     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12814     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12815                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12816                                            DAG.getConstant(X86::COND_B,MVT::i8),
12817                                            N->getOperand(2)),
12818                                DAG.getConstant(1, VT));
12819     return DCI.CombineTo(N, Res1, CarryOut);
12820   }
12821
12822   return SDValue();
12823 }
12824
12825 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12826 //      (add Y, (setne X, 0)) -> sbb -1, Y
12827 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12828 //      (sub (setne X, 0), Y) -> adc -1, Y
12829 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
12830   DebugLoc DL = N->getDebugLoc();
12831
12832   // Look through ZExts.
12833   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12834   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12835     return SDValue();
12836
12837   SDValue SetCC = Ext.getOperand(0);
12838   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12839     return SDValue();
12840
12841   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12842   if (CC != X86::COND_E && CC != X86::COND_NE)
12843     return SDValue();
12844
12845   SDValue Cmp = SetCC.getOperand(1);
12846   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12847       !X86::isZeroNode(Cmp.getOperand(1)) ||
12848       !Cmp.getOperand(0).getValueType().isInteger())
12849     return SDValue();
12850
12851   SDValue CmpOp0 = Cmp.getOperand(0);
12852   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12853                                DAG.getConstant(1, CmpOp0.getValueType()));
12854
12855   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12856   if (CC == X86::COND_NE)
12857     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12858                        DL, OtherVal.getValueType(), OtherVal,
12859                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12860   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12861                      DL, OtherVal.getValueType(), OtherVal,
12862                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12863 }
12864
12865 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
12866   SDValue Op0 = N->getOperand(0);
12867   SDValue Op1 = N->getOperand(1);
12868
12869   // X86 can't encode an immediate LHS of a sub. See if we can push the
12870   // negation into a preceding instruction.
12871   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
12872     uint64_t Op0C = C->getSExtValue();
12873
12874     // If the RHS of the sub is a XOR with one use and a constant, invert the
12875     // immediate. Then add one to the LHS of the sub so we can turn
12876     // X-Y -> X+~Y+1, saving one register.
12877     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
12878         isa<ConstantSDNode>(Op1.getOperand(1))) {
12879       uint64_t XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getSExtValue();
12880       EVT VT = Op0.getValueType();
12881       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
12882                                    Op1.getOperand(0),
12883                                    DAG.getConstant(~XorC, VT));
12884       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
12885                          DAG.getConstant(Op0C+1, VT));
12886     }
12887   }
12888
12889   return OptimizeConditionalInDecrement(N, DAG);
12890 }
12891
12892 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12893                                              DAGCombinerInfo &DCI) const {
12894   SelectionDAG &DAG = DCI.DAG;
12895   switch (N->getOpcode()) {
12896   default: break;
12897   case ISD::EXTRACT_VECTOR_ELT:
12898     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12899   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12900   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12901   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
12902   case ISD::SUB:            return PerformSubCombine(N, DAG);
12903   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12904   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12905   case ISD::SHL:
12906   case ISD::SRA:
12907   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12908   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12909   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12910   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12911   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12912   case X86ISD::FXOR:
12913   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12914   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12915   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12916   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12917   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12918   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12919   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12920   case X86ISD::SHUFPD:
12921   case X86ISD::PALIGN:
12922   case X86ISD::PUNPCKHBW:
12923   case X86ISD::PUNPCKHWD:
12924   case X86ISD::PUNPCKHDQ:
12925   case X86ISD::PUNPCKHQDQ:
12926   case X86ISD::UNPCKHPS:
12927   case X86ISD::UNPCKHPD:
12928   case X86ISD::VUNPCKHPSY:
12929   case X86ISD::VUNPCKHPDY:
12930   case X86ISD::PUNPCKLBW:
12931   case X86ISD::PUNPCKLWD:
12932   case X86ISD::PUNPCKLDQ:
12933   case X86ISD::PUNPCKLQDQ:
12934   case X86ISD::UNPCKLPS:
12935   case X86ISD::UNPCKLPD:
12936   case X86ISD::VUNPCKLPSY:
12937   case X86ISD::VUNPCKLPDY:
12938   case X86ISD::MOVHLPS:
12939   case X86ISD::MOVLHPS:
12940   case X86ISD::PSHUFD:
12941   case X86ISD::PSHUFHW:
12942   case X86ISD::PSHUFLW:
12943   case X86ISD::MOVSS:
12944   case X86ISD::MOVSD:
12945   case X86ISD::VPERMILPS:
12946   case X86ISD::VPERMILPSY:
12947   case X86ISD::VPERMILPD:
12948   case X86ISD::VPERMILPDY:
12949   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12950   }
12951
12952   return SDValue();
12953 }
12954
12955 /// isTypeDesirableForOp - Return true if the target has native support for
12956 /// the specified value type and it is 'desirable' to use the type for the
12957 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12958 /// instruction encodings are longer and some i16 instructions are slow.
12959 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12960   if (!isTypeLegal(VT))
12961     return false;
12962   if (VT != MVT::i16)
12963     return true;
12964
12965   switch (Opc) {
12966   default:
12967     return true;
12968   case ISD::LOAD:
12969   case ISD::SIGN_EXTEND:
12970   case ISD::ZERO_EXTEND:
12971   case ISD::ANY_EXTEND:
12972   case ISD::SHL:
12973   case ISD::SRL:
12974   case ISD::SUB:
12975   case ISD::ADD:
12976   case ISD::MUL:
12977   case ISD::AND:
12978   case ISD::OR:
12979   case ISD::XOR:
12980     return false;
12981   }
12982 }
12983
12984 /// IsDesirableToPromoteOp - This method query the target whether it is
12985 /// beneficial for dag combiner to promote the specified node. If true, it
12986 /// should return the desired promotion type by reference.
12987 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12988   EVT VT = Op.getValueType();
12989   if (VT != MVT::i16)
12990     return false;
12991
12992   bool Promote = false;
12993   bool Commute = false;
12994   switch (Op.getOpcode()) {
12995   default: break;
12996   case ISD::LOAD: {
12997     LoadSDNode *LD = cast<LoadSDNode>(Op);
12998     // If the non-extending load has a single use and it's not live out, then it
12999     // might be folded.
13000     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13001                                                      Op.hasOneUse()*/) {
13002       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13003              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13004         // The only case where we'd want to promote LOAD (rather then it being
13005         // promoted as an operand is when it's only use is liveout.
13006         if (UI->getOpcode() != ISD::CopyToReg)
13007           return false;
13008       }
13009     }
13010     Promote = true;
13011     break;
13012   }
13013   case ISD::SIGN_EXTEND:
13014   case ISD::ZERO_EXTEND:
13015   case ISD::ANY_EXTEND:
13016     Promote = true;
13017     break;
13018   case ISD::SHL:
13019   case ISD::SRL: {
13020     SDValue N0 = Op.getOperand(0);
13021     // Look out for (store (shl (load), x)).
13022     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13023       return false;
13024     Promote = true;
13025     break;
13026   }
13027   case ISD::ADD:
13028   case ISD::MUL:
13029   case ISD::AND:
13030   case ISD::OR:
13031   case ISD::XOR:
13032     Commute = true;
13033     // fallthrough
13034   case ISD::SUB: {
13035     SDValue N0 = Op.getOperand(0);
13036     SDValue N1 = Op.getOperand(1);
13037     if (!Commute && MayFoldLoad(N1))
13038       return false;
13039     // Avoid disabling potential load folding opportunities.
13040     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13041       return false;
13042     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13043       return false;
13044     Promote = true;
13045   }
13046   }
13047
13048   PVT = MVT::i32;
13049   return Promote;
13050 }
13051
13052 //===----------------------------------------------------------------------===//
13053 //                           X86 Inline Assembly Support
13054 //===----------------------------------------------------------------------===//
13055
13056 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
13057   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13058
13059   std::string AsmStr = IA->getAsmString();
13060
13061   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
13062   SmallVector<StringRef, 4> AsmPieces;
13063   SplitString(AsmStr, AsmPieces, ";\n");
13064
13065   switch (AsmPieces.size()) {
13066   default: return false;
13067   case 1:
13068     AsmStr = AsmPieces[0];
13069     AsmPieces.clear();
13070     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
13071
13072     // FIXME: this should verify that we are targeting a 486 or better.  If not,
13073     // we will turn this bswap into something that will be lowered to logical ops
13074     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
13075     // so don't worry about this.
13076     // bswap $0
13077     if (AsmPieces.size() == 2 &&
13078         (AsmPieces[0] == "bswap" ||
13079          AsmPieces[0] == "bswapq" ||
13080          AsmPieces[0] == "bswapl") &&
13081         (AsmPieces[1] == "$0" ||
13082          AsmPieces[1] == "${0:q}")) {
13083       // No need to check constraints, nothing other than the equivalent of
13084       // "=r,0" would be valid here.
13085       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13086       if (!Ty || Ty->getBitWidth() % 16 != 0)
13087         return false;
13088       return IntrinsicLowering::LowerToByteSwap(CI);
13089     }
13090     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
13091     if (CI->getType()->isIntegerTy(16) &&
13092         AsmPieces.size() == 3 &&
13093         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
13094         AsmPieces[1] == "$$8," &&
13095         AsmPieces[2] == "${0:w}" &&
13096         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13097       AsmPieces.clear();
13098       const std::string &ConstraintsStr = IA->getConstraintString();
13099       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13100       std::sort(AsmPieces.begin(), AsmPieces.end());
13101       if (AsmPieces.size() == 4 &&
13102           AsmPieces[0] == "~{cc}" &&
13103           AsmPieces[1] == "~{dirflag}" &&
13104           AsmPieces[2] == "~{flags}" &&
13105           AsmPieces[3] == "~{fpsr}") {
13106         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13107         if (!Ty || Ty->getBitWidth() % 16 != 0)
13108           return false;
13109         return IntrinsicLowering::LowerToByteSwap(CI);
13110       }
13111     }
13112     break;
13113   case 3:
13114     if (CI->getType()->isIntegerTy(32) &&
13115         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13116       SmallVector<StringRef, 4> Words;
13117       SplitString(AsmPieces[0], Words, " \t,");
13118       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13119           Words[2] == "${0:w}") {
13120         Words.clear();
13121         SplitString(AsmPieces[1], Words, " \t,");
13122         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
13123             Words[2] == "$0") {
13124           Words.clear();
13125           SplitString(AsmPieces[2], Words, " \t,");
13126           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13127               Words[2] == "${0:w}") {
13128             AsmPieces.clear();
13129             const std::string &ConstraintsStr = IA->getConstraintString();
13130             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13131             std::sort(AsmPieces.begin(), AsmPieces.end());
13132             if (AsmPieces.size() == 4 &&
13133                 AsmPieces[0] == "~{cc}" &&
13134                 AsmPieces[1] == "~{dirflag}" &&
13135                 AsmPieces[2] == "~{flags}" &&
13136                 AsmPieces[3] == "~{fpsr}") {
13137               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13138               if (!Ty || Ty->getBitWidth() % 16 != 0)
13139                 return false;
13140               return IntrinsicLowering::LowerToByteSwap(CI);
13141             }
13142           }
13143         }
13144       }
13145     }
13146
13147     if (CI->getType()->isIntegerTy(64)) {
13148       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
13149       if (Constraints.size() >= 2 &&
13150           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
13151           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
13152         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
13153         SmallVector<StringRef, 4> Words;
13154         SplitString(AsmPieces[0], Words, " \t");
13155         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
13156           Words.clear();
13157           SplitString(AsmPieces[1], Words, " \t");
13158           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
13159             Words.clear();
13160             SplitString(AsmPieces[2], Words, " \t,");
13161             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
13162                 Words[2] == "%edx") {
13163               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13164               if (!Ty || Ty->getBitWidth() % 16 != 0)
13165                 return false;
13166               return IntrinsicLowering::LowerToByteSwap(CI);
13167             }
13168           }
13169         }
13170       }
13171     }
13172     break;
13173   }
13174   return false;
13175 }
13176
13177
13178
13179 /// getConstraintType - Given a constraint letter, return the type of
13180 /// constraint it is for this target.
13181 X86TargetLowering::ConstraintType
13182 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
13183   if (Constraint.size() == 1) {
13184     switch (Constraint[0]) {
13185     case 'R':
13186     case 'q':
13187     case 'Q':
13188     case 'f':
13189     case 't':
13190     case 'u':
13191     case 'y':
13192     case 'x':
13193     case 'Y':
13194     case 'l':
13195       return C_RegisterClass;
13196     case 'a':
13197     case 'b':
13198     case 'c':
13199     case 'd':
13200     case 'S':
13201     case 'D':
13202     case 'A':
13203       return C_Register;
13204     case 'I':
13205     case 'J':
13206     case 'K':
13207     case 'L':
13208     case 'M':
13209     case 'N':
13210     case 'G':
13211     case 'C':
13212     case 'e':
13213     case 'Z':
13214       return C_Other;
13215     default:
13216       break;
13217     }
13218   }
13219   return TargetLowering::getConstraintType(Constraint);
13220 }
13221
13222 /// Examine constraint type and operand type and determine a weight value.
13223 /// This object must already have been set up with the operand type
13224 /// and the current alternative constraint selected.
13225 TargetLowering::ConstraintWeight
13226   X86TargetLowering::getSingleConstraintMatchWeight(
13227     AsmOperandInfo &info, const char *constraint) const {
13228   ConstraintWeight weight = CW_Invalid;
13229   Value *CallOperandVal = info.CallOperandVal;
13230     // If we don't have a value, we can't do a match,
13231     // but allow it at the lowest weight.
13232   if (CallOperandVal == NULL)
13233     return CW_Default;
13234   Type *type = CallOperandVal->getType();
13235   // Look at the constraint type.
13236   switch (*constraint) {
13237   default:
13238     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13239   case 'R':
13240   case 'q':
13241   case 'Q':
13242   case 'a':
13243   case 'b':
13244   case 'c':
13245   case 'd':
13246   case 'S':
13247   case 'D':
13248   case 'A':
13249     if (CallOperandVal->getType()->isIntegerTy())
13250       weight = CW_SpecificReg;
13251     break;
13252   case 'f':
13253   case 't':
13254   case 'u':
13255       if (type->isFloatingPointTy())
13256         weight = CW_SpecificReg;
13257       break;
13258   case 'y':
13259       if (type->isX86_MMXTy() && Subtarget->hasMMX())
13260         weight = CW_SpecificReg;
13261       break;
13262   case 'x':
13263   case 'Y':
13264     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
13265       weight = CW_Register;
13266     break;
13267   case 'I':
13268     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
13269       if (C->getZExtValue() <= 31)
13270         weight = CW_Constant;
13271     }
13272     break;
13273   case 'J':
13274     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13275       if (C->getZExtValue() <= 63)
13276         weight = CW_Constant;
13277     }
13278     break;
13279   case 'K':
13280     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13281       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
13282         weight = CW_Constant;
13283     }
13284     break;
13285   case 'L':
13286     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13287       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
13288         weight = CW_Constant;
13289     }
13290     break;
13291   case 'M':
13292     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13293       if (C->getZExtValue() <= 3)
13294         weight = CW_Constant;
13295     }
13296     break;
13297   case 'N':
13298     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13299       if (C->getZExtValue() <= 0xff)
13300         weight = CW_Constant;
13301     }
13302     break;
13303   case 'G':
13304   case 'C':
13305     if (dyn_cast<ConstantFP>(CallOperandVal)) {
13306       weight = CW_Constant;
13307     }
13308     break;
13309   case 'e':
13310     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13311       if ((C->getSExtValue() >= -0x80000000LL) &&
13312           (C->getSExtValue() <= 0x7fffffffLL))
13313         weight = CW_Constant;
13314     }
13315     break;
13316   case 'Z':
13317     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13318       if (C->getZExtValue() <= 0xffffffff)
13319         weight = CW_Constant;
13320     }
13321     break;
13322   }
13323   return weight;
13324 }
13325
13326 /// LowerXConstraint - try to replace an X constraint, which matches anything,
13327 /// with another that has more specific requirements based on the type of the
13328 /// corresponding operand.
13329 const char *X86TargetLowering::
13330 LowerXConstraint(EVT ConstraintVT) const {
13331   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
13332   // 'f' like normal targets.
13333   if (ConstraintVT.isFloatingPoint()) {
13334     if (Subtarget->hasXMMInt())
13335       return "Y";
13336     if (Subtarget->hasXMM())
13337       return "x";
13338   }
13339
13340   return TargetLowering::LowerXConstraint(ConstraintVT);
13341 }
13342
13343 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13344 /// vector.  If it is invalid, don't add anything to Ops.
13345 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13346                                                      std::string &Constraint,
13347                                                      std::vector<SDValue>&Ops,
13348                                                      SelectionDAG &DAG) const {
13349   SDValue Result(0, 0);
13350
13351   // Only support length 1 constraints for now.
13352   if (Constraint.length() > 1) return;
13353
13354   char ConstraintLetter = Constraint[0];
13355   switch (ConstraintLetter) {
13356   default: break;
13357   case 'I':
13358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13359       if (C->getZExtValue() <= 31) {
13360         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13361         break;
13362       }
13363     }
13364     return;
13365   case 'J':
13366     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13367       if (C->getZExtValue() <= 63) {
13368         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13369         break;
13370       }
13371     }
13372     return;
13373   case 'K':
13374     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13375       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
13376         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13377         break;
13378       }
13379     }
13380     return;
13381   case 'N':
13382     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13383       if (C->getZExtValue() <= 255) {
13384         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13385         break;
13386       }
13387     }
13388     return;
13389   case 'e': {
13390     // 32-bit signed value
13391     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13392       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13393                                            C->getSExtValue())) {
13394         // Widen to 64 bits here to get it sign extended.
13395         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
13396         break;
13397       }
13398     // FIXME gcc accepts some relocatable values here too, but only in certain
13399     // memory models; it's complicated.
13400     }
13401     return;
13402   }
13403   case 'Z': {
13404     // 32-bit unsigned value
13405     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13406       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13407                                            C->getZExtValue())) {
13408         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13409         break;
13410       }
13411     }
13412     // FIXME gcc accepts some relocatable values here too, but only in certain
13413     // memory models; it's complicated.
13414     return;
13415   }
13416   case 'i': {
13417     // Literal immediates are always ok.
13418     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13419       // Widen to 64 bits here to get it sign extended.
13420       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13421       break;
13422     }
13423
13424     // In any sort of PIC mode addresses need to be computed at runtime by
13425     // adding in a register or some sort of table lookup.  These can't
13426     // be used as immediates.
13427     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13428       return;
13429
13430     // If we are in non-pic codegen mode, we allow the address of a global (with
13431     // an optional displacement) to be used with 'i'.
13432     GlobalAddressSDNode *GA = 0;
13433     int64_t Offset = 0;
13434
13435     // Match either (GA), (GA+C), (GA+C1+C2), etc.
13436     while (1) {
13437       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13438         Offset += GA->getOffset();
13439         break;
13440       } else if (Op.getOpcode() == ISD::ADD) {
13441         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13442           Offset += C->getZExtValue();
13443           Op = Op.getOperand(0);
13444           continue;
13445         }
13446       } else if (Op.getOpcode() == ISD::SUB) {
13447         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13448           Offset += -C->getZExtValue();
13449           Op = Op.getOperand(0);
13450           continue;
13451         }
13452       }
13453
13454       // Otherwise, this isn't something we can handle, reject it.
13455       return;
13456     }
13457
13458     const GlobalValue *GV = GA->getGlobal();
13459     // If we require an extra load to get this address, as in PIC mode, we
13460     // can't accept it.
13461     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
13462                                                         getTargetMachine())))
13463       return;
13464
13465     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
13466                                         GA->getValueType(0), Offset);
13467     break;
13468   }
13469   }
13470
13471   if (Result.getNode()) {
13472     Ops.push_back(Result);
13473     return;
13474   }
13475   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13476 }
13477
13478 std::pair<unsigned, const TargetRegisterClass*>
13479 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
13480                                                 EVT VT) const {
13481   // First, see if this is a constraint that directly corresponds to an LLVM
13482   // register class.
13483   if (Constraint.size() == 1) {
13484     // GCC Constraint Letters
13485     switch (Constraint[0]) {
13486     default: break;
13487       // TODO: Slight differences here in allocation order and leaving
13488       // RIP in the class. Do they matter any more here than they do
13489       // in the normal allocation?
13490     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13491       if (Subtarget->is64Bit()) {
13492         if (VT == MVT::i32 || VT == MVT::f32)
13493           return std::make_pair(0U, X86::GR32RegisterClass);
13494         else if (VT == MVT::i16)
13495           return std::make_pair(0U, X86::GR16RegisterClass);
13496         else if (VT == MVT::i8 || VT == MVT::i1)
13497           return std::make_pair(0U, X86::GR8RegisterClass);
13498         else if (VT == MVT::i64 || VT == MVT::f64)
13499           return std::make_pair(0U, X86::GR64RegisterClass);
13500         break;
13501       }
13502       // 32-bit fallthrough
13503     case 'Q':   // Q_REGS
13504       if (VT == MVT::i32 || VT == MVT::f32)
13505         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
13506       else if (VT == MVT::i16)
13507         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
13508       else if (VT == MVT::i8 || VT == MVT::i1)
13509         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
13510       else if (VT == MVT::i64)
13511         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
13512       break;
13513     case 'r':   // GENERAL_REGS
13514     case 'l':   // INDEX_REGS
13515       if (VT == MVT::i8 || VT == MVT::i1)
13516         return std::make_pair(0U, X86::GR8RegisterClass);
13517       if (VT == MVT::i16)
13518         return std::make_pair(0U, X86::GR16RegisterClass);
13519       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
13520         return std::make_pair(0U, X86::GR32RegisterClass);
13521       return std::make_pair(0U, X86::GR64RegisterClass);
13522     case 'R':   // LEGACY_REGS
13523       if (VT == MVT::i8 || VT == MVT::i1)
13524         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13525       if (VT == MVT::i16)
13526         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13527       if (VT == MVT::i32 || !Subtarget->is64Bit())
13528         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13529       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13530     case 'f':  // FP Stack registers.
13531       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13532       // value to the correct fpstack register class.
13533       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13534         return std::make_pair(0U, X86::RFP32RegisterClass);
13535       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13536         return std::make_pair(0U, X86::RFP64RegisterClass);
13537       return std::make_pair(0U, X86::RFP80RegisterClass);
13538     case 'y':   // MMX_REGS if MMX allowed.
13539       if (!Subtarget->hasMMX()) break;
13540       return std::make_pair(0U, X86::VR64RegisterClass);
13541     case 'Y':   // SSE_REGS if SSE2 allowed
13542       if (!Subtarget->hasXMMInt()) break;
13543       // FALL THROUGH.
13544     case 'x':   // SSE_REGS if SSE1 allowed
13545       if (!Subtarget->hasXMM()) break;
13546
13547       switch (VT.getSimpleVT().SimpleTy) {
13548       default: break;
13549       // Scalar SSE types.
13550       case MVT::f32:
13551       case MVT::i32:
13552         return std::make_pair(0U, X86::FR32RegisterClass);
13553       case MVT::f64:
13554       case MVT::i64:
13555         return std::make_pair(0U, X86::FR64RegisterClass);
13556       // Vector types.
13557       case MVT::v16i8:
13558       case MVT::v8i16:
13559       case MVT::v4i32:
13560       case MVT::v2i64:
13561       case MVT::v4f32:
13562       case MVT::v2f64:
13563         return std::make_pair(0U, X86::VR128RegisterClass);
13564       }
13565       break;
13566     }
13567   }
13568
13569   // Use the default implementation in TargetLowering to convert the register
13570   // constraint into a member of a register class.
13571   std::pair<unsigned, const TargetRegisterClass*> Res;
13572   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13573
13574   // Not found as a standard register?
13575   if (Res.second == 0) {
13576     // Map st(0) -> st(7) -> ST0
13577     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13578         tolower(Constraint[1]) == 's' &&
13579         tolower(Constraint[2]) == 't' &&
13580         Constraint[3] == '(' &&
13581         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13582         Constraint[5] == ')' &&
13583         Constraint[6] == '}') {
13584
13585       Res.first = X86::ST0+Constraint[4]-'0';
13586       Res.second = X86::RFP80RegisterClass;
13587       return Res;
13588     }
13589
13590     // GCC allows "st(0)" to be called just plain "st".
13591     if (StringRef("{st}").equals_lower(Constraint)) {
13592       Res.first = X86::ST0;
13593       Res.second = X86::RFP80RegisterClass;
13594       return Res;
13595     }
13596
13597     // flags -> EFLAGS
13598     if (StringRef("{flags}").equals_lower(Constraint)) {
13599       Res.first = X86::EFLAGS;
13600       Res.second = X86::CCRRegisterClass;
13601       return Res;
13602     }
13603
13604     // 'A' means EAX + EDX.
13605     if (Constraint == "A") {
13606       Res.first = X86::EAX;
13607       Res.second = X86::GR32_ADRegisterClass;
13608       return Res;
13609     }
13610     return Res;
13611   }
13612
13613   // Otherwise, check to see if this is a register class of the wrong value
13614   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13615   // turn into {ax},{dx}.
13616   if (Res.second->hasType(VT))
13617     return Res;   // Correct type already, nothing to do.
13618
13619   // All of the single-register GCC register classes map their values onto
13620   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13621   // really want an 8-bit or 32-bit register, map to the appropriate register
13622   // class and return the appropriate register.
13623   if (Res.second == X86::GR16RegisterClass) {
13624     if (VT == MVT::i8) {
13625       unsigned DestReg = 0;
13626       switch (Res.first) {
13627       default: break;
13628       case X86::AX: DestReg = X86::AL; break;
13629       case X86::DX: DestReg = X86::DL; break;
13630       case X86::CX: DestReg = X86::CL; break;
13631       case X86::BX: DestReg = X86::BL; break;
13632       }
13633       if (DestReg) {
13634         Res.first = DestReg;
13635         Res.second = X86::GR8RegisterClass;
13636       }
13637     } else if (VT == MVT::i32) {
13638       unsigned DestReg = 0;
13639       switch (Res.first) {
13640       default: break;
13641       case X86::AX: DestReg = X86::EAX; break;
13642       case X86::DX: DestReg = X86::EDX; break;
13643       case X86::CX: DestReg = X86::ECX; break;
13644       case X86::BX: DestReg = X86::EBX; break;
13645       case X86::SI: DestReg = X86::ESI; break;
13646       case X86::DI: DestReg = X86::EDI; break;
13647       case X86::BP: DestReg = X86::EBP; break;
13648       case X86::SP: DestReg = X86::ESP; break;
13649       }
13650       if (DestReg) {
13651         Res.first = DestReg;
13652         Res.second = X86::GR32RegisterClass;
13653       }
13654     } else if (VT == MVT::i64) {
13655       unsigned DestReg = 0;
13656       switch (Res.first) {
13657       default: break;
13658       case X86::AX: DestReg = X86::RAX; break;
13659       case X86::DX: DestReg = X86::RDX; break;
13660       case X86::CX: DestReg = X86::RCX; break;
13661       case X86::BX: DestReg = X86::RBX; break;
13662       case X86::SI: DestReg = X86::RSI; break;
13663       case X86::DI: DestReg = X86::RDI; break;
13664       case X86::BP: DestReg = X86::RBP; break;
13665       case X86::SP: DestReg = X86::RSP; break;
13666       }
13667       if (DestReg) {
13668         Res.first = DestReg;
13669         Res.second = X86::GR64RegisterClass;
13670       }
13671     }
13672   } else if (Res.second == X86::FR32RegisterClass ||
13673              Res.second == X86::FR64RegisterClass ||
13674              Res.second == X86::VR128RegisterClass) {
13675     // Handle references to XMM physical registers that got mapped into the
13676     // wrong class.  This can happen with constraints like {xmm0} where the
13677     // target independent register mapper will just pick the first match it can
13678     // find, ignoring the required type.
13679     if (VT == MVT::f32)
13680       Res.second = X86::FR32RegisterClass;
13681     else if (VT == MVT::f64)
13682       Res.second = X86::FR64RegisterClass;
13683     else if (X86::VR128RegisterClass->hasType(VT))
13684       Res.second = X86::VR128RegisterClass;
13685   }
13686
13687   return Res;
13688 }