2c62b93f7bde53515310a65f23535477e3e52581
[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();
172   X86ScalarSSEf32 = Subtarget->hasXMM();
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   // We may not have a libcall for MEMBARRIER so we should lower this.
453   setOperationAction(ISD::MEMBARRIER    , 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()) {
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()) {
926     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
927     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
928     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
929
930     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
931     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
932     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
933
934     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
935     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
936   }
937
938   if (Subtarget->hasSSE42())
939     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
940
941   if (!UseSoftFloat && Subtarget->hasAVX()) {
942     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
943     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
944     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
945     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
946     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
947     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
948
949     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
950     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
951     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
952
953     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
954     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
955     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
956     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
957     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
958     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
959
960     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
961     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
962     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
963     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
964     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
965     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
966
967     // Custom lower several nodes for 256-bit types.
968     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
969                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
970       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
971       EVT VT = SVT;
972
973       // Extract subvector is special because the value type
974       // (result) is 128-bit but the source is 256-bit wide.
975       if (VT.is128BitVector())
976         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
977
978       // Do not attempt to custom lower other non-256-bit vectors
979       if (!VT.is256BitVector())
980         continue;
981
982       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
984       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
985       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
986       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
987       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
988     }
989
990     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
991     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
992       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
993       EVT VT = SVT;
994
995       // Do not attempt to promote non-256-bit vectors
996       if (!VT.is256BitVector())
997         continue;
998
999       setOperationAction(ISD::AND,    SVT, Promote);
1000       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1001       setOperationAction(ISD::OR,     SVT, Promote);
1002       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1003       setOperationAction(ISD::XOR,    SVT, Promote);
1004       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1005       setOperationAction(ISD::LOAD,   SVT, Promote);
1006       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1007       setOperationAction(ISD::SELECT, SVT, Promote);
1008       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1009     }
1010   }
1011
1012   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1013   // of this type with custom code.
1014   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1015          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1016     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1017   }
1018
1019   // We want to custom lower some of our intrinsics.
1020   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1021
1022
1023   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1024   // handle type legalization for these operations here.
1025   //
1026   // FIXME: We really should do custom legalization for addition and
1027   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1028   // than generic legalization for 64-bit multiplication-with-overflow, though.
1029   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1030     // Add/Sub/Mul with overflow operations are custom lowered.
1031     MVT VT = IntVTs[i];
1032     setOperationAction(ISD::SADDO, VT, Custom);
1033     setOperationAction(ISD::UADDO, VT, Custom);
1034     setOperationAction(ISD::SSUBO, VT, Custom);
1035     setOperationAction(ISD::USUBO, VT, Custom);
1036     setOperationAction(ISD::SMULO, VT, Custom);
1037     setOperationAction(ISD::UMULO, VT, Custom);
1038   }
1039
1040   // There are no 8-bit 3-address imul/mul instructions
1041   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1042   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1043
1044   if (!Subtarget->is64Bit()) {
1045     // These libcalls are not available in 32-bit.
1046     setLibcallName(RTLIB::SHL_I128, 0);
1047     setLibcallName(RTLIB::SRL_I128, 0);
1048     setLibcallName(RTLIB::SRA_I128, 0);
1049   }
1050
1051   // We have target-specific dag combine patterns for the following nodes:
1052   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1053   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1054   setTargetDAGCombine(ISD::BUILD_VECTOR);
1055   setTargetDAGCombine(ISD::SELECT);
1056   setTargetDAGCombine(ISD::SHL);
1057   setTargetDAGCombine(ISD::SRA);
1058   setTargetDAGCombine(ISD::SRL);
1059   setTargetDAGCombine(ISD::OR);
1060   setTargetDAGCombine(ISD::AND);
1061   setTargetDAGCombine(ISD::ADD);
1062   setTargetDAGCombine(ISD::SUB);
1063   setTargetDAGCombine(ISD::STORE);
1064   setTargetDAGCombine(ISD::ZERO_EXTEND);
1065   setTargetDAGCombine(ISD::SINT_TO_FP);
1066   if (Subtarget->is64Bit())
1067     setTargetDAGCombine(ISD::MUL);
1068
1069   computeRegisterProperties();
1070
1071   // On Darwin, -Os means optimize for size without hurting performance,
1072   // do not reduce the limit.
1073   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1074   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1075   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1076   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1077   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1078   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1079   setPrefLoopAlignment(16);
1080   benefitFromCodePlacementOpt = true;
1081
1082   setPrefFunctionAlignment(4);
1083 }
1084
1085
1086 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1087   return MVT::i8;
1088 }
1089
1090
1091 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1092 /// the desired ByVal argument alignment.
1093 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1094   if (MaxAlign == 16)
1095     return;
1096   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1097     if (VTy->getBitWidth() == 128)
1098       MaxAlign = 16;
1099   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1100     unsigned EltAlign = 0;
1101     getMaxByValAlign(ATy->getElementType(), EltAlign);
1102     if (EltAlign > MaxAlign)
1103       MaxAlign = EltAlign;
1104   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1105     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1106       unsigned EltAlign = 0;
1107       getMaxByValAlign(STy->getElementType(i), EltAlign);
1108       if (EltAlign > MaxAlign)
1109         MaxAlign = EltAlign;
1110       if (MaxAlign == 16)
1111         break;
1112     }
1113   }
1114   return;
1115 }
1116
1117 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1118 /// function arguments in the caller parameter area. For X86, aggregates
1119 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1120 /// are at 4-byte boundaries.
1121 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1122   if (Subtarget->is64Bit()) {
1123     // Max of 8 and alignment of type.
1124     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1125     if (TyAlign > 8)
1126       return TyAlign;
1127     return 8;
1128   }
1129
1130   unsigned Align = 4;
1131   if (Subtarget->hasXMM())
1132     getMaxByValAlign(Ty, Align);
1133   return Align;
1134 }
1135
1136 /// getOptimalMemOpType - Returns the target specific optimal type for load
1137 /// and store operations as a result of memset, memcpy, and memmove
1138 /// lowering. If DstAlign is zero that means it's safe to destination
1139 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1140 /// means there isn't a need to check it against alignment requirement,
1141 /// probably because the source does not need to be loaded. If
1142 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1143 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1144 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1145 /// constant so it does not need to be loaded.
1146 /// It returns EVT::Other if the type should be determined using generic
1147 /// target-independent logic.
1148 EVT
1149 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1150                                        unsigned DstAlign, unsigned SrcAlign,
1151                                        bool NonScalarIntSafe,
1152                                        bool MemcpyStrSrc,
1153                                        MachineFunction &MF) const {
1154   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1155   // linux.  This is because the stack realignment code can't handle certain
1156   // cases like PR2962.  This should be removed when PR2962 is fixed.
1157   const Function *F = MF.getFunction();
1158   if (NonScalarIntSafe &&
1159       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1160     if (Size >= 16 &&
1161         (Subtarget->isUnalignedMemAccessFast() ||
1162          ((DstAlign == 0 || DstAlign >= 16) &&
1163           (SrcAlign == 0 || SrcAlign >= 16))) &&
1164         Subtarget->getStackAlignment() >= 16) {
1165       if (Subtarget->hasSSE2())
1166         return MVT::v4i32;
1167       if (Subtarget->hasSSE1())
1168         return MVT::v4f32;
1169     } else if (!MemcpyStrSrc && Size >= 8 &&
1170                !Subtarget->is64Bit() &&
1171                Subtarget->getStackAlignment() >= 8 &&
1172                Subtarget->hasXMMInt()) {
1173       // Do not use f64 to lower memcpy if source is string constant. It's
1174       // better to use i32 to avoid the loads.
1175       return MVT::f64;
1176     }
1177   }
1178   if (Subtarget->is64Bit() && Size >= 8)
1179     return MVT::i64;
1180   return MVT::i32;
1181 }
1182
1183 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1184 /// current function.  The returned value is a member of the
1185 /// MachineJumpTableInfo::JTEntryKind enum.
1186 unsigned X86TargetLowering::getJumpTableEncoding() const {
1187   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1188   // symbol.
1189   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1190       Subtarget->isPICStyleGOT())
1191     return MachineJumpTableInfo::EK_Custom32;
1192
1193   // Otherwise, use the normal jump table encoding heuristics.
1194   return TargetLowering::getJumpTableEncoding();
1195 }
1196
1197 const MCExpr *
1198 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1199                                              const MachineBasicBlock *MBB,
1200                                              unsigned uid,MCContext &Ctx) const{
1201   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1202          Subtarget->isPICStyleGOT());
1203   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1204   // entries.
1205   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1206                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1207 }
1208
1209 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1210 /// jumptable.
1211 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1212                                                     SelectionDAG &DAG) const {
1213   if (!Subtarget->is64Bit())
1214     // This doesn't have DebugLoc associated with it, but is not really the
1215     // same as a Register.
1216     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1217   return Table;
1218 }
1219
1220 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1221 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1222 /// MCExpr.
1223 const MCExpr *X86TargetLowering::
1224 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1225                              MCContext &Ctx) const {
1226   // X86-64 uses RIP relative addressing based on the jump table label.
1227   if (Subtarget->isPICStyleRIPRel())
1228     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1229
1230   // Otherwise, the reference is relative to the PIC base.
1231   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1232 }
1233
1234 // FIXME: Why this routine is here? Move to RegInfo!
1235 std::pair<const TargetRegisterClass*, uint8_t>
1236 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1237   const TargetRegisterClass *RRC = 0;
1238   uint8_t Cost = 1;
1239   switch (VT.getSimpleVT().SimpleTy) {
1240   default:
1241     return TargetLowering::findRepresentativeClass(VT);
1242   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1243     RRC = (Subtarget->is64Bit()
1244            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1245     break;
1246   case MVT::x86mmx:
1247     RRC = X86::VR64RegisterClass;
1248     break;
1249   case MVT::f32: case MVT::f64:
1250   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1251   case MVT::v4f32: case MVT::v2f64:
1252   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1253   case MVT::v4f64:
1254     RRC = X86::VR128RegisterClass;
1255     break;
1256   }
1257   return std::make_pair(RRC, Cost);
1258 }
1259
1260 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1261                                                unsigned &Offset) const {
1262   if (!Subtarget->isTargetLinux())
1263     return false;
1264
1265   if (Subtarget->is64Bit()) {
1266     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1267     Offset = 0x28;
1268     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1269       AddressSpace = 256;
1270     else
1271       AddressSpace = 257;
1272   } else {
1273     // %gs:0x14 on i386
1274     Offset = 0x14;
1275     AddressSpace = 256;
1276   }
1277   return true;
1278 }
1279
1280
1281 //===----------------------------------------------------------------------===//
1282 //               Return Value Calling Convention Implementation
1283 //===----------------------------------------------------------------------===//
1284
1285 #include "X86GenCallingConv.inc"
1286
1287 bool
1288 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1289                                   MachineFunction &MF, bool isVarArg,
1290                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1291                         LLVMContext &Context) const {
1292   SmallVector<CCValAssign, 16> RVLocs;
1293   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1294                  RVLocs, Context);
1295   return CCInfo.CheckReturn(Outs, RetCC_X86);
1296 }
1297
1298 SDValue
1299 X86TargetLowering::LowerReturn(SDValue Chain,
1300                                CallingConv::ID CallConv, bool isVarArg,
1301                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1302                                const SmallVectorImpl<SDValue> &OutVals,
1303                                DebugLoc dl, SelectionDAG &DAG) const {
1304   MachineFunction &MF = DAG.getMachineFunction();
1305   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1306
1307   SmallVector<CCValAssign, 16> RVLocs;
1308   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1309                  RVLocs, *DAG.getContext());
1310   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1311
1312   // Add the regs to the liveout set for the function.
1313   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1314   for (unsigned i = 0; i != RVLocs.size(); ++i)
1315     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1316       MRI.addLiveOut(RVLocs[i].getLocReg());
1317
1318   SDValue Flag;
1319
1320   SmallVector<SDValue, 6> RetOps;
1321   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1322   // Operand #1 = Bytes To Pop
1323   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1324                    MVT::i16));
1325
1326   // Copy the result values into the output registers.
1327   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1328     CCValAssign &VA = RVLocs[i];
1329     assert(VA.isRegLoc() && "Can only return in registers!");
1330     SDValue ValToCopy = OutVals[i];
1331     EVT ValVT = ValToCopy.getValueType();
1332
1333     // If this is x86-64, and we disabled SSE, we can't return FP values,
1334     // or SSE or MMX vectors.
1335     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1336          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1337           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1338       report_fatal_error("SSE register return with SSE disabled");
1339     }
1340     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1341     // llvm-gcc has never done it right and no one has noticed, so this
1342     // should be OK for now.
1343     if (ValVT == MVT::f64 &&
1344         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1345       report_fatal_error("SSE2 register return with SSE2 disabled");
1346
1347     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1348     // the RET instruction and handled by the FP Stackifier.
1349     if (VA.getLocReg() == X86::ST0 ||
1350         VA.getLocReg() == X86::ST1) {
1351       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1352       // change the value to the FP stack register class.
1353       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1354         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1355       RetOps.push_back(ValToCopy);
1356       // Don't emit a copytoreg.
1357       continue;
1358     }
1359
1360     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1361     // which is returned in RAX / RDX.
1362     if (Subtarget->is64Bit()) {
1363       if (ValVT == MVT::x86mmx) {
1364         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1365           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1366           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1367                                   ValToCopy);
1368           // If we don't have SSE2 available, convert to v4f32 so the generated
1369           // register is legal.
1370           if (!Subtarget->hasSSE2())
1371             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1372         }
1373       }
1374     }
1375
1376     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1377     Flag = Chain.getValue(1);
1378   }
1379
1380   // The x86-64 ABI for returning structs by value requires that we copy
1381   // the sret argument into %rax for the return. We saved the argument into
1382   // a virtual register in the entry block, so now we copy the value out
1383   // and into %rax.
1384   if (Subtarget->is64Bit() &&
1385       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1386     MachineFunction &MF = DAG.getMachineFunction();
1387     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1388     unsigned Reg = FuncInfo->getSRetReturnReg();
1389     assert(Reg &&
1390            "SRetReturnReg should have been set in LowerFormalArguments().");
1391     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1392
1393     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1394     Flag = Chain.getValue(1);
1395
1396     // RAX now acts like a return value.
1397     MRI.addLiveOut(X86::RAX);
1398   }
1399
1400   RetOps[0] = Chain;  // Update chain.
1401
1402   // Add the flag if we have it.
1403   if (Flag.getNode())
1404     RetOps.push_back(Flag);
1405
1406   return DAG.getNode(X86ISD::RET_FLAG, dl,
1407                      MVT::Other, &RetOps[0], RetOps.size());
1408 }
1409
1410 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1411   if (N->getNumValues() != 1)
1412     return false;
1413   if (!N->hasNUsesOfValue(1, 0))
1414     return false;
1415
1416   SDNode *Copy = *N->use_begin();
1417   if (Copy->getOpcode() != ISD::CopyToReg &&
1418       Copy->getOpcode() != ISD::FP_EXTEND)
1419     return false;
1420
1421   bool HasRet = false;
1422   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1423        UI != UE; ++UI) {
1424     if (UI->getOpcode() != X86ISD::RET_FLAG)
1425       return false;
1426     HasRet = true;
1427   }
1428
1429   return HasRet;
1430 }
1431
1432 EVT
1433 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1434                                             ISD::NodeType ExtendKind) const {
1435   MVT ReturnMVT;
1436   // TODO: Is this also valid on 32-bit?
1437   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1438     ReturnMVT = MVT::i8;
1439   else
1440     ReturnMVT = MVT::i32;
1441
1442   EVT MinVT = getRegisterType(Context, ReturnMVT);
1443   return VT.bitsLT(MinVT) ? MinVT : VT;
1444 }
1445
1446 /// LowerCallResult - Lower the result values of a call into the
1447 /// appropriate copies out of appropriate physical registers.
1448 ///
1449 SDValue
1450 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1451                                    CallingConv::ID CallConv, bool isVarArg,
1452                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1453                                    DebugLoc dl, SelectionDAG &DAG,
1454                                    SmallVectorImpl<SDValue> &InVals) const {
1455
1456   // Assign locations to each value returned by this call.
1457   SmallVector<CCValAssign, 16> RVLocs;
1458   bool Is64Bit = Subtarget->is64Bit();
1459   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1460                  getTargetMachine(), RVLocs, *DAG.getContext());
1461   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1462
1463   // Copy all of the result registers out of their specified physreg.
1464   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1465     CCValAssign &VA = RVLocs[i];
1466     EVT CopyVT = VA.getValVT();
1467
1468     // If this is x86-64, and we disabled SSE, we can't return FP values
1469     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1470         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1471       report_fatal_error("SSE register return with SSE disabled");
1472     }
1473
1474     SDValue Val;
1475
1476     // If this is a call to a function that returns an fp value on the floating
1477     // point stack, we must guarantee the the value is popped from the stack, so
1478     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1479     // if the return value is not used. We use the FpPOP_RETVAL instruction
1480     // instead.
1481     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1482       // If we prefer to use the value in xmm registers, copy it out as f80 and
1483       // use a truncate to move it from fp stack reg to xmm reg.
1484       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1485       SDValue Ops[] = { Chain, InFlag };
1486       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1487                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1488       Val = Chain.getValue(0);
1489
1490       // Round the f80 to the right size, which also moves it to the appropriate
1491       // xmm register.
1492       if (CopyVT != VA.getValVT())
1493         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1494                           // This truncation won't change the value.
1495                           DAG.getIntPtrConstant(1));
1496     } else {
1497       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1498                                  CopyVT, InFlag).getValue(1);
1499       Val = Chain.getValue(0);
1500     }
1501     InFlag = Chain.getValue(2);
1502     InVals.push_back(Val);
1503   }
1504
1505   return Chain;
1506 }
1507
1508
1509 //===----------------------------------------------------------------------===//
1510 //                C & StdCall & Fast Calling Convention implementation
1511 //===----------------------------------------------------------------------===//
1512 //  StdCall calling convention seems to be standard for many Windows' API
1513 //  routines and around. It differs from C calling convention just a little:
1514 //  callee should clean up the stack, not caller. Symbols should be also
1515 //  decorated in some fancy way :) It doesn't support any vector arguments.
1516 //  For info on fast calling convention see Fast Calling Convention (tail call)
1517 //  implementation LowerX86_32FastCCCallTo.
1518
1519 /// CallIsStructReturn - Determines whether a call uses struct return
1520 /// semantics.
1521 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1522   if (Outs.empty())
1523     return false;
1524
1525   return Outs[0].Flags.isSRet();
1526 }
1527
1528 /// ArgsAreStructReturn - Determines whether a function uses struct
1529 /// return semantics.
1530 static bool
1531 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1532   if (Ins.empty())
1533     return false;
1534
1535   return Ins[0].Flags.isSRet();
1536 }
1537
1538 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1539 /// by "Src" to address "Dst" with size and alignment information specified by
1540 /// the specific parameter attribute. The copy will be passed as a byval
1541 /// function parameter.
1542 static SDValue
1543 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1544                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1545                           DebugLoc dl) {
1546   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1547
1548   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1549                        /*isVolatile*/false, /*AlwaysInline=*/true,
1550                        MachinePointerInfo(), MachinePointerInfo());
1551 }
1552
1553 /// IsTailCallConvention - Return true if the calling convention is one that
1554 /// supports tail call optimization.
1555 static bool IsTailCallConvention(CallingConv::ID CC) {
1556   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1557 }
1558
1559 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1560   if (!CI->isTailCall())
1561     return false;
1562
1563   CallSite CS(CI);
1564   CallingConv::ID CalleeCC = CS.getCallingConv();
1565   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1566     return false;
1567
1568   return true;
1569 }
1570
1571 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1572 /// a tailcall target by changing its ABI.
1573 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1574   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1575 }
1576
1577 SDValue
1578 X86TargetLowering::LowerMemArgument(SDValue Chain,
1579                                     CallingConv::ID CallConv,
1580                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1581                                     DebugLoc dl, SelectionDAG &DAG,
1582                                     const CCValAssign &VA,
1583                                     MachineFrameInfo *MFI,
1584                                     unsigned i) const {
1585   // Create the nodes corresponding to a load from this parameter slot.
1586   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1587   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1588   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1589   EVT ValVT;
1590
1591   // If value is passed by pointer we have address passed instead of the value
1592   // itself.
1593   if (VA.getLocInfo() == CCValAssign::Indirect)
1594     ValVT = VA.getLocVT();
1595   else
1596     ValVT = VA.getValVT();
1597
1598   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1599   // changed with more analysis.
1600   // In case of tail call optimization mark all arguments mutable. Since they
1601   // could be overwritten by lowering of arguments in case of a tail call.
1602   if (Flags.isByVal()) {
1603     unsigned Bytes = Flags.getByValSize();
1604     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1605     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1606     return DAG.getFrameIndex(FI, getPointerTy());
1607   } else {
1608     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1609                                     VA.getLocMemOffset(), isImmutable);
1610     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1611     return DAG.getLoad(ValVT, dl, Chain, FIN,
1612                        MachinePointerInfo::getFixedStack(FI),
1613                        false, false, 0);
1614   }
1615 }
1616
1617 SDValue
1618 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1619                                         CallingConv::ID CallConv,
1620                                         bool isVarArg,
1621                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1622                                         DebugLoc dl,
1623                                         SelectionDAG &DAG,
1624                                         SmallVectorImpl<SDValue> &InVals)
1625                                           const {
1626   MachineFunction &MF = DAG.getMachineFunction();
1627   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1628
1629   const Function* Fn = MF.getFunction();
1630   if (Fn->hasExternalLinkage() &&
1631       Subtarget->isTargetCygMing() &&
1632       Fn->getName() == "main")
1633     FuncInfo->setForceFramePointer(true);
1634
1635   MachineFrameInfo *MFI = MF.getFrameInfo();
1636   bool Is64Bit = Subtarget->is64Bit();
1637   bool IsWin64 = Subtarget->isTargetWin64();
1638
1639   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1640          "Var args not supported with calling convention fastcc or ghc");
1641
1642   // Assign locations to all of the incoming arguments.
1643   SmallVector<CCValAssign, 16> ArgLocs;
1644   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1645                  ArgLocs, *DAG.getContext());
1646
1647   // Allocate shadow area for Win64
1648   if (IsWin64) {
1649     CCInfo.AllocateStack(32, 8);
1650   }
1651
1652   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1653
1654   unsigned LastVal = ~0U;
1655   SDValue ArgValue;
1656   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1657     CCValAssign &VA = ArgLocs[i];
1658     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1659     // places.
1660     assert(VA.getValNo() != LastVal &&
1661            "Don't support value assigned to multiple locs yet");
1662     LastVal = VA.getValNo();
1663
1664     if (VA.isRegLoc()) {
1665       EVT RegVT = VA.getLocVT();
1666       TargetRegisterClass *RC = NULL;
1667       if (RegVT == MVT::i32)
1668         RC = X86::GR32RegisterClass;
1669       else if (Is64Bit && RegVT == MVT::i64)
1670         RC = X86::GR64RegisterClass;
1671       else if (RegVT == MVT::f32)
1672         RC = X86::FR32RegisterClass;
1673       else if (RegVT == MVT::f64)
1674         RC = X86::FR64RegisterClass;
1675       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1676         RC = X86::VR256RegisterClass;
1677       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1678         RC = X86::VR128RegisterClass;
1679       else if (RegVT == MVT::x86mmx)
1680         RC = X86::VR64RegisterClass;
1681       else
1682         llvm_unreachable("Unknown argument type!");
1683
1684       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1685       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1686
1687       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1688       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1689       // right size.
1690       if (VA.getLocInfo() == CCValAssign::SExt)
1691         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1692                                DAG.getValueType(VA.getValVT()));
1693       else if (VA.getLocInfo() == CCValAssign::ZExt)
1694         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1695                                DAG.getValueType(VA.getValVT()));
1696       else if (VA.getLocInfo() == CCValAssign::BCvt)
1697         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1698
1699       if (VA.isExtInLoc()) {
1700         // Handle MMX values passed in XMM regs.
1701         if (RegVT.isVector()) {
1702           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1703                                  ArgValue);
1704         } else
1705           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1706       }
1707     } else {
1708       assert(VA.isMemLoc());
1709       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1710     }
1711
1712     // If value is passed via pointer - do a load.
1713     if (VA.getLocInfo() == CCValAssign::Indirect)
1714       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1715                              MachinePointerInfo(), false, false, 0);
1716
1717     InVals.push_back(ArgValue);
1718   }
1719
1720   // The x86-64 ABI for returning structs by value requires that we copy
1721   // the sret argument into %rax for the return. Save the argument into
1722   // a virtual register so that we can access it from the return points.
1723   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1724     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1725     unsigned Reg = FuncInfo->getSRetReturnReg();
1726     if (!Reg) {
1727       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1728       FuncInfo->setSRetReturnReg(Reg);
1729     }
1730     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1731     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1732   }
1733
1734   unsigned StackSize = CCInfo.getNextStackOffset();
1735   // Align stack specially for tail calls.
1736   if (FuncIsMadeTailCallSafe(CallConv))
1737     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1738
1739   // If the function takes variable number of arguments, make a frame index for
1740   // the start of the first vararg value... for expansion of llvm.va_start.
1741   if (isVarArg) {
1742     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1743                     CallConv != CallingConv::X86_ThisCall)) {
1744       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1745     }
1746     if (Is64Bit) {
1747       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1748
1749       // FIXME: We should really autogenerate these arrays
1750       static const unsigned GPR64ArgRegsWin64[] = {
1751         X86::RCX, X86::RDX, X86::R8,  X86::R9
1752       };
1753       static const unsigned GPR64ArgRegs64Bit[] = {
1754         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1755       };
1756       static const unsigned XMMArgRegs64Bit[] = {
1757         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1758         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1759       };
1760       const unsigned *GPR64ArgRegs;
1761       unsigned NumXMMRegs = 0;
1762
1763       if (IsWin64) {
1764         // The XMM registers which might contain var arg parameters are shadowed
1765         // in their paired GPR.  So we only need to save the GPR to their home
1766         // slots.
1767         TotalNumIntRegs = 4;
1768         GPR64ArgRegs = GPR64ArgRegsWin64;
1769       } else {
1770         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1771         GPR64ArgRegs = GPR64ArgRegs64Bit;
1772
1773         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1774       }
1775       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1776                                                        TotalNumIntRegs);
1777
1778       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1779       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1780              "SSE register cannot be used when SSE is disabled!");
1781       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1782              "SSE register cannot be used when SSE is disabled!");
1783       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1784         // Kernel mode asks for SSE to be disabled, so don't push them
1785         // on the stack.
1786         TotalNumXMMRegs = 0;
1787
1788       if (IsWin64) {
1789         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1790         // Get to the caller-allocated home save location.  Add 8 to account
1791         // for the return address.
1792         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1793         FuncInfo->setRegSaveFrameIndex(
1794           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1795         // Fixup to set vararg frame on shadow area (4 x i64).
1796         if (NumIntRegs < 4)
1797           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1798       } else {
1799         // For X86-64, if there are vararg parameters that are passed via
1800         // registers, then we must store them to their spots on the stack so they
1801         // may be loaded by deferencing the result of va_next.
1802         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1803         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1804         FuncInfo->setRegSaveFrameIndex(
1805           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1806                                false));
1807       }
1808
1809       // Store the integer parameter registers.
1810       SmallVector<SDValue, 8> MemOps;
1811       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1812                                         getPointerTy());
1813       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1814       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1815         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1816                                   DAG.getIntPtrConstant(Offset));
1817         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1818                                      X86::GR64RegisterClass);
1819         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1820         SDValue Store =
1821           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1822                        MachinePointerInfo::getFixedStack(
1823                          FuncInfo->getRegSaveFrameIndex(), Offset),
1824                        false, false, 0);
1825         MemOps.push_back(Store);
1826         Offset += 8;
1827       }
1828
1829       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1830         // Now store the XMM (fp + vector) parameter registers.
1831         SmallVector<SDValue, 11> SaveXMMOps;
1832         SaveXMMOps.push_back(Chain);
1833
1834         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1835         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1836         SaveXMMOps.push_back(ALVal);
1837
1838         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1839                                FuncInfo->getRegSaveFrameIndex()));
1840         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1841                                FuncInfo->getVarArgsFPOffset()));
1842
1843         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1844           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1845                                        X86::VR128RegisterClass);
1846           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1847           SaveXMMOps.push_back(Val);
1848         }
1849         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1850                                      MVT::Other,
1851                                      &SaveXMMOps[0], SaveXMMOps.size()));
1852       }
1853
1854       if (!MemOps.empty())
1855         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1856                             &MemOps[0], MemOps.size());
1857     }
1858   }
1859
1860   // Some CCs need callee pop.
1861   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1862     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1863   } else {
1864     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1865     // If this is an sret function, the return should pop the hidden pointer.
1866     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1867       FuncInfo->setBytesToPopOnReturn(4);
1868   }
1869
1870   if (!Is64Bit) {
1871     // RegSaveFrameIndex is X86-64 only.
1872     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1873     if (CallConv == CallingConv::X86_FastCall ||
1874         CallConv == CallingConv::X86_ThisCall)
1875       // fastcc functions can't have varargs.
1876       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1877   }
1878
1879   return Chain;
1880 }
1881
1882 SDValue
1883 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1884                                     SDValue StackPtr, SDValue Arg,
1885                                     DebugLoc dl, SelectionDAG &DAG,
1886                                     const CCValAssign &VA,
1887                                     ISD::ArgFlagsTy Flags) const {
1888   unsigned LocMemOffset = VA.getLocMemOffset();
1889   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1890   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1891   if (Flags.isByVal())
1892     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1893
1894   return DAG.getStore(Chain, dl, Arg, PtrOff,
1895                       MachinePointerInfo::getStack(LocMemOffset),
1896                       false, false, 0);
1897 }
1898
1899 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1900 /// optimization is performed and it is required.
1901 SDValue
1902 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1903                                            SDValue &OutRetAddr, SDValue Chain,
1904                                            bool IsTailCall, bool Is64Bit,
1905                                            int FPDiff, DebugLoc dl) const {
1906   // Adjust the Return address stack slot.
1907   EVT VT = getPointerTy();
1908   OutRetAddr = getReturnAddressFrameIndex(DAG);
1909
1910   // Load the "old" Return address.
1911   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1912                            false, false, 0);
1913   return SDValue(OutRetAddr.getNode(), 1);
1914 }
1915
1916 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1917 /// optimization is performed and it is required (FPDiff!=0).
1918 static SDValue
1919 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1920                          SDValue Chain, SDValue RetAddrFrIdx,
1921                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1922   // Store the return address to the appropriate stack slot.
1923   if (!FPDiff) return Chain;
1924   // Calculate the new stack slot for the return address.
1925   int SlotSize = Is64Bit ? 8 : 4;
1926   int NewReturnAddrFI =
1927     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1928   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1929   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1930   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1931                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1932                        false, false, 0);
1933   return Chain;
1934 }
1935
1936 SDValue
1937 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1938                              CallingConv::ID CallConv, bool isVarArg,
1939                              bool &isTailCall,
1940                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1941                              const SmallVectorImpl<SDValue> &OutVals,
1942                              const SmallVectorImpl<ISD::InputArg> &Ins,
1943                              DebugLoc dl, SelectionDAG &DAG,
1944                              SmallVectorImpl<SDValue> &InVals) const {
1945   MachineFunction &MF = DAG.getMachineFunction();
1946   bool Is64Bit        = Subtarget->is64Bit();
1947   bool IsWin64        = Subtarget->isTargetWin64();
1948   bool IsStructRet    = CallIsStructReturn(Outs);
1949   bool IsSibcall      = false;
1950
1951   if (isTailCall) {
1952     // Check if it's really possible to do a tail call.
1953     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1954                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1955                                                    Outs, OutVals, Ins, DAG);
1956
1957     // Sibcalls are automatically detected tailcalls which do not require
1958     // ABI changes.
1959     if (!GuaranteedTailCallOpt && isTailCall)
1960       IsSibcall = true;
1961
1962     if (isTailCall)
1963       ++NumTailCalls;
1964   }
1965
1966   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1967          "Var args not supported with calling convention fastcc or ghc");
1968
1969   // Analyze operands of the call, assigning locations to each operand.
1970   SmallVector<CCValAssign, 16> ArgLocs;
1971   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1972                  ArgLocs, *DAG.getContext());
1973
1974   // Allocate shadow area for Win64
1975   if (IsWin64) {
1976     CCInfo.AllocateStack(32, 8);
1977   }
1978
1979   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1980
1981   // Get a count of how many bytes are to be pushed on the stack.
1982   unsigned NumBytes = CCInfo.getNextStackOffset();
1983   if (IsSibcall)
1984     // This is a sibcall. The memory operands are available in caller's
1985     // own caller's stack.
1986     NumBytes = 0;
1987   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1988     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1989
1990   int FPDiff = 0;
1991   if (isTailCall && !IsSibcall) {
1992     // Lower arguments at fp - stackoffset + fpdiff.
1993     unsigned NumBytesCallerPushed =
1994       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1995     FPDiff = NumBytesCallerPushed - NumBytes;
1996
1997     // Set the delta of movement of the returnaddr stackslot.
1998     // But only set if delta is greater than previous delta.
1999     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2000       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2001   }
2002
2003   if (!IsSibcall)
2004     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2005
2006   SDValue RetAddrFrIdx;
2007   // Load return address for tail calls.
2008   if (isTailCall && FPDiff)
2009     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2010                                     Is64Bit, FPDiff, dl);
2011
2012   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2013   SmallVector<SDValue, 8> MemOpChains;
2014   SDValue StackPtr;
2015
2016   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2017   // of tail call optimization arguments are handle later.
2018   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2019     CCValAssign &VA = ArgLocs[i];
2020     EVT RegVT = VA.getLocVT();
2021     SDValue Arg = OutVals[i];
2022     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2023     bool isByVal = Flags.isByVal();
2024
2025     // Promote the value if needed.
2026     switch (VA.getLocInfo()) {
2027     default: llvm_unreachable("Unknown loc info!");
2028     case CCValAssign::Full: break;
2029     case CCValAssign::SExt:
2030       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2031       break;
2032     case CCValAssign::ZExt:
2033       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2034       break;
2035     case CCValAssign::AExt:
2036       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2037         // Special case: passing MMX values in XMM registers.
2038         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2039         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2040         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2041       } else
2042         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2043       break;
2044     case CCValAssign::BCvt:
2045       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2046       break;
2047     case CCValAssign::Indirect: {
2048       // Store the argument.
2049       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2050       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2051       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2052                            MachinePointerInfo::getFixedStack(FI),
2053                            false, false, 0);
2054       Arg = SpillSlot;
2055       break;
2056     }
2057     }
2058
2059     if (VA.isRegLoc()) {
2060       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2061       if (isVarArg && IsWin64) {
2062         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2063         // shadow reg if callee is a varargs function.
2064         unsigned ShadowReg = 0;
2065         switch (VA.getLocReg()) {
2066         case X86::XMM0: ShadowReg = X86::RCX; break;
2067         case X86::XMM1: ShadowReg = X86::RDX; break;
2068         case X86::XMM2: ShadowReg = X86::R8; break;
2069         case X86::XMM3: ShadowReg = X86::R9; break;
2070         }
2071         if (ShadowReg)
2072           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2073       }
2074     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2075       assert(VA.isMemLoc());
2076       if (StackPtr.getNode() == 0)
2077         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2078       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2079                                              dl, DAG, VA, Flags));
2080     }
2081   }
2082
2083   if (!MemOpChains.empty())
2084     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2085                         &MemOpChains[0], MemOpChains.size());
2086
2087   // Build a sequence of copy-to-reg nodes chained together with token chain
2088   // and flag operands which copy the outgoing args into registers.
2089   SDValue InFlag;
2090   // Tail call byval lowering might overwrite argument registers so in case of
2091   // tail call optimization the copies to registers are lowered later.
2092   if (!isTailCall)
2093     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2094       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2095                                RegsToPass[i].second, InFlag);
2096       InFlag = Chain.getValue(1);
2097     }
2098
2099   if (Subtarget->isPICStyleGOT()) {
2100     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2101     // GOT pointer.
2102     if (!isTailCall) {
2103       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2104                                DAG.getNode(X86ISD::GlobalBaseReg,
2105                                            DebugLoc(), getPointerTy()),
2106                                InFlag);
2107       InFlag = Chain.getValue(1);
2108     } else {
2109       // If we are tail calling and generating PIC/GOT style code load the
2110       // address of the callee into ECX. The value in ecx is used as target of
2111       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2112       // for tail calls on PIC/GOT architectures. Normally we would just put the
2113       // address of GOT into ebx and then call target@PLT. But for tail calls
2114       // ebx would be restored (since ebx is callee saved) before jumping to the
2115       // target@PLT.
2116
2117       // Note: The actual moving to ECX is done further down.
2118       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2119       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2120           !G->getGlobal()->hasProtectedVisibility())
2121         Callee = LowerGlobalAddress(Callee, DAG);
2122       else if (isa<ExternalSymbolSDNode>(Callee))
2123         Callee = LowerExternalSymbol(Callee, DAG);
2124     }
2125   }
2126
2127   if (Is64Bit && isVarArg && !IsWin64) {
2128     // From AMD64 ABI document:
2129     // For calls that may call functions that use varargs or stdargs
2130     // (prototype-less calls or calls to functions containing ellipsis (...) in
2131     // the declaration) %al is used as hidden argument to specify the number
2132     // of SSE registers used. The contents of %al do not need to match exactly
2133     // the number of registers, but must be an ubound on the number of SSE
2134     // registers used and is in the range 0 - 8 inclusive.
2135
2136     // Count the number of XMM registers allocated.
2137     static const unsigned XMMArgRegs[] = {
2138       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2139       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2140     };
2141     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2142     assert((Subtarget->hasXMM() || !NumXMMRegs)
2143            && "SSE registers cannot be used when SSE is disabled");
2144
2145     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2146                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2147     InFlag = Chain.getValue(1);
2148   }
2149
2150
2151   // For tail calls lower the arguments to the 'real' stack slot.
2152   if (isTailCall) {
2153     // Force all the incoming stack arguments to be loaded from the stack
2154     // before any new outgoing arguments are stored to the stack, because the
2155     // outgoing stack slots may alias the incoming argument stack slots, and
2156     // the alias isn't otherwise explicit. This is slightly more conservative
2157     // than necessary, because it means that each store effectively depends
2158     // on every argument instead of just those arguments it would clobber.
2159     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2160
2161     SmallVector<SDValue, 8> MemOpChains2;
2162     SDValue FIN;
2163     int FI = 0;
2164     // Do not flag preceding copytoreg stuff together with the following stuff.
2165     InFlag = SDValue();
2166     if (GuaranteedTailCallOpt) {
2167       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2168         CCValAssign &VA = ArgLocs[i];
2169         if (VA.isRegLoc())
2170           continue;
2171         assert(VA.isMemLoc());
2172         SDValue Arg = OutVals[i];
2173         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2174         // Create frame index.
2175         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2176         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2177         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2178         FIN = DAG.getFrameIndex(FI, getPointerTy());
2179
2180         if (Flags.isByVal()) {
2181           // Copy relative to framepointer.
2182           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2183           if (StackPtr.getNode() == 0)
2184             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2185                                           getPointerTy());
2186           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2187
2188           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2189                                                            ArgChain,
2190                                                            Flags, DAG, dl));
2191         } else {
2192           // Store relative to framepointer.
2193           MemOpChains2.push_back(
2194             DAG.getStore(ArgChain, dl, Arg, FIN,
2195                          MachinePointerInfo::getFixedStack(FI),
2196                          false, false, 0));
2197         }
2198       }
2199     }
2200
2201     if (!MemOpChains2.empty())
2202       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2203                           &MemOpChains2[0], MemOpChains2.size());
2204
2205     // Copy arguments to their registers.
2206     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2207       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2208                                RegsToPass[i].second, InFlag);
2209       InFlag = Chain.getValue(1);
2210     }
2211     InFlag =SDValue();
2212
2213     // Store the return address to the appropriate stack slot.
2214     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2215                                      FPDiff, dl);
2216   }
2217
2218   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2219     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2220     // In the 64-bit large code model, we have to make all calls
2221     // through a register, since the call instruction's 32-bit
2222     // pc-relative offset may not be large enough to hold the whole
2223     // address.
2224   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2225     // If the callee is a GlobalAddress node (quite common, every direct call
2226     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2227     // it.
2228
2229     // We should use extra load for direct calls to dllimported functions in
2230     // non-JIT mode.
2231     const GlobalValue *GV = G->getGlobal();
2232     if (!GV->hasDLLImportLinkage()) {
2233       unsigned char OpFlags = 0;
2234       bool ExtraLoad = false;
2235       unsigned WrapperKind = ISD::DELETED_NODE;
2236
2237       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2238       // external symbols most go through the PLT in PIC mode.  If the symbol
2239       // has hidden or protected visibility, or if it is static or local, then
2240       // we don't need to use the PLT - we can directly call it.
2241       if (Subtarget->isTargetELF() &&
2242           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2243           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2244         OpFlags = X86II::MO_PLT;
2245       } else if (Subtarget->isPICStyleStubAny() &&
2246                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2247                  (!Subtarget->getTargetTriple().isMacOSX() ||
2248                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2249         // PC-relative references to external symbols should go through $stub,
2250         // unless we're building with the leopard linker or later, which
2251         // automatically synthesizes these stubs.
2252         OpFlags = X86II::MO_DARWIN_STUB;
2253       } else if (Subtarget->isPICStyleRIPRel() &&
2254                  isa<Function>(GV) &&
2255                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2256         // If the function is marked as non-lazy, generate an indirect call
2257         // which loads from the GOT directly. This avoids runtime overhead
2258         // at the cost of eager binding (and one extra byte of encoding).
2259         OpFlags = X86II::MO_GOTPCREL;
2260         WrapperKind = X86ISD::WrapperRIP;
2261         ExtraLoad = true;
2262       }
2263
2264       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2265                                           G->getOffset(), OpFlags);
2266
2267       // Add a wrapper if needed.
2268       if (WrapperKind != ISD::DELETED_NODE)
2269         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2270       // Add extra indirection if needed.
2271       if (ExtraLoad)
2272         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2273                              MachinePointerInfo::getGOT(),
2274                              false, false, 0);
2275     }
2276   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2277     unsigned char OpFlags = 0;
2278
2279     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2280     // external symbols should go through the PLT.
2281     if (Subtarget->isTargetELF() &&
2282         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2283       OpFlags = X86II::MO_PLT;
2284     } else if (Subtarget->isPICStyleStubAny() &&
2285                (!Subtarget->getTargetTriple().isMacOSX() ||
2286                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2287       // PC-relative references to external symbols should go through $stub,
2288       // unless we're building with the leopard linker or later, which
2289       // automatically synthesizes these stubs.
2290       OpFlags = X86II::MO_DARWIN_STUB;
2291     }
2292
2293     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2294                                          OpFlags);
2295   }
2296
2297   // Returns a chain & a flag for retval copy to use.
2298   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2299   SmallVector<SDValue, 8> Ops;
2300
2301   if (!IsSibcall && isTailCall) {
2302     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2303                            DAG.getIntPtrConstant(0, true), InFlag);
2304     InFlag = Chain.getValue(1);
2305   }
2306
2307   Ops.push_back(Chain);
2308   Ops.push_back(Callee);
2309
2310   if (isTailCall)
2311     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2312
2313   // Add argument registers to the end of the list so that they are known live
2314   // into the call.
2315   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2316     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2317                                   RegsToPass[i].second.getValueType()));
2318
2319   // Add an implicit use GOT pointer in EBX.
2320   if (!isTailCall && Subtarget->isPICStyleGOT())
2321     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2322
2323   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2324   if (Is64Bit && isVarArg && !IsWin64)
2325     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2326
2327   if (InFlag.getNode())
2328     Ops.push_back(InFlag);
2329
2330   if (isTailCall) {
2331     // We used to do:
2332     //// If this is the first return lowered for this function, add the regs
2333     //// to the liveout set for the function.
2334     // This isn't right, although it's probably harmless on x86; liveouts
2335     // should be computed from returns not tail calls.  Consider a void
2336     // function making a tail call to a function returning int.
2337     return DAG.getNode(X86ISD::TC_RETURN, dl,
2338                        NodeTys, &Ops[0], Ops.size());
2339   }
2340
2341   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2342   InFlag = Chain.getValue(1);
2343
2344   // Create the CALLSEQ_END node.
2345   unsigned NumBytesForCalleeToPush;
2346   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2347     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2348   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2349     // If this is a call to a struct-return function, the callee
2350     // pops the hidden struct pointer, so we have to push it back.
2351     // This is common for Darwin/X86, Linux & Mingw32 targets.
2352     NumBytesForCalleeToPush = 4;
2353   else
2354     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2355
2356   // Returns a flag for retval copy to use.
2357   if (!IsSibcall) {
2358     Chain = DAG.getCALLSEQ_END(Chain,
2359                                DAG.getIntPtrConstant(NumBytes, true),
2360                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2361                                                      true),
2362                                InFlag);
2363     InFlag = Chain.getValue(1);
2364   }
2365
2366   // Handle result values, copying them out of physregs into vregs that we
2367   // return.
2368   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2369                          Ins, dl, DAG, InVals);
2370 }
2371
2372
2373 //===----------------------------------------------------------------------===//
2374 //                Fast Calling Convention (tail call) implementation
2375 //===----------------------------------------------------------------------===//
2376
2377 //  Like std call, callee cleans arguments, convention except that ECX is
2378 //  reserved for storing the tail called function address. Only 2 registers are
2379 //  free for argument passing (inreg). Tail call optimization is performed
2380 //  provided:
2381 //                * tailcallopt is enabled
2382 //                * caller/callee are fastcc
2383 //  On X86_64 architecture with GOT-style position independent code only local
2384 //  (within module) calls are supported at the moment.
2385 //  To keep the stack aligned according to platform abi the function
2386 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2387 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2388 //  If a tail called function callee has more arguments than the caller the
2389 //  caller needs to make sure that there is room to move the RETADDR to. This is
2390 //  achieved by reserving an area the size of the argument delta right after the
2391 //  original REtADDR, but before the saved framepointer or the spilled registers
2392 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2393 //  stack layout:
2394 //    arg1
2395 //    arg2
2396 //    RETADDR
2397 //    [ new RETADDR
2398 //      move area ]
2399 //    (possible EBP)
2400 //    ESI
2401 //    EDI
2402 //    local1 ..
2403
2404 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2405 /// for a 16 byte align requirement.
2406 unsigned
2407 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2408                                                SelectionDAG& DAG) const {
2409   MachineFunction &MF = DAG.getMachineFunction();
2410   const TargetMachine &TM = MF.getTarget();
2411   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2412   unsigned StackAlignment = TFI.getStackAlignment();
2413   uint64_t AlignMask = StackAlignment - 1;
2414   int64_t Offset = StackSize;
2415   uint64_t SlotSize = TD->getPointerSize();
2416   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2417     // Number smaller than 12 so just add the difference.
2418     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2419   } else {
2420     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2421     Offset = ((~AlignMask) & Offset) + StackAlignment +
2422       (StackAlignment-SlotSize);
2423   }
2424   return Offset;
2425 }
2426
2427 /// MatchingStackOffset - Return true if the given stack call argument is
2428 /// already available in the same position (relatively) of the caller's
2429 /// incoming argument stack.
2430 static
2431 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2432                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2433                          const X86InstrInfo *TII) {
2434   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2435   int FI = INT_MAX;
2436   if (Arg.getOpcode() == ISD::CopyFromReg) {
2437     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2438     if (!TargetRegisterInfo::isVirtualRegister(VR))
2439       return false;
2440     MachineInstr *Def = MRI->getVRegDef(VR);
2441     if (!Def)
2442       return false;
2443     if (!Flags.isByVal()) {
2444       if (!TII->isLoadFromStackSlot(Def, FI))
2445         return false;
2446     } else {
2447       unsigned Opcode = Def->getOpcode();
2448       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2449           Def->getOperand(1).isFI()) {
2450         FI = Def->getOperand(1).getIndex();
2451         Bytes = Flags.getByValSize();
2452       } else
2453         return false;
2454     }
2455   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2456     if (Flags.isByVal())
2457       // ByVal argument is passed in as a pointer but it's now being
2458       // dereferenced. e.g.
2459       // define @foo(%struct.X* %A) {
2460       //   tail call @bar(%struct.X* byval %A)
2461       // }
2462       return false;
2463     SDValue Ptr = Ld->getBasePtr();
2464     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2465     if (!FINode)
2466       return false;
2467     FI = FINode->getIndex();
2468   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2469     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2470     FI = FINode->getIndex();
2471     Bytes = Flags.getByValSize();
2472   } else
2473     return false;
2474
2475   assert(FI != INT_MAX);
2476   if (!MFI->isFixedObjectIndex(FI))
2477     return false;
2478   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2479 }
2480
2481 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2482 /// for tail call optimization. Targets which want to do tail call
2483 /// optimization should implement this function.
2484 bool
2485 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2486                                                      CallingConv::ID CalleeCC,
2487                                                      bool isVarArg,
2488                                                      bool isCalleeStructRet,
2489                                                      bool isCallerStructRet,
2490                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2491                                     const SmallVectorImpl<SDValue> &OutVals,
2492                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2493                                                      SelectionDAG& DAG) const {
2494   if (!IsTailCallConvention(CalleeCC) &&
2495       CalleeCC != CallingConv::C)
2496     return false;
2497
2498   // If -tailcallopt is specified, make fastcc functions tail-callable.
2499   const MachineFunction &MF = DAG.getMachineFunction();
2500   const Function *CallerF = DAG.getMachineFunction().getFunction();
2501   CallingConv::ID CallerCC = CallerF->getCallingConv();
2502   bool CCMatch = CallerCC == CalleeCC;
2503
2504   if (GuaranteedTailCallOpt) {
2505     if (IsTailCallConvention(CalleeCC) && CCMatch)
2506       return true;
2507     return false;
2508   }
2509
2510   // Look for obvious safe cases to perform tail call optimization that do not
2511   // require ABI changes. This is what gcc calls sibcall.
2512
2513   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2514   // emit a special epilogue.
2515   if (RegInfo->needsStackRealignment(MF))
2516     return false;
2517
2518   // Also avoid sibcall optimization if either caller or callee uses struct
2519   // return semantics.
2520   if (isCalleeStructRet || isCallerStructRet)
2521     return false;
2522
2523   // An stdcall caller is expected to clean up its arguments; the callee
2524   // isn't going to do that.
2525   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2526     return false;
2527
2528   // Do not sibcall optimize vararg calls unless all arguments are passed via
2529   // registers.
2530   if (isVarArg && !Outs.empty()) {
2531
2532     // Optimizing for varargs on Win64 is unlikely to be safe without
2533     // additional testing.
2534     if (Subtarget->isTargetWin64())
2535       return false;
2536
2537     SmallVector<CCValAssign, 16> ArgLocs;
2538     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2539                    getTargetMachine(), ArgLocs, *DAG.getContext());
2540
2541     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2542     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2543       if (!ArgLocs[i].isRegLoc())
2544         return false;
2545   }
2546
2547   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2548   // Therefore if it's not used by the call it is not safe to optimize this into
2549   // a sibcall.
2550   bool Unused = false;
2551   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2552     if (!Ins[i].Used) {
2553       Unused = true;
2554       break;
2555     }
2556   }
2557   if (Unused) {
2558     SmallVector<CCValAssign, 16> RVLocs;
2559     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2560                    getTargetMachine(), RVLocs, *DAG.getContext());
2561     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2562     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2563       CCValAssign &VA = RVLocs[i];
2564       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2565         return false;
2566     }
2567   }
2568
2569   // If the calling conventions do not match, then we'd better make sure the
2570   // results are returned in the same way as what the caller expects.
2571   if (!CCMatch) {
2572     SmallVector<CCValAssign, 16> RVLocs1;
2573     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2574                     getTargetMachine(), RVLocs1, *DAG.getContext());
2575     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2576
2577     SmallVector<CCValAssign, 16> RVLocs2;
2578     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2579                     getTargetMachine(), RVLocs2, *DAG.getContext());
2580     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2581
2582     if (RVLocs1.size() != RVLocs2.size())
2583       return false;
2584     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2585       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2586         return false;
2587       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2588         return false;
2589       if (RVLocs1[i].isRegLoc()) {
2590         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2591           return false;
2592       } else {
2593         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2594           return false;
2595       }
2596     }
2597   }
2598
2599   // If the callee takes no arguments then go on to check the results of the
2600   // call.
2601   if (!Outs.empty()) {
2602     // Check if stack adjustment is needed. For now, do not do this if any
2603     // argument is passed on the stack.
2604     SmallVector<CCValAssign, 16> ArgLocs;
2605     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2606                    getTargetMachine(), ArgLocs, *DAG.getContext());
2607
2608     // Allocate shadow area for Win64
2609     if (Subtarget->isTargetWin64()) {
2610       CCInfo.AllocateStack(32, 8);
2611     }
2612
2613     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2614     if (CCInfo.getNextStackOffset()) {
2615       MachineFunction &MF = DAG.getMachineFunction();
2616       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2617         return false;
2618
2619       // Check if the arguments are already laid out in the right way as
2620       // the caller's fixed stack objects.
2621       MachineFrameInfo *MFI = MF.getFrameInfo();
2622       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2623       const X86InstrInfo *TII =
2624         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2625       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2626         CCValAssign &VA = ArgLocs[i];
2627         SDValue Arg = OutVals[i];
2628         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2629         if (VA.getLocInfo() == CCValAssign::Indirect)
2630           return false;
2631         if (!VA.isRegLoc()) {
2632           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2633                                    MFI, MRI, TII))
2634             return false;
2635         }
2636       }
2637     }
2638
2639     // If the tailcall address may be in a register, then make sure it's
2640     // possible to register allocate for it. In 32-bit, the call address can
2641     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2642     // callee-saved registers are restored. These happen to be the same
2643     // registers used to pass 'inreg' arguments so watch out for those.
2644     if (!Subtarget->is64Bit() &&
2645         !isa<GlobalAddressSDNode>(Callee) &&
2646         !isa<ExternalSymbolSDNode>(Callee)) {
2647       unsigned NumInRegs = 0;
2648       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2649         CCValAssign &VA = ArgLocs[i];
2650         if (!VA.isRegLoc())
2651           continue;
2652         unsigned Reg = VA.getLocReg();
2653         switch (Reg) {
2654         default: break;
2655         case X86::EAX: case X86::EDX: case X86::ECX:
2656           if (++NumInRegs == 3)
2657             return false;
2658           break;
2659         }
2660       }
2661     }
2662   }
2663
2664   return true;
2665 }
2666
2667 FastISel *
2668 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2669   return X86::createFastISel(funcInfo);
2670 }
2671
2672
2673 //===----------------------------------------------------------------------===//
2674 //                           Other Lowering Hooks
2675 //===----------------------------------------------------------------------===//
2676
2677 static bool MayFoldLoad(SDValue Op) {
2678   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2679 }
2680
2681 static bool MayFoldIntoStore(SDValue Op) {
2682   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2683 }
2684
2685 static bool isTargetShuffle(unsigned Opcode) {
2686   switch(Opcode) {
2687   default: return false;
2688   case X86ISD::PSHUFD:
2689   case X86ISD::PSHUFHW:
2690   case X86ISD::PSHUFLW:
2691   case X86ISD::SHUFPD:
2692   case X86ISD::PALIGN:
2693   case X86ISD::SHUFPS:
2694   case X86ISD::MOVLHPS:
2695   case X86ISD::MOVLHPD:
2696   case X86ISD::MOVHLPS:
2697   case X86ISD::MOVLPS:
2698   case X86ISD::MOVLPD:
2699   case X86ISD::MOVSHDUP:
2700   case X86ISD::MOVSLDUP:
2701   case X86ISD::MOVDDUP:
2702   case X86ISD::MOVSS:
2703   case X86ISD::MOVSD:
2704   case X86ISD::UNPCKLPS:
2705   case X86ISD::UNPCKLPD:
2706   case X86ISD::VUNPCKLPSY:
2707   case X86ISD::VUNPCKLPDY:
2708   case X86ISD::PUNPCKLWD:
2709   case X86ISD::PUNPCKLBW:
2710   case X86ISD::PUNPCKLDQ:
2711   case X86ISD::PUNPCKLQDQ:
2712   case X86ISD::UNPCKHPS:
2713   case X86ISD::UNPCKHPD:
2714   case X86ISD::PUNPCKHWD:
2715   case X86ISD::PUNPCKHBW:
2716   case X86ISD::PUNPCKHDQ:
2717   case X86ISD::PUNPCKHQDQ:
2718   case X86ISD::VPERMIL:
2719     return true;
2720   }
2721   return false;
2722 }
2723
2724 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2725                                                SDValue V1, SelectionDAG &DAG) {
2726   switch(Opc) {
2727   default: llvm_unreachable("Unknown x86 shuffle node");
2728   case X86ISD::MOVSHDUP:
2729   case X86ISD::MOVSLDUP:
2730   case X86ISD::MOVDDUP:
2731     return DAG.getNode(Opc, dl, VT, V1);
2732   }
2733
2734   return SDValue();
2735 }
2736
2737 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2738                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2739   switch(Opc) {
2740   default: llvm_unreachable("Unknown x86 shuffle node");
2741   case X86ISD::PSHUFD:
2742   case X86ISD::PSHUFHW:
2743   case X86ISD::PSHUFLW:
2744   case X86ISD::VPERMIL:
2745     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2746   }
2747
2748   return SDValue();
2749 }
2750
2751 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2752                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2753   switch(Opc) {
2754   default: llvm_unreachable("Unknown x86 shuffle node");
2755   case X86ISD::PALIGN:
2756   case X86ISD::SHUFPD:
2757   case X86ISD::SHUFPS:
2758     return DAG.getNode(Opc, dl, VT, V1, V2,
2759                        DAG.getConstant(TargetMask, MVT::i8));
2760   }
2761   return SDValue();
2762 }
2763
2764 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2765                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2766   switch(Opc) {
2767   default: llvm_unreachable("Unknown x86 shuffle node");
2768   case X86ISD::MOVLHPS:
2769   case X86ISD::MOVLHPD:
2770   case X86ISD::MOVHLPS:
2771   case X86ISD::MOVLPS:
2772   case X86ISD::MOVLPD:
2773   case X86ISD::MOVSS:
2774   case X86ISD::MOVSD:
2775   case X86ISD::UNPCKLPS:
2776   case X86ISD::UNPCKLPD:
2777   case X86ISD::VUNPCKLPSY:
2778   case X86ISD::VUNPCKLPDY:
2779   case X86ISD::PUNPCKLWD:
2780   case X86ISD::PUNPCKLBW:
2781   case X86ISD::PUNPCKLDQ:
2782   case X86ISD::PUNPCKLQDQ:
2783   case X86ISD::UNPCKHPS:
2784   case X86ISD::UNPCKHPD:
2785   case X86ISD::PUNPCKHWD:
2786   case X86ISD::PUNPCKHBW:
2787   case X86ISD::PUNPCKHDQ:
2788   case X86ISD::PUNPCKHQDQ:
2789     return DAG.getNode(Opc, dl, VT, V1, V2);
2790   }
2791   return SDValue();
2792 }
2793
2794 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2795   MachineFunction &MF = DAG.getMachineFunction();
2796   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2797   int ReturnAddrIndex = FuncInfo->getRAIndex();
2798
2799   if (ReturnAddrIndex == 0) {
2800     // Set up a frame object for the return address.
2801     uint64_t SlotSize = TD->getPointerSize();
2802     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2803                                                            false);
2804     FuncInfo->setRAIndex(ReturnAddrIndex);
2805   }
2806
2807   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2808 }
2809
2810
2811 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2812                                        bool hasSymbolicDisplacement) {
2813   // Offset should fit into 32 bit immediate field.
2814   if (!isInt<32>(Offset))
2815     return false;
2816
2817   // If we don't have a symbolic displacement - we don't have any extra
2818   // restrictions.
2819   if (!hasSymbolicDisplacement)
2820     return true;
2821
2822   // FIXME: Some tweaks might be needed for medium code model.
2823   if (M != CodeModel::Small && M != CodeModel::Kernel)
2824     return false;
2825
2826   // For small code model we assume that latest object is 16MB before end of 31
2827   // bits boundary. We may also accept pretty large negative constants knowing
2828   // that all objects are in the positive half of address space.
2829   if (M == CodeModel::Small && Offset < 16*1024*1024)
2830     return true;
2831
2832   // For kernel code model we know that all object resist in the negative half
2833   // of 32bits address space. We may not accept negative offsets, since they may
2834   // be just off and we may accept pretty large positive ones.
2835   if (M == CodeModel::Kernel && Offset > 0)
2836     return true;
2837
2838   return false;
2839 }
2840
2841 /// isCalleePop - Determines whether the callee is required to pop its
2842 /// own arguments. Callee pop is necessary to support tail calls.
2843 bool X86::isCalleePop(CallingConv::ID CallingConv,
2844                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2845   if (IsVarArg)
2846     return false;
2847
2848   switch (CallingConv) {
2849   default:
2850     return false;
2851   case CallingConv::X86_StdCall:
2852     return !is64Bit;
2853   case CallingConv::X86_FastCall:
2854     return !is64Bit;
2855   case CallingConv::X86_ThisCall:
2856     return !is64Bit;
2857   case CallingConv::Fast:
2858     return TailCallOpt;
2859   case CallingConv::GHC:
2860     return TailCallOpt;
2861   }
2862 }
2863
2864 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2865 /// specific condition code, returning the condition code and the LHS/RHS of the
2866 /// comparison to make.
2867 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2868                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2869   if (!isFP) {
2870     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2871       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2872         // X > -1   -> X == 0, jump !sign.
2873         RHS = DAG.getConstant(0, RHS.getValueType());
2874         return X86::COND_NS;
2875       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2876         // X < 0   -> X == 0, jump on sign.
2877         return X86::COND_S;
2878       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2879         // X < 1   -> X <= 0
2880         RHS = DAG.getConstant(0, RHS.getValueType());
2881         return X86::COND_LE;
2882       }
2883     }
2884
2885     switch (SetCCOpcode) {
2886     default: llvm_unreachable("Invalid integer condition!");
2887     case ISD::SETEQ:  return X86::COND_E;
2888     case ISD::SETGT:  return X86::COND_G;
2889     case ISD::SETGE:  return X86::COND_GE;
2890     case ISD::SETLT:  return X86::COND_L;
2891     case ISD::SETLE:  return X86::COND_LE;
2892     case ISD::SETNE:  return X86::COND_NE;
2893     case ISD::SETULT: return X86::COND_B;
2894     case ISD::SETUGT: return X86::COND_A;
2895     case ISD::SETULE: return X86::COND_BE;
2896     case ISD::SETUGE: return X86::COND_AE;
2897     }
2898   }
2899
2900   // First determine if it is required or is profitable to flip the operands.
2901
2902   // If LHS is a foldable load, but RHS is not, flip the condition.
2903   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2904       !ISD::isNON_EXTLoad(RHS.getNode())) {
2905     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2906     std::swap(LHS, RHS);
2907   }
2908
2909   switch (SetCCOpcode) {
2910   default: break;
2911   case ISD::SETOLT:
2912   case ISD::SETOLE:
2913   case ISD::SETUGT:
2914   case ISD::SETUGE:
2915     std::swap(LHS, RHS);
2916     break;
2917   }
2918
2919   // On a floating point condition, the flags are set as follows:
2920   // ZF  PF  CF   op
2921   //  0 | 0 | 0 | X > Y
2922   //  0 | 0 | 1 | X < Y
2923   //  1 | 0 | 0 | X == Y
2924   //  1 | 1 | 1 | unordered
2925   switch (SetCCOpcode) {
2926   default: llvm_unreachable("Condcode should be pre-legalized away");
2927   case ISD::SETUEQ:
2928   case ISD::SETEQ:   return X86::COND_E;
2929   case ISD::SETOLT:              // flipped
2930   case ISD::SETOGT:
2931   case ISD::SETGT:   return X86::COND_A;
2932   case ISD::SETOLE:              // flipped
2933   case ISD::SETOGE:
2934   case ISD::SETGE:   return X86::COND_AE;
2935   case ISD::SETUGT:              // flipped
2936   case ISD::SETULT:
2937   case ISD::SETLT:   return X86::COND_B;
2938   case ISD::SETUGE:              // flipped
2939   case ISD::SETULE:
2940   case ISD::SETLE:   return X86::COND_BE;
2941   case ISD::SETONE:
2942   case ISD::SETNE:   return X86::COND_NE;
2943   case ISD::SETUO:   return X86::COND_P;
2944   case ISD::SETO:    return X86::COND_NP;
2945   case ISD::SETOEQ:
2946   case ISD::SETUNE:  return X86::COND_INVALID;
2947   }
2948 }
2949
2950 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2951 /// code. Current x86 isa includes the following FP cmov instructions:
2952 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2953 static bool hasFPCMov(unsigned X86CC) {
2954   switch (X86CC) {
2955   default:
2956     return false;
2957   case X86::COND_B:
2958   case X86::COND_BE:
2959   case X86::COND_E:
2960   case X86::COND_P:
2961   case X86::COND_A:
2962   case X86::COND_AE:
2963   case X86::COND_NE:
2964   case X86::COND_NP:
2965     return true;
2966   }
2967 }
2968
2969 /// isFPImmLegal - Returns true if the target can instruction select the
2970 /// specified FP immediate natively. If false, the legalizer will
2971 /// materialize the FP immediate as a load from a constant pool.
2972 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2973   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2974     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2975       return true;
2976   }
2977   return false;
2978 }
2979
2980 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2981 /// the specified range (L, H].
2982 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2983   return (Val < 0) || (Val >= Low && Val < Hi);
2984 }
2985
2986 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2987 /// specified value.
2988 static bool isUndefOrEqual(int Val, int CmpVal) {
2989   if (Val < 0 || Val == CmpVal)
2990     return true;
2991   return false;
2992 }
2993
2994 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2995 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2996 /// the second operand.
2997 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2998   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2999     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3000   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3001     return (Mask[0] < 2 && Mask[1] < 2);
3002   return false;
3003 }
3004
3005 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3006   SmallVector<int, 8> M;
3007   N->getMask(M);
3008   return ::isPSHUFDMask(M, N->getValueType(0));
3009 }
3010
3011 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3012 /// is suitable for input to PSHUFHW.
3013 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3014   if (VT != MVT::v8i16)
3015     return false;
3016
3017   // Lower quadword copied in order or undef.
3018   for (int i = 0; i != 4; ++i)
3019     if (Mask[i] >= 0 && Mask[i] != i)
3020       return false;
3021
3022   // Upper quadword shuffled.
3023   for (int i = 4; i != 8; ++i)
3024     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3025       return false;
3026
3027   return true;
3028 }
3029
3030 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3031   SmallVector<int, 8> M;
3032   N->getMask(M);
3033   return ::isPSHUFHWMask(M, N->getValueType(0));
3034 }
3035
3036 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3037 /// is suitable for input to PSHUFLW.
3038 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3039   if (VT != MVT::v8i16)
3040     return false;
3041
3042   // Upper quadword copied in order.
3043   for (int i = 4; i != 8; ++i)
3044     if (Mask[i] >= 0 && Mask[i] != i)
3045       return false;
3046
3047   // Lower quadword shuffled.
3048   for (int i = 0; i != 4; ++i)
3049     if (Mask[i] >= 4)
3050       return false;
3051
3052   return true;
3053 }
3054
3055 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3056   SmallVector<int, 8> M;
3057   N->getMask(M);
3058   return ::isPSHUFLWMask(M, N->getValueType(0));
3059 }
3060
3061 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3062 /// is suitable for input to PALIGNR.
3063 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3064                           bool hasSSSE3) {
3065   int i, e = VT.getVectorNumElements();
3066
3067   // Do not handle v2i64 / v2f64 shuffles with palignr.
3068   if (e < 4 || !hasSSSE3)
3069     return false;
3070
3071   for (i = 0; i != e; ++i)
3072     if (Mask[i] >= 0)
3073       break;
3074
3075   // All undef, not a palignr.
3076   if (i == e)
3077     return false;
3078
3079   // Make sure we're shifting in the right direction.
3080   if (Mask[i] <= i)
3081     return false;
3082
3083   int s = Mask[i] - i;
3084
3085   // Check the rest of the elements to see if they are consecutive.
3086   for (++i; i != e; ++i) {
3087     int m = Mask[i];
3088     if (m >= 0 && m != s+i)
3089       return false;
3090   }
3091   return true;
3092 }
3093
3094 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3095   SmallVector<int, 8> M;
3096   N->getMask(M);
3097   return ::isPALIGNRMask(M, N->getValueType(0), true);
3098 }
3099
3100 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3101 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3102 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3103   int NumElems = VT.getVectorNumElements();
3104   if (NumElems != 2 && NumElems != 4)
3105     return false;
3106
3107   int Half = NumElems / 2;
3108   for (int i = 0; i < Half; ++i)
3109     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3110       return false;
3111   for (int i = Half; i < NumElems; ++i)
3112     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3113       return false;
3114
3115   return true;
3116 }
3117
3118 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3119   SmallVector<int, 8> M;
3120   N->getMask(M);
3121   return ::isSHUFPMask(M, N->getValueType(0));
3122 }
3123
3124 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3125 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3126 /// half elements to come from vector 1 (which would equal the dest.) and
3127 /// the upper half to come from vector 2.
3128 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3129   int NumElems = VT.getVectorNumElements();
3130
3131   if (NumElems != 2 && NumElems != 4)
3132     return false;
3133
3134   int Half = NumElems / 2;
3135   for (int i = 0; i < Half; ++i)
3136     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3137       return false;
3138   for (int i = Half; i < NumElems; ++i)
3139     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3140       return false;
3141   return true;
3142 }
3143
3144 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3145   SmallVector<int, 8> M;
3146   N->getMask(M);
3147   return isCommutedSHUFPMask(M, N->getValueType(0));
3148 }
3149
3150 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3151 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3152 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3153   if (N->getValueType(0).getVectorNumElements() != 4)
3154     return false;
3155
3156   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3157   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3158          isUndefOrEqual(N->getMaskElt(1), 7) &&
3159          isUndefOrEqual(N->getMaskElt(2), 2) &&
3160          isUndefOrEqual(N->getMaskElt(3), 3);
3161 }
3162
3163 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3164 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3165 /// <2, 3, 2, 3>
3166 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3167   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3168
3169   if (NumElems != 4)
3170     return false;
3171
3172   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3173   isUndefOrEqual(N->getMaskElt(1), 3) &&
3174   isUndefOrEqual(N->getMaskElt(2), 2) &&
3175   isUndefOrEqual(N->getMaskElt(3), 3);
3176 }
3177
3178 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3179 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3180 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3181   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3182
3183   if (NumElems != 2 && NumElems != 4)
3184     return false;
3185
3186   for (unsigned i = 0; i < NumElems/2; ++i)
3187     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3188       return false;
3189
3190   for (unsigned i = NumElems/2; i < NumElems; ++i)
3191     if (!isUndefOrEqual(N->getMaskElt(i), i))
3192       return false;
3193
3194   return true;
3195 }
3196
3197 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3198 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3199 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3200   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3201
3202   if ((NumElems != 2 && NumElems != 4)
3203       || N->getValueType(0).getSizeInBits() > 128)
3204     return false;
3205
3206   for (unsigned i = 0; i < NumElems/2; ++i)
3207     if (!isUndefOrEqual(N->getMaskElt(i), i))
3208       return false;
3209
3210   for (unsigned i = 0; i < NumElems/2; ++i)
3211     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3212       return false;
3213
3214   return true;
3215 }
3216
3217 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3218 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3219 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3220                          bool V2IsSplat = false) {
3221   int NumElts = VT.getVectorNumElements();
3222   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3223     return false;
3224
3225   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3226   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3227   // sections.
3228   unsigned NumSections = VT.getSizeInBits() / 128;
3229   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3230   unsigned NumSectionElts = NumElts / NumSections;
3231
3232   unsigned Start = 0;
3233   unsigned End = NumSectionElts;
3234   for (unsigned s = 0; s < NumSections; ++s) {
3235     for (unsigned i = Start, j = s * NumSectionElts;
3236          i != End;
3237          i += 2, ++j) {
3238       int BitI  = Mask[i];
3239       int BitI1 = Mask[i+1];
3240       if (!isUndefOrEqual(BitI, j))
3241         return false;
3242       if (V2IsSplat) {
3243         if (!isUndefOrEqual(BitI1, NumElts))
3244           return false;
3245       } else {
3246         if (!isUndefOrEqual(BitI1, j + NumElts))
3247           return false;
3248       }
3249     }
3250     // Process the next 128 bits.
3251     Start += NumSectionElts;
3252     End += NumSectionElts;
3253   }
3254
3255   return true;
3256 }
3257
3258 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3259   SmallVector<int, 8> M;
3260   N->getMask(M);
3261   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3262 }
3263
3264 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3265 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3266 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3267                          bool V2IsSplat = false) {
3268   int NumElts = VT.getVectorNumElements();
3269   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3270     return false;
3271
3272   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3273     int BitI  = Mask[i];
3274     int BitI1 = Mask[i+1];
3275     if (!isUndefOrEqual(BitI, j + NumElts/2))
3276       return false;
3277     if (V2IsSplat) {
3278       if (isUndefOrEqual(BitI1, NumElts))
3279         return false;
3280     } else {
3281       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3282         return false;
3283     }
3284   }
3285   return true;
3286 }
3287
3288 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3289   SmallVector<int, 8> M;
3290   N->getMask(M);
3291   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3292 }
3293
3294 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3295 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3296 /// <0, 0, 1, 1>
3297 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3298   int NumElems = VT.getVectorNumElements();
3299   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3300     return false;
3301
3302   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3303   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3304   // sections.
3305   unsigned NumSections = VT.getSizeInBits() / 128;
3306   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3307   unsigned NumSectionElts = NumElems / NumSections;
3308
3309   for (unsigned s = 0; s < NumSections; ++s) {
3310     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3311          i != NumSectionElts * (s + 1);
3312          i += 2, ++j) {
3313       int BitI  = Mask[i];
3314       int BitI1 = Mask[i+1];
3315
3316       if (!isUndefOrEqual(BitI, j))
3317         return false;
3318       if (!isUndefOrEqual(BitI1, j))
3319         return false;
3320     }
3321   }
3322
3323   return true;
3324 }
3325
3326 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3327   SmallVector<int, 8> M;
3328   N->getMask(M);
3329   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3330 }
3331
3332 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3333 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3334 /// <2, 2, 3, 3>
3335 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3336   int NumElems = VT.getVectorNumElements();
3337   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3338     return false;
3339
3340   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3341     int BitI  = Mask[i];
3342     int BitI1 = Mask[i+1];
3343     if (!isUndefOrEqual(BitI, j))
3344       return false;
3345     if (!isUndefOrEqual(BitI1, j))
3346       return false;
3347   }
3348   return true;
3349 }
3350
3351 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3352   SmallVector<int, 8> M;
3353   N->getMask(M);
3354   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3355 }
3356
3357 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3358 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3359 /// MOVSD, and MOVD, i.e. setting the lowest element.
3360 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3361   if (VT.getVectorElementType().getSizeInBits() < 32)
3362     return false;
3363
3364   int NumElts = VT.getVectorNumElements();
3365
3366   if (!isUndefOrEqual(Mask[0], NumElts))
3367     return false;
3368
3369   for (int i = 1; i < NumElts; ++i)
3370     if (!isUndefOrEqual(Mask[i], i))
3371       return false;
3372
3373   return true;
3374 }
3375
3376 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3377   SmallVector<int, 8> M;
3378   N->getMask(M);
3379   return ::isMOVLMask(M, N->getValueType(0));
3380 }
3381
3382 /// isVPERMILMask - Return true if the specified VECTOR_SHUFFLE operand
3383 /// specifies a shuffle of elements that is suitable for input to VPERMIL*.
3384 static bool isVPERMILMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3385   unsigned NumElts = VT.getVectorNumElements();
3386   unsigned NumLanes = VT.getSizeInBits()/128;
3387
3388   // Match any permutation of 128-bit vector with 32/64-bit types
3389   if (NumLanes == 1) {
3390     if (NumElts == 4 || NumElts == 2)
3391       return true;
3392     return false;
3393   }
3394
3395   // Only match 256-bit with 32/64-bit types
3396   if (NumElts != 8 && NumElts != 4)
3397     return false;
3398
3399   // The mask on the high lane should be the same as the low. Actually,
3400   // they can differ if any of the corresponding index in a lane is undef.
3401   int LaneSize = NumElts/NumLanes;
3402   for (int i = 0; i < LaneSize; ++i) {
3403     int HighElt = i+LaneSize;
3404     if (Mask[i] < 0 || Mask[HighElt] < 0)
3405       continue;
3406
3407     if (Mask[HighElt]-Mask[i] != LaneSize)
3408       return false;
3409   }
3410
3411   return true;
3412 }
3413
3414 /// getShuffleVPERMILImmediateediate - Return the appropriate immediate to shuffle
3415 /// the specified VECTOR_MASK mask with VPERMIL* instructions.
3416 static unsigned getShuffleVPERMILImmediate(SDNode *N) {
3417   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3418   EVT VT = SVOp->getValueType(0);
3419
3420   int NumElts = VT.getVectorNumElements();
3421   int NumLanes = VT.getSizeInBits()/128;
3422
3423   unsigned Mask = 0;
3424   for (int i = 0; i < NumElts/NumLanes /* lane size */; ++i)
3425     Mask |= SVOp->getMaskElt(i) << (i*2);
3426
3427   return Mask;
3428 }
3429
3430 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3431 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3432 /// element of vector 2 and the other elements to come from vector 1 in order.
3433 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3434                                bool V2IsSplat = false, bool V2IsUndef = false) {
3435   int NumOps = VT.getVectorNumElements();
3436   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3437     return false;
3438
3439   if (!isUndefOrEqual(Mask[0], 0))
3440     return false;
3441
3442   for (int i = 1; i < NumOps; ++i)
3443     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3444           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3445           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3446       return false;
3447
3448   return true;
3449 }
3450
3451 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3452                            bool V2IsUndef = false) {
3453   SmallVector<int, 8> M;
3454   N->getMask(M);
3455   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3456 }
3457
3458 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3459 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3460 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3461 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3462                          const X86Subtarget *Subtarget) {
3463   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3464     return false;
3465
3466   // The second vector must be undef
3467   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3468     return false;
3469
3470   EVT VT = N->getValueType(0);
3471   unsigned NumElems = VT.getVectorNumElements();
3472
3473   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3474       (VT.getSizeInBits() == 256 && NumElems != 8))
3475     return false;
3476
3477   // "i+1" is the value the indexed mask element must have
3478   for (unsigned i = 0; i < NumElems; i += 2)
3479     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3480         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3481       return false;
3482
3483   return true;
3484 }
3485
3486 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3487 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3488 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3489 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3490                          const X86Subtarget *Subtarget) {
3491   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3492     return false;
3493
3494   // The second vector must be undef
3495   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3496     return false;
3497
3498   EVT VT = N->getValueType(0);
3499   unsigned NumElems = VT.getVectorNumElements();
3500
3501   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3502       (VT.getSizeInBits() == 256 && NumElems != 8))
3503     return false;
3504
3505   // "i" is the value the indexed mask element must have
3506   for (unsigned i = 0; i < NumElems; i += 2)
3507     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3508         !isUndefOrEqual(N->getMaskElt(i+1), i))
3509       return false;
3510
3511   return true;
3512 }
3513
3514 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3515 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3516 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3517   int e = N->getValueType(0).getVectorNumElements() / 2;
3518
3519   for (int i = 0; i < e; ++i)
3520     if (!isUndefOrEqual(N->getMaskElt(i), i))
3521       return false;
3522   for (int i = 0; i < e; ++i)
3523     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3524       return false;
3525   return true;
3526 }
3527
3528 /// isVEXTRACTF128Index - Return true if the specified
3529 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3530 /// suitable for input to VEXTRACTF128.
3531 bool X86::isVEXTRACTF128Index(SDNode *N) {
3532   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3533     return false;
3534
3535   // The index should be aligned on a 128-bit boundary.
3536   uint64_t Index =
3537     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3538
3539   unsigned VL = N->getValueType(0).getVectorNumElements();
3540   unsigned VBits = N->getValueType(0).getSizeInBits();
3541   unsigned ElSize = VBits / VL;
3542   bool Result = (Index * ElSize) % 128 == 0;
3543
3544   return Result;
3545 }
3546
3547 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3548 /// operand specifies a subvector insert that is suitable for input to
3549 /// VINSERTF128.
3550 bool X86::isVINSERTF128Index(SDNode *N) {
3551   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3552     return false;
3553
3554   // The index should be aligned on a 128-bit boundary.
3555   uint64_t Index =
3556     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3557
3558   unsigned VL = N->getValueType(0).getVectorNumElements();
3559   unsigned VBits = N->getValueType(0).getSizeInBits();
3560   unsigned ElSize = VBits / VL;
3561   bool Result = (Index * ElSize) % 128 == 0;
3562
3563   return Result;
3564 }
3565
3566 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3567 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3568 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3569   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3570   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3571
3572   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3573   unsigned Mask = 0;
3574   for (int i = 0; i < NumOperands; ++i) {
3575     int Val = SVOp->getMaskElt(NumOperands-i-1);
3576     if (Val < 0) Val = 0;
3577     if (Val >= NumOperands) Val -= NumOperands;
3578     Mask |= Val;
3579     if (i != NumOperands - 1)
3580       Mask <<= Shift;
3581   }
3582   return Mask;
3583 }
3584
3585 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3586 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3587 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3588   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3589   unsigned Mask = 0;
3590   // 8 nodes, but we only care about the last 4.
3591   for (unsigned i = 7; i >= 4; --i) {
3592     int Val = SVOp->getMaskElt(i);
3593     if (Val >= 0)
3594       Mask |= (Val - 4);
3595     if (i != 4)
3596       Mask <<= 2;
3597   }
3598   return Mask;
3599 }
3600
3601 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3602 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3603 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3604   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3605   unsigned Mask = 0;
3606   // 8 nodes, but we only care about the first 4.
3607   for (int i = 3; i >= 0; --i) {
3608     int Val = SVOp->getMaskElt(i);
3609     if (Val >= 0)
3610       Mask |= Val;
3611     if (i != 0)
3612       Mask <<= 2;
3613   }
3614   return Mask;
3615 }
3616
3617 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3618 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3619 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3620   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3621   EVT VVT = N->getValueType(0);
3622   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3623   int Val = 0;
3624
3625   unsigned i, e;
3626   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3627     Val = SVOp->getMaskElt(i);
3628     if (Val >= 0)
3629       break;
3630   }
3631   assert(Val - i > 0 && "PALIGNR imm should be positive");
3632   return (Val - i) * EltSize;
3633 }
3634
3635 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3636 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3637 /// instructions.
3638 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3639   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3640     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3641
3642   uint64_t Index =
3643     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3644
3645   EVT VecVT = N->getOperand(0).getValueType();
3646   EVT ElVT = VecVT.getVectorElementType();
3647
3648   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3649   return Index / NumElemsPerChunk;
3650 }
3651
3652 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3653 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3654 /// instructions.
3655 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3656   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3657     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3658
3659   uint64_t Index =
3660     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3661
3662   EVT VecVT = N->getValueType(0);
3663   EVT ElVT = VecVT.getVectorElementType();
3664
3665   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3666   return Index / NumElemsPerChunk;
3667 }
3668
3669 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3670 /// constant +0.0.
3671 bool X86::isZeroNode(SDValue Elt) {
3672   return ((isa<ConstantSDNode>(Elt) &&
3673            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3674           (isa<ConstantFPSDNode>(Elt) &&
3675            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3676 }
3677
3678 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3679 /// their permute mask.
3680 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3681                                     SelectionDAG &DAG) {
3682   EVT VT = SVOp->getValueType(0);
3683   unsigned NumElems = VT.getVectorNumElements();
3684   SmallVector<int, 8> MaskVec;
3685
3686   for (unsigned i = 0; i != NumElems; ++i) {
3687     int idx = SVOp->getMaskElt(i);
3688     if (idx < 0)
3689       MaskVec.push_back(idx);
3690     else if (idx < (int)NumElems)
3691       MaskVec.push_back(idx + NumElems);
3692     else
3693       MaskVec.push_back(idx - NumElems);
3694   }
3695   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3696                               SVOp->getOperand(0), &MaskVec[0]);
3697 }
3698
3699 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3700 /// the two vector operands have swapped position.
3701 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3702   unsigned NumElems = VT.getVectorNumElements();
3703   for (unsigned i = 0; i != NumElems; ++i) {
3704     int idx = Mask[i];
3705     if (idx < 0)
3706       continue;
3707     else if (idx < (int)NumElems)
3708       Mask[i] = idx + NumElems;
3709     else
3710       Mask[i] = idx - NumElems;
3711   }
3712 }
3713
3714 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3715 /// match movhlps. The lower half elements should come from upper half of
3716 /// V1 (and in order), and the upper half elements should come from the upper
3717 /// half of V2 (and in order).
3718 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3719   if (Op->getValueType(0).getVectorNumElements() != 4)
3720     return false;
3721   for (unsigned i = 0, e = 2; i != e; ++i)
3722     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3723       return false;
3724   for (unsigned i = 2; i != 4; ++i)
3725     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3726       return false;
3727   return true;
3728 }
3729
3730 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3731 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3732 /// required.
3733 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3734   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3735     return false;
3736   N = N->getOperand(0).getNode();
3737   if (!ISD::isNON_EXTLoad(N))
3738     return false;
3739   if (LD)
3740     *LD = cast<LoadSDNode>(N);
3741   return true;
3742 }
3743
3744 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3745 /// match movlp{s|d}. The lower half elements should come from lower half of
3746 /// V1 (and in order), and the upper half elements should come from the upper
3747 /// half of V2 (and in order). And since V1 will become the source of the
3748 /// MOVLP, it must be either a vector load or a scalar load to vector.
3749 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3750                                ShuffleVectorSDNode *Op) {
3751   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3752     return false;
3753   // Is V2 is a vector load, don't do this transformation. We will try to use
3754   // load folding shufps op.
3755   if (ISD::isNON_EXTLoad(V2))
3756     return false;
3757
3758   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3759
3760   if (NumElems != 2 && NumElems != 4)
3761     return false;
3762   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3763     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3764       return false;
3765   for (unsigned i = NumElems/2; i != NumElems; ++i)
3766     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3767       return false;
3768   return true;
3769 }
3770
3771 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3772 /// all the same.
3773 static bool isSplatVector(SDNode *N) {
3774   if (N->getOpcode() != ISD::BUILD_VECTOR)
3775     return false;
3776
3777   SDValue SplatValue = N->getOperand(0);
3778   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3779     if (N->getOperand(i) != SplatValue)
3780       return false;
3781   return true;
3782 }
3783
3784 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3785 /// to an zero vector.
3786 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3787 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3788   SDValue V1 = N->getOperand(0);
3789   SDValue V2 = N->getOperand(1);
3790   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3791   for (unsigned i = 0; i != NumElems; ++i) {
3792     int Idx = N->getMaskElt(i);
3793     if (Idx >= (int)NumElems) {
3794       unsigned Opc = V2.getOpcode();
3795       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3796         continue;
3797       if (Opc != ISD::BUILD_VECTOR ||
3798           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3799         return false;
3800     } else if (Idx >= 0) {
3801       unsigned Opc = V1.getOpcode();
3802       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3803         continue;
3804       if (Opc != ISD::BUILD_VECTOR ||
3805           !X86::isZeroNode(V1.getOperand(Idx)))
3806         return false;
3807     }
3808   }
3809   return true;
3810 }
3811
3812 /// getZeroVector - Returns a vector of specified type with all zero elements.
3813 ///
3814 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3815                              DebugLoc dl) {
3816   assert(VT.isVector() && "Expected a vector type");
3817
3818   // Always build SSE zero vectors as <4 x i32> bitcasted
3819   // to their dest type. This ensures they get CSE'd.
3820   SDValue Vec;
3821   if (VT.getSizeInBits() == 128) {  // SSE
3822     if (HasSSE2) {  // SSE2
3823       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3824       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3825     } else { // SSE1
3826       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3827       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3828     }
3829   } else if (VT.getSizeInBits() == 256) { // AVX
3830     // 256-bit logic and arithmetic instructions in AVX are
3831     // all floating-point, no support for integer ops. Default
3832     // to emitting fp zeroed vectors then.
3833     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3834     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3835     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3836   }
3837   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3838 }
3839
3840 /// getOnesVector - Returns a vector of specified type with all bits set.
3841 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
3842 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
3843 /// original type, ensuring they get CSE'd.
3844 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3845   assert(VT.isVector() && "Expected a vector type");
3846   assert((VT.is128BitVector() || VT.is256BitVector())
3847          && "Expected a 128-bit or 256-bit vector type");
3848
3849   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3850   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3851                             Cst, Cst, Cst, Cst);
3852
3853   if (VT.is256BitVector()) {
3854     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
3855                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
3856     Vec = Insert128BitVector(InsV, Vec,
3857                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
3858   }
3859
3860   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3861 }
3862
3863 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3864 /// that point to V2 points to its first element.
3865 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3866   EVT VT = SVOp->getValueType(0);
3867   unsigned NumElems = VT.getVectorNumElements();
3868
3869   bool Changed = false;
3870   SmallVector<int, 8> MaskVec;
3871   SVOp->getMask(MaskVec);
3872
3873   for (unsigned i = 0; i != NumElems; ++i) {
3874     if (MaskVec[i] > (int)NumElems) {
3875       MaskVec[i] = NumElems;
3876       Changed = true;
3877     }
3878   }
3879   if (Changed)
3880     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3881                                 SVOp->getOperand(1), &MaskVec[0]);
3882   return SDValue(SVOp, 0);
3883 }
3884
3885 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3886 /// operation of specified width.
3887 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3888                        SDValue V2) {
3889   unsigned NumElems = VT.getVectorNumElements();
3890   SmallVector<int, 8> Mask;
3891   Mask.push_back(NumElems);
3892   for (unsigned i = 1; i != NumElems; ++i)
3893     Mask.push_back(i);
3894   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3895 }
3896
3897 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3898 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3899                           SDValue V2) {
3900   unsigned NumElems = VT.getVectorNumElements();
3901   SmallVector<int, 8> Mask;
3902   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3903     Mask.push_back(i);
3904     Mask.push_back(i + NumElems);
3905   }
3906   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3907 }
3908
3909 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
3910 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3911                           SDValue V2) {
3912   unsigned NumElems = VT.getVectorNumElements();
3913   unsigned Half = NumElems/2;
3914   SmallVector<int, 8> Mask;
3915   for (unsigned i = 0; i != Half; ++i) {
3916     Mask.push_back(i + Half);
3917     Mask.push_back(i + NumElems + Half);
3918   }
3919   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3920 }
3921
3922 // PromoteSplatv8v16 - All i16 and i8 vector types can't be used directly by
3923 // a generic shuffle instruction because the target has no such instructions.
3924 // Generate shuffles which repeat i16 and i8 several times until they can be
3925 // represented by v4f32 and then be manipulated by target suported shuffles.
3926 static SDValue PromoteSplatv8v16(SDValue V, SelectionDAG &DAG, int &EltNo) {
3927   EVT VT = V.getValueType();
3928   int NumElems = VT.getVectorNumElements();
3929   DebugLoc dl = V.getDebugLoc();
3930
3931   while (NumElems > 4) {
3932     if (EltNo < NumElems/2) {
3933       V = getUnpackl(DAG, dl, VT, V, V);
3934     } else {
3935       V = getUnpackh(DAG, dl, VT, V, V);
3936       EltNo -= NumElems/2;
3937     }
3938     NumElems >>= 1;
3939   }
3940   return V;
3941 }
3942
3943 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
3944 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
3945   EVT VT = V.getValueType();
3946   DebugLoc dl = V.getDebugLoc();
3947   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
3948          && "Vector size not supported");
3949
3950   bool Is128 = VT.getSizeInBits() == 128;
3951   EVT NVT = Is128 ? MVT::v4f32 : MVT::v8f32;
3952   V = DAG.getNode(ISD::BITCAST, dl, NVT, V);
3953
3954   if (Is128) {
3955     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3956     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3957   } else {
3958     // The second half of indicies refer to the higher part, which is a
3959     // duplication of the lower one. This makes this shuffle a perfect match
3960     // for the VPERM instruction.
3961     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
3962                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
3963     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3964   }
3965
3966   return DAG.getNode(ISD::BITCAST, dl, VT, V);
3967 }
3968
3969 /// PromoteVectorToScalarSplat - Since there's no native support for
3970 /// scalar_to_vector for 256-bit AVX, a 128-bit scalar_to_vector +
3971 /// INSERT_SUBVECTOR is generated. Recognize this idiom and do the
3972 /// shuffle before the insertion, this yields less instructions in the end.
3973 static SDValue PromoteVectorToScalarSplat(ShuffleVectorSDNode *SV,
3974                                           SelectionDAG &DAG) {
3975   EVT SrcVT = SV->getValueType(0);
3976   SDValue V1 = SV->getOperand(0);
3977   DebugLoc dl = SV->getDebugLoc();
3978   int NumElems = SrcVT.getVectorNumElements();
3979
3980   assert(SrcVT.is256BitVector() && "unknown howto handle vector type");
3981
3982   SmallVector<int, 4> Mask;
3983   for (int i = 0; i < NumElems/2; ++i)
3984     Mask.push_back(SV->getMaskElt(i));
3985
3986   EVT SVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
3987                              NumElems/2);
3988   SDValue SV1 = DAG.getVectorShuffle(SVT, dl, V1.getOperand(1),
3989                                      DAG.getUNDEF(SVT), &Mask[0]);
3990   SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), SV1,
3991                                     DAG.getConstant(0, MVT::i32), DAG, dl);
3992
3993   return Insert128BitVector(InsV, SV1,
3994                        DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
3995 }
3996
3997 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32 and
3998 /// v8i32, v16i16 or v32i8 to v8f32.
3999 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4000   EVT SrcVT = SV->getValueType(0);
4001   SDValue V1 = SV->getOperand(0);
4002   DebugLoc dl = SV->getDebugLoc();
4003
4004   int EltNo = SV->getSplatIndex();
4005   int NumElems = SrcVT.getVectorNumElements();
4006   unsigned Size = SrcVT.getSizeInBits();
4007
4008   // Extract the 128-bit part containing the splat element and update
4009   // the splat element index when it refers to the higher register.
4010   if (Size == 256) {
4011     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4012     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4013     if (Idx > 0)
4014       EltNo -= NumElems/2;
4015   }
4016
4017   // Make this 128-bit vector duplicate i8 and i16 elements
4018   if (NumElems > 4)
4019     V1 = PromoteSplatv8v16(V1, DAG, EltNo);
4020
4021   // Recreate the 256-bit vector and place the same 128-bit vector
4022   // into the low and high part. This is necessary because we want
4023   // to use VPERM to shuffle the v8f32 vector, and VPERM only shuffles
4024   // inside each separate v4f32 lane.
4025   if (Size == 256) {
4026     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4027                          DAG.getConstant(0, MVT::i32), DAG, dl);
4028     V1 = Insert128BitVector(InsV, V1,
4029                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4030   }
4031
4032   return getLegalSplat(DAG, V1, EltNo);
4033 }
4034
4035 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4036 /// vector of zero or undef vector.  This produces a shuffle where the low
4037 /// element of V2 is swizzled into the zero/undef vector, landing at element
4038 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4039 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4040                                              bool isZero, bool HasSSE2,
4041                                              SelectionDAG &DAG) {
4042   EVT VT = V2.getValueType();
4043   SDValue V1 = isZero
4044     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4045   unsigned NumElems = VT.getVectorNumElements();
4046   SmallVector<int, 16> MaskVec;
4047   for (unsigned i = 0; i != NumElems; ++i)
4048     // If this is the insertion idx, put the low elt of V2 here.
4049     MaskVec.push_back(i == Idx ? NumElems : i);
4050   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4051 }
4052
4053 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4054 /// element of the result of the vector shuffle.
4055 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4056                                    unsigned Depth) {
4057   if (Depth == 6)
4058     return SDValue();  // Limit search depth.
4059
4060   SDValue V = SDValue(N, 0);
4061   EVT VT = V.getValueType();
4062   unsigned Opcode = V.getOpcode();
4063
4064   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4065   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4066     Index = SV->getMaskElt(Index);
4067
4068     if (Index < 0)
4069       return DAG.getUNDEF(VT.getVectorElementType());
4070
4071     int NumElems = VT.getVectorNumElements();
4072     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4073     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4074   }
4075
4076   // Recurse into target specific vector shuffles to find scalars.
4077   if (isTargetShuffle(Opcode)) {
4078     int NumElems = VT.getVectorNumElements();
4079     SmallVector<unsigned, 16> ShuffleMask;
4080     SDValue ImmN;
4081
4082     switch(Opcode) {
4083     case X86ISD::SHUFPS:
4084     case X86ISD::SHUFPD:
4085       ImmN = N->getOperand(N->getNumOperands()-1);
4086       DecodeSHUFPSMask(NumElems,
4087                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4088                        ShuffleMask);
4089       break;
4090     case X86ISD::PUNPCKHBW:
4091     case X86ISD::PUNPCKHWD:
4092     case X86ISD::PUNPCKHDQ:
4093     case X86ISD::PUNPCKHQDQ:
4094       DecodePUNPCKHMask(NumElems, ShuffleMask);
4095       break;
4096     case X86ISD::UNPCKHPS:
4097     case X86ISD::UNPCKHPD:
4098       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4099       break;
4100     case X86ISD::PUNPCKLBW:
4101     case X86ISD::PUNPCKLWD:
4102     case X86ISD::PUNPCKLDQ:
4103     case X86ISD::PUNPCKLQDQ:
4104       DecodePUNPCKLMask(VT, ShuffleMask);
4105       break;
4106     case X86ISD::UNPCKLPS:
4107     case X86ISD::UNPCKLPD:
4108     case X86ISD::VUNPCKLPSY:
4109     case X86ISD::VUNPCKLPDY:
4110       DecodeUNPCKLPMask(VT, ShuffleMask);
4111       break;
4112     case X86ISD::MOVHLPS:
4113       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4114       break;
4115     case X86ISD::MOVLHPS:
4116       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4117       break;
4118     case X86ISD::PSHUFD:
4119       ImmN = N->getOperand(N->getNumOperands()-1);
4120       DecodePSHUFMask(NumElems,
4121                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4122                       ShuffleMask);
4123       break;
4124     case X86ISD::PSHUFHW:
4125       ImmN = N->getOperand(N->getNumOperands()-1);
4126       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4127                         ShuffleMask);
4128       break;
4129     case X86ISD::PSHUFLW:
4130       ImmN = N->getOperand(N->getNumOperands()-1);
4131       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4132                         ShuffleMask);
4133       break;
4134     case X86ISD::MOVSS:
4135     case X86ISD::MOVSD: {
4136       // The index 0 always comes from the first element of the second source,
4137       // this is why MOVSS and MOVSD are used in the first place. The other
4138       // elements come from the other positions of the first source vector.
4139       unsigned OpNum = (Index == 0) ? 1 : 0;
4140       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4141                                  Depth+1);
4142     }
4143     case X86ISD::VPERMIL:
4144       ImmN = N->getOperand(N->getNumOperands()-1);
4145       DecodeVPERMILMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4146                         ShuffleMask);
4147     default:
4148       assert("not implemented for target shuffle node");
4149       return SDValue();
4150     }
4151
4152     Index = ShuffleMask[Index];
4153     if (Index < 0)
4154       return DAG.getUNDEF(VT.getVectorElementType());
4155
4156     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4157     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4158                                Depth+1);
4159   }
4160
4161   // Actual nodes that may contain scalar elements
4162   if (Opcode == ISD::BITCAST) {
4163     V = V.getOperand(0);
4164     EVT SrcVT = V.getValueType();
4165     unsigned NumElems = VT.getVectorNumElements();
4166
4167     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4168       return SDValue();
4169   }
4170
4171   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4172     return (Index == 0) ? V.getOperand(0)
4173                           : DAG.getUNDEF(VT.getVectorElementType());
4174
4175   if (V.getOpcode() == ISD::BUILD_VECTOR)
4176     return V.getOperand(Index);
4177
4178   return SDValue();
4179 }
4180
4181 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4182 /// shuffle operation which come from a consecutively from a zero. The
4183 /// search can start in two different directions, from left or right.
4184 static
4185 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4186                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4187   int i = 0;
4188
4189   while (i < NumElems) {
4190     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4191     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4192     if (!(Elt.getNode() &&
4193          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4194       break;
4195     ++i;
4196   }
4197
4198   return i;
4199 }
4200
4201 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4202 /// MaskE correspond consecutively to elements from one of the vector operands,
4203 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4204 static
4205 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4206                               int OpIdx, int NumElems, unsigned &OpNum) {
4207   bool SeenV1 = false;
4208   bool SeenV2 = false;
4209
4210   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4211     int Idx = SVOp->getMaskElt(i);
4212     // Ignore undef indicies
4213     if (Idx < 0)
4214       continue;
4215
4216     if (Idx < NumElems)
4217       SeenV1 = true;
4218     else
4219       SeenV2 = true;
4220
4221     // Only accept consecutive elements from the same vector
4222     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4223       return false;
4224   }
4225
4226   OpNum = SeenV1 ? 0 : 1;
4227   return true;
4228 }
4229
4230 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4231 /// logical left shift of a vector.
4232 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4233                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4234   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4235   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4236               false /* check zeros from right */, DAG);
4237   unsigned OpSrc;
4238
4239   if (!NumZeros)
4240     return false;
4241
4242   // Considering the elements in the mask that are not consecutive zeros,
4243   // check if they consecutively come from only one of the source vectors.
4244   //
4245   //               V1 = {X, A, B, C}     0
4246   //                         \  \  \    /
4247   //   vector_shuffle V1, V2 <1, 2, 3, X>
4248   //
4249   if (!isShuffleMaskConsecutive(SVOp,
4250             0,                   // Mask Start Index
4251             NumElems-NumZeros-1, // Mask End Index
4252             NumZeros,            // Where to start looking in the src vector
4253             NumElems,            // Number of elements in vector
4254             OpSrc))              // Which source operand ?
4255     return false;
4256
4257   isLeft = false;
4258   ShAmt = NumZeros;
4259   ShVal = SVOp->getOperand(OpSrc);
4260   return true;
4261 }
4262
4263 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4264 /// logical left shift of a vector.
4265 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4266                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4267   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4268   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4269               true /* check zeros from left */, DAG);
4270   unsigned OpSrc;
4271
4272   if (!NumZeros)
4273     return false;
4274
4275   // Considering the elements in the mask that are not consecutive zeros,
4276   // check if they consecutively come from only one of the source vectors.
4277   //
4278   //                           0    { A, B, X, X } = V2
4279   //                          / \    /  /
4280   //   vector_shuffle V1, V2 <X, X, 4, 5>
4281   //
4282   if (!isShuffleMaskConsecutive(SVOp,
4283             NumZeros,     // Mask Start Index
4284             NumElems-1,   // Mask End Index
4285             0,            // Where to start looking in the src vector
4286             NumElems,     // Number of elements in vector
4287             OpSrc))       // Which source operand ?
4288     return false;
4289
4290   isLeft = true;
4291   ShAmt = NumZeros;
4292   ShVal = SVOp->getOperand(OpSrc);
4293   return true;
4294 }
4295
4296 /// isVectorShift - Returns true if the shuffle can be implemented as a
4297 /// logical left or right shift of a vector.
4298 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4299                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4300   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4301       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4302     return true;
4303
4304   return false;
4305 }
4306
4307 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4308 ///
4309 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4310                                        unsigned NumNonZero, unsigned NumZero,
4311                                        SelectionDAG &DAG,
4312                                        const TargetLowering &TLI) {
4313   if (NumNonZero > 8)
4314     return SDValue();
4315
4316   DebugLoc dl = Op.getDebugLoc();
4317   SDValue V(0, 0);
4318   bool First = true;
4319   for (unsigned i = 0; i < 16; ++i) {
4320     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4321     if (ThisIsNonZero && First) {
4322       if (NumZero)
4323         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4324       else
4325         V = DAG.getUNDEF(MVT::v8i16);
4326       First = false;
4327     }
4328
4329     if ((i & 1) != 0) {
4330       SDValue ThisElt(0, 0), LastElt(0, 0);
4331       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4332       if (LastIsNonZero) {
4333         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4334                               MVT::i16, Op.getOperand(i-1));
4335       }
4336       if (ThisIsNonZero) {
4337         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4338         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4339                               ThisElt, DAG.getConstant(8, MVT::i8));
4340         if (LastIsNonZero)
4341           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4342       } else
4343         ThisElt = LastElt;
4344
4345       if (ThisElt.getNode())
4346         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4347                         DAG.getIntPtrConstant(i/2));
4348     }
4349   }
4350
4351   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4352 }
4353
4354 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4355 ///
4356 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4357                                      unsigned NumNonZero, unsigned NumZero,
4358                                      SelectionDAG &DAG,
4359                                      const TargetLowering &TLI) {
4360   if (NumNonZero > 4)
4361     return SDValue();
4362
4363   DebugLoc dl = Op.getDebugLoc();
4364   SDValue V(0, 0);
4365   bool First = true;
4366   for (unsigned i = 0; i < 8; ++i) {
4367     bool isNonZero = (NonZeros & (1 << i)) != 0;
4368     if (isNonZero) {
4369       if (First) {
4370         if (NumZero)
4371           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4372         else
4373           V = DAG.getUNDEF(MVT::v8i16);
4374         First = false;
4375       }
4376       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4377                       MVT::v8i16, V, Op.getOperand(i),
4378                       DAG.getIntPtrConstant(i));
4379     }
4380   }
4381
4382   return V;
4383 }
4384
4385 /// getVShift - Return a vector logical shift node.
4386 ///
4387 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4388                          unsigned NumBits, SelectionDAG &DAG,
4389                          const TargetLowering &TLI, DebugLoc dl) {
4390   EVT ShVT = MVT::v2i64;
4391   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4392   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4393   return DAG.getNode(ISD::BITCAST, dl, VT,
4394                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4395                              DAG.getConstant(NumBits,
4396                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4397 }
4398
4399 SDValue
4400 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4401                                           SelectionDAG &DAG) const {
4402
4403   // Check if the scalar load can be widened into a vector load. And if
4404   // the address is "base + cst" see if the cst can be "absorbed" into
4405   // the shuffle mask.
4406   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4407     SDValue Ptr = LD->getBasePtr();
4408     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4409       return SDValue();
4410     EVT PVT = LD->getValueType(0);
4411     if (PVT != MVT::i32 && PVT != MVT::f32)
4412       return SDValue();
4413
4414     int FI = -1;
4415     int64_t Offset = 0;
4416     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4417       FI = FINode->getIndex();
4418       Offset = 0;
4419     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4420                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4421       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4422       Offset = Ptr.getConstantOperandVal(1);
4423       Ptr = Ptr.getOperand(0);
4424     } else {
4425       return SDValue();
4426     }
4427
4428     SDValue Chain = LD->getChain();
4429     // Make sure the stack object alignment is at least 16.
4430     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4431     if (DAG.InferPtrAlignment(Ptr) < 16) {
4432       if (MFI->isFixedObjectIndex(FI)) {
4433         // Can't change the alignment. FIXME: It's possible to compute
4434         // the exact stack offset and reference FI + adjust offset instead.
4435         // If someone *really* cares about this. That's the way to implement it.
4436         return SDValue();
4437       } else {
4438         MFI->setObjectAlignment(FI, 16);
4439       }
4440     }
4441
4442     // (Offset % 16) must be multiple of 4. Then address is then
4443     // Ptr + (Offset & ~15).
4444     if (Offset < 0)
4445       return SDValue();
4446     if ((Offset % 16) & 3)
4447       return SDValue();
4448     int64_t StartOffset = Offset & ~15;
4449     if (StartOffset)
4450       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4451                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4452
4453     int EltNo = (Offset - StartOffset) >> 2;
4454     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4455     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4456     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4457                              LD->getPointerInfo().getWithOffset(StartOffset),
4458                              false, false, 0);
4459     // Canonicalize it to a v4i32 shuffle.
4460     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4461     return DAG.getNode(ISD::BITCAST, dl, VT,
4462                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4463                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4464   }
4465
4466   return SDValue();
4467 }
4468
4469 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4470 /// vector of type 'VT', see if the elements can be replaced by a single large
4471 /// load which has the same value as a build_vector whose operands are 'elts'.
4472 ///
4473 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4474 ///
4475 /// FIXME: we'd also like to handle the case where the last elements are zero
4476 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4477 /// There's even a handy isZeroNode for that purpose.
4478 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4479                                         DebugLoc &DL, SelectionDAG &DAG) {
4480   EVT EltVT = VT.getVectorElementType();
4481   unsigned NumElems = Elts.size();
4482
4483   LoadSDNode *LDBase = NULL;
4484   unsigned LastLoadedElt = -1U;
4485
4486   // For each element in the initializer, see if we've found a load or an undef.
4487   // If we don't find an initial load element, or later load elements are
4488   // non-consecutive, bail out.
4489   for (unsigned i = 0; i < NumElems; ++i) {
4490     SDValue Elt = Elts[i];
4491
4492     if (!Elt.getNode() ||
4493         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4494       return SDValue();
4495     if (!LDBase) {
4496       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4497         return SDValue();
4498       LDBase = cast<LoadSDNode>(Elt.getNode());
4499       LastLoadedElt = i;
4500       continue;
4501     }
4502     if (Elt.getOpcode() == ISD::UNDEF)
4503       continue;
4504
4505     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4506     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4507       return SDValue();
4508     LastLoadedElt = i;
4509   }
4510
4511   // If we have found an entire vector of loads and undefs, then return a large
4512   // load of the entire vector width starting at the base pointer.  If we found
4513   // consecutive loads for the low half, generate a vzext_load node.
4514   if (LastLoadedElt == NumElems - 1) {
4515     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4516       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4517                          LDBase->getPointerInfo(),
4518                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4519     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4520                        LDBase->getPointerInfo(),
4521                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4522                        LDBase->getAlignment());
4523   } else if (NumElems == 4 && LastLoadedElt == 1) {
4524     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4525     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4526     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4527                                               Ops, 2, MVT::i32,
4528                                               LDBase->getMemOperand());
4529     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4530   }
4531   return SDValue();
4532 }
4533
4534 SDValue
4535 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4536   DebugLoc dl = Op.getDebugLoc();
4537
4538   EVT VT = Op.getValueType();
4539   EVT ExtVT = VT.getVectorElementType();
4540   unsigned NumElems = Op.getNumOperands();
4541
4542   // All zero's:
4543   //  - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4544   // All one's:
4545   //  - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4546   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4547       ISD::isBuildVectorAllOnes(Op.getNode())) {
4548     // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4549     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4550     // eliminated on x86-32 hosts.
4551     if (Op.getValueType() == MVT::v4i32 ||
4552         Op.getValueType() == MVT::v8i32)
4553       return Op;
4554
4555     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4556       return getOnesVector(Op.getValueType(), DAG, dl);
4557     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4558   }
4559
4560   unsigned EVTBits = ExtVT.getSizeInBits();
4561
4562   unsigned NumZero  = 0;
4563   unsigned NumNonZero = 0;
4564   unsigned NonZeros = 0;
4565   bool IsAllConstants = true;
4566   SmallSet<SDValue, 8> Values;
4567   for (unsigned i = 0; i < NumElems; ++i) {
4568     SDValue Elt = Op.getOperand(i);
4569     if (Elt.getOpcode() == ISD::UNDEF)
4570       continue;
4571     Values.insert(Elt);
4572     if (Elt.getOpcode() != ISD::Constant &&
4573         Elt.getOpcode() != ISD::ConstantFP)
4574       IsAllConstants = false;
4575     if (X86::isZeroNode(Elt))
4576       NumZero++;
4577     else {
4578       NonZeros |= (1 << i);
4579       NumNonZero++;
4580     }
4581   }
4582
4583   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4584   if (NumNonZero == 0)
4585     return DAG.getUNDEF(VT);
4586
4587   // Special case for single non-zero, non-undef, element.
4588   if (NumNonZero == 1) {
4589     unsigned Idx = CountTrailingZeros_32(NonZeros);
4590     SDValue Item = Op.getOperand(Idx);
4591
4592     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4593     // the value are obviously zero, truncate the value to i32 and do the
4594     // insertion that way.  Only do this if the value is non-constant or if the
4595     // value is a constant being inserted into element 0.  It is cheaper to do
4596     // a constant pool load than it is to do a movd + shuffle.
4597     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4598         (!IsAllConstants || Idx == 0)) {
4599       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4600         // Handle SSE only.
4601         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4602         EVT VecVT = MVT::v4i32;
4603         unsigned VecElts = 4;
4604
4605         // Truncate the value (which may itself be a constant) to i32, and
4606         // convert it to a vector with movd (S2V+shuffle to zero extend).
4607         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4608         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4609         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4610                                            Subtarget->hasSSE2(), DAG);
4611
4612         // Now we have our 32-bit value zero extended in the low element of
4613         // a vector.  If Idx != 0, swizzle it into place.
4614         if (Idx != 0) {
4615           SmallVector<int, 4> Mask;
4616           Mask.push_back(Idx);
4617           for (unsigned i = 1; i != VecElts; ++i)
4618             Mask.push_back(i);
4619           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4620                                       DAG.getUNDEF(Item.getValueType()),
4621                                       &Mask[0]);
4622         }
4623         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4624       }
4625     }
4626
4627     // If we have a constant or non-constant insertion into the low element of
4628     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4629     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4630     // depending on what the source datatype is.
4631     if (Idx == 0) {
4632       if (NumZero == 0) {
4633         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4634       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4635           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4636         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4637         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4638         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4639                                            DAG);
4640       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4641         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4642         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4643         EVT MiddleVT = MVT::v4i32;
4644         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4645         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4646                                            Subtarget->hasSSE2(), DAG);
4647         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4648       }
4649     }
4650
4651     // Is it a vector logical left shift?
4652     if (NumElems == 2 && Idx == 1 &&
4653         X86::isZeroNode(Op.getOperand(0)) &&
4654         !X86::isZeroNode(Op.getOperand(1))) {
4655       unsigned NumBits = VT.getSizeInBits();
4656       return getVShift(true, VT,
4657                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4658                                    VT, Op.getOperand(1)),
4659                        NumBits/2, DAG, *this, dl);
4660     }
4661
4662     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4663       return SDValue();
4664
4665     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4666     // is a non-constant being inserted into an element other than the low one,
4667     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4668     // movd/movss) to move this into the low element, then shuffle it into
4669     // place.
4670     if (EVTBits == 32) {
4671       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4672
4673       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4674       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4675                                          Subtarget->hasSSE2(), DAG);
4676       SmallVector<int, 8> MaskVec;
4677       for (unsigned i = 0; i < NumElems; i++)
4678         MaskVec.push_back(i == Idx ? 0 : 1);
4679       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4680     }
4681   }
4682
4683   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4684   if (Values.size() == 1) {
4685     if (EVTBits == 32) {
4686       // Instead of a shuffle like this:
4687       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4688       // Check if it's possible to issue this instead.
4689       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4690       unsigned Idx = CountTrailingZeros_32(NonZeros);
4691       SDValue Item = Op.getOperand(Idx);
4692       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4693         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4694     }
4695     return SDValue();
4696   }
4697
4698   // A vector full of immediates; various special cases are already
4699   // handled, so this is best done with a single constant-pool load.
4700   if (IsAllConstants)
4701     return SDValue();
4702
4703   // For AVX-length vectors, build the individual 128-bit pieces and use
4704   // shuffles to put them in place.
4705   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
4706     SmallVector<SDValue, 32> V;
4707     for (unsigned i = 0; i < NumElems; ++i)
4708       V.push_back(Op.getOperand(i));
4709
4710     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4711
4712     // Build both the lower and upper subvector.
4713     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4714     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4715                                 NumElems/2);
4716
4717     // Recreate the wider vector with the lower and upper part.
4718     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
4719                                 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4720     return Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32),
4721                               DAG, dl);
4722   }
4723
4724   // Let legalizer expand 2-wide build_vectors.
4725   if (EVTBits == 64) {
4726     if (NumNonZero == 1) {
4727       // One half is zero or undef.
4728       unsigned Idx = CountTrailingZeros_32(NonZeros);
4729       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4730                                  Op.getOperand(Idx));
4731       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4732                                          Subtarget->hasSSE2(), DAG);
4733     }
4734     return SDValue();
4735   }
4736
4737   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4738   if (EVTBits == 8 && NumElems == 16) {
4739     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4740                                         *this);
4741     if (V.getNode()) return V;
4742   }
4743
4744   if (EVTBits == 16 && NumElems == 8) {
4745     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4746                                       *this);
4747     if (V.getNode()) return V;
4748   }
4749
4750   // If element VT is == 32 bits, turn it into a number of shuffles.
4751   SmallVector<SDValue, 8> V;
4752   V.resize(NumElems);
4753   if (NumElems == 4 && NumZero > 0) {
4754     for (unsigned i = 0; i < 4; ++i) {
4755       bool isZero = !(NonZeros & (1 << i));
4756       if (isZero)
4757         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4758       else
4759         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4760     }
4761
4762     for (unsigned i = 0; i < 2; ++i) {
4763       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4764         default: break;
4765         case 0:
4766           V[i] = V[i*2];  // Must be a zero vector.
4767           break;
4768         case 1:
4769           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4770           break;
4771         case 2:
4772           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4773           break;
4774         case 3:
4775           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4776           break;
4777       }
4778     }
4779
4780     SmallVector<int, 8> MaskVec;
4781     bool Reverse = (NonZeros & 0x3) == 2;
4782     for (unsigned i = 0; i < 2; ++i)
4783       MaskVec.push_back(Reverse ? 1-i : i);
4784     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4785     for (unsigned i = 0; i < 2; ++i)
4786       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4787     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4788   }
4789
4790   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4791     // Check for a build vector of consecutive loads.
4792     for (unsigned i = 0; i < NumElems; ++i)
4793       V[i] = Op.getOperand(i);
4794
4795     // Check for elements which are consecutive loads.
4796     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4797     if (LD.getNode())
4798       return LD;
4799
4800     // For SSE 4.1, use insertps to put the high elements into the low element.
4801     if (getSubtarget()->hasSSE41()) {
4802       SDValue Result;
4803       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4804         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4805       else
4806         Result = DAG.getUNDEF(VT);
4807
4808       for (unsigned i = 1; i < NumElems; ++i) {
4809         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4810         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4811                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4812       }
4813       return Result;
4814     }
4815
4816     // Otherwise, expand into a number of unpckl*, start by extending each of
4817     // our (non-undef) elements to the full vector width with the element in the
4818     // bottom slot of the vector (which generates no code for SSE).
4819     for (unsigned i = 0; i < NumElems; ++i) {
4820       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4821         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4822       else
4823         V[i] = DAG.getUNDEF(VT);
4824     }
4825
4826     // Next, we iteratively mix elements, e.g. for v4f32:
4827     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4828     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4829     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4830     unsigned EltStride = NumElems >> 1;
4831     while (EltStride != 0) {
4832       for (unsigned i = 0; i < EltStride; ++i) {
4833         // If V[i+EltStride] is undef and this is the first round of mixing,
4834         // then it is safe to just drop this shuffle: V[i] is already in the
4835         // right place, the one element (since it's the first round) being
4836         // inserted as undef can be dropped.  This isn't safe for successive
4837         // rounds because they will permute elements within both vectors.
4838         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4839             EltStride == NumElems/2)
4840           continue;
4841
4842         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4843       }
4844       EltStride >>= 1;
4845     }
4846     return V[0];
4847   }
4848   return SDValue();
4849 }
4850
4851 SDValue
4852 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4853   // We support concatenate two MMX registers and place them in a MMX
4854   // register.  This is better than doing a stack convert.
4855   DebugLoc dl = Op.getDebugLoc();
4856   EVT ResVT = Op.getValueType();
4857   assert(Op.getNumOperands() == 2);
4858   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4859          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4860   int Mask[2];
4861   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4862   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4863   InVec = Op.getOperand(1);
4864   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4865     unsigned NumElts = ResVT.getVectorNumElements();
4866     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4867     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4868                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4869   } else {
4870     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4871     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4872     Mask[0] = 0; Mask[1] = 2;
4873     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4874   }
4875   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4876 }
4877
4878 // v8i16 shuffles - Prefer shuffles in the following order:
4879 // 1. [all]   pshuflw, pshufhw, optional move
4880 // 2. [ssse3] 1 x pshufb
4881 // 3. [ssse3] 2 x pshufb + 1 x por
4882 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4883 SDValue
4884 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4885                                             SelectionDAG &DAG) const {
4886   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4887   SDValue V1 = SVOp->getOperand(0);
4888   SDValue V2 = SVOp->getOperand(1);
4889   DebugLoc dl = SVOp->getDebugLoc();
4890   SmallVector<int, 8> MaskVals;
4891
4892   // Determine if more than 1 of the words in each of the low and high quadwords
4893   // of the result come from the same quadword of one of the two inputs.  Undef
4894   // mask values count as coming from any quadword, for better codegen.
4895   SmallVector<unsigned, 4> LoQuad(4);
4896   SmallVector<unsigned, 4> HiQuad(4);
4897   BitVector InputQuads(4);
4898   for (unsigned i = 0; i < 8; ++i) {
4899     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4900     int EltIdx = SVOp->getMaskElt(i);
4901     MaskVals.push_back(EltIdx);
4902     if (EltIdx < 0) {
4903       ++Quad[0];
4904       ++Quad[1];
4905       ++Quad[2];
4906       ++Quad[3];
4907       continue;
4908     }
4909     ++Quad[EltIdx / 4];
4910     InputQuads.set(EltIdx / 4);
4911   }
4912
4913   int BestLoQuad = -1;
4914   unsigned MaxQuad = 1;
4915   for (unsigned i = 0; i < 4; ++i) {
4916     if (LoQuad[i] > MaxQuad) {
4917       BestLoQuad = i;
4918       MaxQuad = LoQuad[i];
4919     }
4920   }
4921
4922   int BestHiQuad = -1;
4923   MaxQuad = 1;
4924   for (unsigned i = 0; i < 4; ++i) {
4925     if (HiQuad[i] > MaxQuad) {
4926       BestHiQuad = i;
4927       MaxQuad = HiQuad[i];
4928     }
4929   }
4930
4931   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4932   // of the two input vectors, shuffle them into one input vector so only a
4933   // single pshufb instruction is necessary. If There are more than 2 input
4934   // quads, disable the next transformation since it does not help SSSE3.
4935   bool V1Used = InputQuads[0] || InputQuads[1];
4936   bool V2Used = InputQuads[2] || InputQuads[3];
4937   if (Subtarget->hasSSSE3()) {
4938     if (InputQuads.count() == 2 && V1Used && V2Used) {
4939       BestLoQuad = InputQuads.find_first();
4940       BestHiQuad = InputQuads.find_next(BestLoQuad);
4941     }
4942     if (InputQuads.count() > 2) {
4943       BestLoQuad = -1;
4944       BestHiQuad = -1;
4945     }
4946   }
4947
4948   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4949   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4950   // words from all 4 input quadwords.
4951   SDValue NewV;
4952   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4953     SmallVector<int, 8> MaskV;
4954     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4955     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4956     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4957                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4958                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4959     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4960
4961     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4962     // source words for the shuffle, to aid later transformations.
4963     bool AllWordsInNewV = true;
4964     bool InOrder[2] = { true, true };
4965     for (unsigned i = 0; i != 8; ++i) {
4966       int idx = MaskVals[i];
4967       if (idx != (int)i)
4968         InOrder[i/4] = false;
4969       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4970         continue;
4971       AllWordsInNewV = false;
4972       break;
4973     }
4974
4975     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4976     if (AllWordsInNewV) {
4977       for (int i = 0; i != 8; ++i) {
4978         int idx = MaskVals[i];
4979         if (idx < 0)
4980           continue;
4981         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4982         if ((idx != i) && idx < 4)
4983           pshufhw = false;
4984         if ((idx != i) && idx > 3)
4985           pshuflw = false;
4986       }
4987       V1 = NewV;
4988       V2Used = false;
4989       BestLoQuad = 0;
4990       BestHiQuad = 1;
4991     }
4992
4993     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4994     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4995     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4996       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4997       unsigned TargetMask = 0;
4998       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4999                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5000       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5001                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5002       V1 = NewV.getOperand(0);
5003       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5004     }
5005   }
5006
5007   // If we have SSSE3, and all words of the result are from 1 input vector,
5008   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5009   // is present, fall back to case 4.
5010   if (Subtarget->hasSSSE3()) {
5011     SmallVector<SDValue,16> pshufbMask;
5012
5013     // If we have elements from both input vectors, set the high bit of the
5014     // shuffle mask element to zero out elements that come from V2 in the V1
5015     // mask, and elements that come from V1 in the V2 mask, so that the two
5016     // results can be OR'd together.
5017     bool TwoInputs = V1Used && V2Used;
5018     for (unsigned i = 0; i != 8; ++i) {
5019       int EltIdx = MaskVals[i] * 2;
5020       if (TwoInputs && (EltIdx >= 16)) {
5021         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5022         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5023         continue;
5024       }
5025       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5026       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5027     }
5028     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5029     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5030                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5031                                  MVT::v16i8, &pshufbMask[0], 16));
5032     if (!TwoInputs)
5033       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5034
5035     // Calculate the shuffle mask for the second input, shuffle it, and
5036     // OR it with the first shuffled input.
5037     pshufbMask.clear();
5038     for (unsigned i = 0; i != 8; ++i) {
5039       int EltIdx = MaskVals[i] * 2;
5040       if (EltIdx < 16) {
5041         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5042         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5043         continue;
5044       }
5045       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5046       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5047     }
5048     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5049     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5050                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5051                                  MVT::v16i8, &pshufbMask[0], 16));
5052     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5053     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5054   }
5055
5056   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5057   // and update MaskVals with new element order.
5058   BitVector InOrder(8);
5059   if (BestLoQuad >= 0) {
5060     SmallVector<int, 8> MaskV;
5061     for (int i = 0; i != 4; ++i) {
5062       int idx = MaskVals[i];
5063       if (idx < 0) {
5064         MaskV.push_back(-1);
5065         InOrder.set(i);
5066       } else if ((idx / 4) == BestLoQuad) {
5067         MaskV.push_back(idx & 3);
5068         InOrder.set(i);
5069       } else {
5070         MaskV.push_back(-1);
5071       }
5072     }
5073     for (unsigned i = 4; i != 8; ++i)
5074       MaskV.push_back(i);
5075     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5076                                 &MaskV[0]);
5077
5078     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5079       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5080                                NewV.getOperand(0),
5081                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5082                                DAG);
5083   }
5084
5085   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5086   // and update MaskVals with the new element order.
5087   if (BestHiQuad >= 0) {
5088     SmallVector<int, 8> MaskV;
5089     for (unsigned i = 0; i != 4; ++i)
5090       MaskV.push_back(i);
5091     for (unsigned i = 4; i != 8; ++i) {
5092       int idx = MaskVals[i];
5093       if (idx < 0) {
5094         MaskV.push_back(-1);
5095         InOrder.set(i);
5096       } else if ((idx / 4) == BestHiQuad) {
5097         MaskV.push_back((idx & 3) + 4);
5098         InOrder.set(i);
5099       } else {
5100         MaskV.push_back(-1);
5101       }
5102     }
5103     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5104                                 &MaskV[0]);
5105
5106     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5107       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5108                               NewV.getOperand(0),
5109                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5110                               DAG);
5111   }
5112
5113   // In case BestHi & BestLo were both -1, which means each quadword has a word
5114   // from each of the four input quadwords, calculate the InOrder bitvector now
5115   // before falling through to the insert/extract cleanup.
5116   if (BestLoQuad == -1 && BestHiQuad == -1) {
5117     NewV = V1;
5118     for (int i = 0; i != 8; ++i)
5119       if (MaskVals[i] < 0 || MaskVals[i] == i)
5120         InOrder.set(i);
5121   }
5122
5123   // The other elements are put in the right place using pextrw and pinsrw.
5124   for (unsigned i = 0; i != 8; ++i) {
5125     if (InOrder[i])
5126       continue;
5127     int EltIdx = MaskVals[i];
5128     if (EltIdx < 0)
5129       continue;
5130     SDValue ExtOp = (EltIdx < 8)
5131     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5132                   DAG.getIntPtrConstant(EltIdx))
5133     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5134                   DAG.getIntPtrConstant(EltIdx - 8));
5135     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5136                        DAG.getIntPtrConstant(i));
5137   }
5138   return NewV;
5139 }
5140
5141 // v16i8 shuffles - Prefer shuffles in the following order:
5142 // 1. [ssse3] 1 x pshufb
5143 // 2. [ssse3] 2 x pshufb + 1 x por
5144 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5145 static
5146 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5147                                  SelectionDAG &DAG,
5148                                  const X86TargetLowering &TLI) {
5149   SDValue V1 = SVOp->getOperand(0);
5150   SDValue V2 = SVOp->getOperand(1);
5151   DebugLoc dl = SVOp->getDebugLoc();
5152   SmallVector<int, 16> MaskVals;
5153   SVOp->getMask(MaskVals);
5154
5155   // If we have SSSE3, case 1 is generated when all result bytes come from
5156   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5157   // present, fall back to case 3.
5158   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5159   bool V1Only = true;
5160   bool V2Only = true;
5161   for (unsigned i = 0; i < 16; ++i) {
5162     int EltIdx = MaskVals[i];
5163     if (EltIdx < 0)
5164       continue;
5165     if (EltIdx < 16)
5166       V2Only = false;
5167     else
5168       V1Only = false;
5169   }
5170
5171   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5172   if (TLI.getSubtarget()->hasSSSE3()) {
5173     SmallVector<SDValue,16> pshufbMask;
5174
5175     // If all result elements are from one input vector, then only translate
5176     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5177     //
5178     // Otherwise, we have elements from both input vectors, and must zero out
5179     // elements that come from V2 in the first mask, and V1 in the second mask
5180     // so that we can OR them together.
5181     bool TwoInputs = !(V1Only || V2Only);
5182     for (unsigned i = 0; i != 16; ++i) {
5183       int EltIdx = MaskVals[i];
5184       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5185         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5186         continue;
5187       }
5188       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5189     }
5190     // If all the elements are from V2, assign it to V1 and return after
5191     // building the first pshufb.
5192     if (V2Only)
5193       V1 = V2;
5194     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5195                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5196                                  MVT::v16i8, &pshufbMask[0], 16));
5197     if (!TwoInputs)
5198       return V1;
5199
5200     // Calculate the shuffle mask for the second input, shuffle it, and
5201     // OR it with the first shuffled input.
5202     pshufbMask.clear();
5203     for (unsigned i = 0; i != 16; ++i) {
5204       int EltIdx = MaskVals[i];
5205       if (EltIdx < 16) {
5206         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5207         continue;
5208       }
5209       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5210     }
5211     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5212                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5213                                  MVT::v16i8, &pshufbMask[0], 16));
5214     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5215   }
5216
5217   // No SSSE3 - Calculate in place words and then fix all out of place words
5218   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5219   // the 16 different words that comprise the two doublequadword input vectors.
5220   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5221   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5222   SDValue NewV = V2Only ? V2 : V1;
5223   for (int i = 0; i != 8; ++i) {
5224     int Elt0 = MaskVals[i*2];
5225     int Elt1 = MaskVals[i*2+1];
5226
5227     // This word of the result is all undef, skip it.
5228     if (Elt0 < 0 && Elt1 < 0)
5229       continue;
5230
5231     // This word of the result is already in the correct place, skip it.
5232     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5233       continue;
5234     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5235       continue;
5236
5237     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5238     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5239     SDValue InsElt;
5240
5241     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5242     // using a single extract together, load it and store it.
5243     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5244       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5245                            DAG.getIntPtrConstant(Elt1 / 2));
5246       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5247                         DAG.getIntPtrConstant(i));
5248       continue;
5249     }
5250
5251     // If Elt1 is defined, extract it from the appropriate source.  If the
5252     // source byte is not also odd, shift the extracted word left 8 bits
5253     // otherwise clear the bottom 8 bits if we need to do an or.
5254     if (Elt1 >= 0) {
5255       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5256                            DAG.getIntPtrConstant(Elt1 / 2));
5257       if ((Elt1 & 1) == 0)
5258         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5259                              DAG.getConstant(8,
5260                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5261       else if (Elt0 >= 0)
5262         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5263                              DAG.getConstant(0xFF00, MVT::i16));
5264     }
5265     // If Elt0 is defined, extract it from the appropriate source.  If the
5266     // source byte is not also even, shift the extracted word right 8 bits. If
5267     // Elt1 was also defined, OR the extracted values together before
5268     // inserting them in the result.
5269     if (Elt0 >= 0) {
5270       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5271                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5272       if ((Elt0 & 1) != 0)
5273         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5274                               DAG.getConstant(8,
5275                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5276       else if (Elt1 >= 0)
5277         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5278                              DAG.getConstant(0x00FF, MVT::i16));
5279       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5280                          : InsElt0;
5281     }
5282     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5283                        DAG.getIntPtrConstant(i));
5284   }
5285   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5286 }
5287
5288 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5289 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5290 /// done when every pair / quad of shuffle mask elements point to elements in
5291 /// the right sequence. e.g.
5292 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5293 static
5294 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5295                                  SelectionDAG &DAG, DebugLoc dl) {
5296   EVT VT = SVOp->getValueType(0);
5297   SDValue V1 = SVOp->getOperand(0);
5298   SDValue V2 = SVOp->getOperand(1);
5299   unsigned NumElems = VT.getVectorNumElements();
5300   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5301   EVT NewVT;
5302   switch (VT.getSimpleVT().SimpleTy) {
5303   default: assert(false && "Unexpected!");
5304   case MVT::v4f32: NewVT = MVT::v2f64; break;
5305   case MVT::v4i32: NewVT = MVT::v2i64; break;
5306   case MVT::v8i16: NewVT = MVT::v4i32; break;
5307   case MVT::v16i8: NewVT = MVT::v4i32; break;
5308   }
5309
5310   int Scale = NumElems / NewWidth;
5311   SmallVector<int, 8> MaskVec;
5312   for (unsigned i = 0; i < NumElems; i += Scale) {
5313     int StartIdx = -1;
5314     for (int j = 0; j < Scale; ++j) {
5315       int EltIdx = SVOp->getMaskElt(i+j);
5316       if (EltIdx < 0)
5317         continue;
5318       if (StartIdx == -1)
5319         StartIdx = EltIdx - (EltIdx % Scale);
5320       if (EltIdx != StartIdx + j)
5321         return SDValue();
5322     }
5323     if (StartIdx == -1)
5324       MaskVec.push_back(-1);
5325     else
5326       MaskVec.push_back(StartIdx / Scale);
5327   }
5328
5329   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5330   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5331   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5332 }
5333
5334 /// getVZextMovL - Return a zero-extending vector move low node.
5335 ///
5336 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5337                             SDValue SrcOp, SelectionDAG &DAG,
5338                             const X86Subtarget *Subtarget, DebugLoc dl) {
5339   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5340     LoadSDNode *LD = NULL;
5341     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5342       LD = dyn_cast<LoadSDNode>(SrcOp);
5343     if (!LD) {
5344       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5345       // instead.
5346       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5347       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5348           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5349           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5350           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5351         // PR2108
5352         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5353         return DAG.getNode(ISD::BITCAST, dl, VT,
5354                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5355                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5356                                                    OpVT,
5357                                                    SrcOp.getOperand(0)
5358                                                           .getOperand(0))));
5359       }
5360     }
5361   }
5362
5363   return DAG.getNode(ISD::BITCAST, dl, VT,
5364                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5365                                  DAG.getNode(ISD::BITCAST, dl,
5366                                              OpVT, SrcOp)));
5367 }
5368
5369 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5370 /// which could not be matched by any known target speficic shuffle
5371 static SDValue
5372 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5373   return SDValue();
5374 }
5375
5376 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5377 /// 4 elements, and match them with several different shuffle types.
5378 static SDValue
5379 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5380   SDValue V1 = SVOp->getOperand(0);
5381   SDValue V2 = SVOp->getOperand(1);
5382   DebugLoc dl = SVOp->getDebugLoc();
5383   EVT VT = SVOp->getValueType(0);
5384
5385   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5386
5387   SmallVector<std::pair<int, int>, 8> Locs;
5388   Locs.resize(4);
5389   SmallVector<int, 8> Mask1(4U, -1);
5390   SmallVector<int, 8> PermMask;
5391   SVOp->getMask(PermMask);
5392
5393   unsigned NumHi = 0;
5394   unsigned NumLo = 0;
5395   for (unsigned i = 0; i != 4; ++i) {
5396     int Idx = PermMask[i];
5397     if (Idx < 0) {
5398       Locs[i] = std::make_pair(-1, -1);
5399     } else {
5400       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5401       if (Idx < 4) {
5402         Locs[i] = std::make_pair(0, NumLo);
5403         Mask1[NumLo] = Idx;
5404         NumLo++;
5405       } else {
5406         Locs[i] = std::make_pair(1, NumHi);
5407         if (2+NumHi < 4)
5408           Mask1[2+NumHi] = Idx;
5409         NumHi++;
5410       }
5411     }
5412   }
5413
5414   if (NumLo <= 2 && NumHi <= 2) {
5415     // If no more than two elements come from either vector. This can be
5416     // implemented with two shuffles. First shuffle gather the elements.
5417     // The second shuffle, which takes the first shuffle as both of its
5418     // vector operands, put the elements into the right order.
5419     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5420
5421     SmallVector<int, 8> Mask2(4U, -1);
5422
5423     for (unsigned i = 0; i != 4; ++i) {
5424       if (Locs[i].first == -1)
5425         continue;
5426       else {
5427         unsigned Idx = (i < 2) ? 0 : 4;
5428         Idx += Locs[i].first * 2 + Locs[i].second;
5429         Mask2[i] = Idx;
5430       }
5431     }
5432
5433     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5434   } else if (NumLo == 3 || NumHi == 3) {
5435     // Otherwise, we must have three elements from one vector, call it X, and
5436     // one element from the other, call it Y.  First, use a shufps to build an
5437     // intermediate vector with the one element from Y and the element from X
5438     // that will be in the same half in the final destination (the indexes don't
5439     // matter). Then, use a shufps to build the final vector, taking the half
5440     // containing the element from Y from the intermediate, and the other half
5441     // from X.
5442     if (NumHi == 3) {
5443       // Normalize it so the 3 elements come from V1.
5444       CommuteVectorShuffleMask(PermMask, VT);
5445       std::swap(V1, V2);
5446     }
5447
5448     // Find the element from V2.
5449     unsigned HiIndex;
5450     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5451       int Val = PermMask[HiIndex];
5452       if (Val < 0)
5453         continue;
5454       if (Val >= 4)
5455         break;
5456     }
5457
5458     Mask1[0] = PermMask[HiIndex];
5459     Mask1[1] = -1;
5460     Mask1[2] = PermMask[HiIndex^1];
5461     Mask1[3] = -1;
5462     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5463
5464     if (HiIndex >= 2) {
5465       Mask1[0] = PermMask[0];
5466       Mask1[1] = PermMask[1];
5467       Mask1[2] = HiIndex & 1 ? 6 : 4;
5468       Mask1[3] = HiIndex & 1 ? 4 : 6;
5469       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5470     } else {
5471       Mask1[0] = HiIndex & 1 ? 2 : 0;
5472       Mask1[1] = HiIndex & 1 ? 0 : 2;
5473       Mask1[2] = PermMask[2];
5474       Mask1[3] = PermMask[3];
5475       if (Mask1[2] >= 0)
5476         Mask1[2] += 4;
5477       if (Mask1[3] >= 0)
5478         Mask1[3] += 4;
5479       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5480     }
5481   }
5482
5483   // Break it into (shuffle shuffle_hi, shuffle_lo).
5484   Locs.clear();
5485   Locs.resize(4);
5486   SmallVector<int,8> LoMask(4U, -1);
5487   SmallVector<int,8> HiMask(4U, -1);
5488
5489   SmallVector<int,8> *MaskPtr = &LoMask;
5490   unsigned MaskIdx = 0;
5491   unsigned LoIdx = 0;
5492   unsigned HiIdx = 2;
5493   for (unsigned i = 0; i != 4; ++i) {
5494     if (i == 2) {
5495       MaskPtr = &HiMask;
5496       MaskIdx = 1;
5497       LoIdx = 0;
5498       HiIdx = 2;
5499     }
5500     int Idx = PermMask[i];
5501     if (Idx < 0) {
5502       Locs[i] = std::make_pair(-1, -1);
5503     } else if (Idx < 4) {
5504       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5505       (*MaskPtr)[LoIdx] = Idx;
5506       LoIdx++;
5507     } else {
5508       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5509       (*MaskPtr)[HiIdx] = Idx;
5510       HiIdx++;
5511     }
5512   }
5513
5514   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5515   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5516   SmallVector<int, 8> MaskOps;
5517   for (unsigned i = 0; i != 4; ++i) {
5518     if (Locs[i].first == -1) {
5519       MaskOps.push_back(-1);
5520     } else {
5521       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5522       MaskOps.push_back(Idx);
5523     }
5524   }
5525   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5526 }
5527
5528 static bool MayFoldVectorLoad(SDValue V) {
5529   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5530     V = V.getOperand(0);
5531   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5532     V = V.getOperand(0);
5533   if (MayFoldLoad(V))
5534     return true;
5535   return false;
5536 }
5537
5538 // FIXME: the version above should always be used. Since there's
5539 // a bug where several vector shuffles can't be folded because the
5540 // DAG is not updated during lowering and a node claims to have two
5541 // uses while it only has one, use this version, and let isel match
5542 // another instruction if the load really happens to have more than
5543 // one use. Remove this version after this bug get fixed.
5544 // rdar://8434668, PR8156
5545 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5546   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5547     V = V.getOperand(0);
5548   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5549     V = V.getOperand(0);
5550   if (ISD::isNormalLoad(V.getNode()))
5551     return true;
5552   return false;
5553 }
5554
5555 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5556 /// a vector extract, and if both can be later optimized into a single load.
5557 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5558 /// here because otherwise a target specific shuffle node is going to be
5559 /// emitted for this shuffle, and the optimization not done.
5560 /// FIXME: This is probably not the best approach, but fix the problem
5561 /// until the right path is decided.
5562 static
5563 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5564                                          const TargetLowering &TLI) {
5565   EVT VT = V.getValueType();
5566   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5567
5568   // Be sure that the vector shuffle is present in a pattern like this:
5569   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5570   if (!V.hasOneUse())
5571     return false;
5572
5573   SDNode *N = *V.getNode()->use_begin();
5574   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5575     return false;
5576
5577   SDValue EltNo = N->getOperand(1);
5578   if (!isa<ConstantSDNode>(EltNo))
5579     return false;
5580
5581   // If the bit convert changed the number of elements, it is unsafe
5582   // to examine the mask.
5583   bool HasShuffleIntoBitcast = false;
5584   if (V.getOpcode() == ISD::BITCAST) {
5585     EVT SrcVT = V.getOperand(0).getValueType();
5586     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5587       return false;
5588     V = V.getOperand(0);
5589     HasShuffleIntoBitcast = true;
5590   }
5591
5592   // Select the input vector, guarding against out of range extract vector.
5593   unsigned NumElems = VT.getVectorNumElements();
5594   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5595   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5596   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5597
5598   // Skip one more bit_convert if necessary
5599   if (V.getOpcode() == ISD::BITCAST)
5600     V = V.getOperand(0);
5601
5602   if (ISD::isNormalLoad(V.getNode())) {
5603     // Is the original load suitable?
5604     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5605
5606     // FIXME: avoid the multi-use bug that is preventing lots of
5607     // of foldings to be detected, this is still wrong of course, but
5608     // give the temporary desired behavior, and if it happens that
5609     // the load has real more uses, during isel it will not fold, and
5610     // will generate poor code.
5611     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5612       return false;
5613
5614     if (!HasShuffleIntoBitcast)
5615       return true;
5616
5617     // If there's a bitcast before the shuffle, check if the load type and
5618     // alignment is valid.
5619     unsigned Align = LN0->getAlignment();
5620     unsigned NewAlign =
5621       TLI.getTargetData()->getABITypeAlignment(
5622                                     VT.getTypeForEVT(*DAG.getContext()));
5623
5624     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5625       return false;
5626   }
5627
5628   return true;
5629 }
5630
5631 static
5632 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5633   EVT VT = Op.getValueType();
5634
5635   // Canonizalize to v2f64.
5636   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5637   return DAG.getNode(ISD::BITCAST, dl, VT,
5638                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5639                                           V1, DAG));
5640 }
5641
5642 static
5643 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5644                         bool HasSSE2) {
5645   SDValue V1 = Op.getOperand(0);
5646   SDValue V2 = Op.getOperand(1);
5647   EVT VT = Op.getValueType();
5648
5649   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5650
5651   if (HasSSE2 && VT == MVT::v2f64)
5652     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5653
5654   // v4f32 or v4i32
5655   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5656 }
5657
5658 static
5659 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5660   SDValue V1 = Op.getOperand(0);
5661   SDValue V2 = Op.getOperand(1);
5662   EVT VT = Op.getValueType();
5663
5664   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5665          "unsupported shuffle type");
5666
5667   if (V2.getOpcode() == ISD::UNDEF)
5668     V2 = V1;
5669
5670   // v4i32 or v4f32
5671   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5672 }
5673
5674 static
5675 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5676   SDValue V1 = Op.getOperand(0);
5677   SDValue V2 = Op.getOperand(1);
5678   EVT VT = Op.getValueType();
5679   unsigned NumElems = VT.getVectorNumElements();
5680
5681   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5682   // operand of these instructions is only memory, so check if there's a
5683   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5684   // same masks.
5685   bool CanFoldLoad = false;
5686
5687   // Trivial case, when V2 comes from a load.
5688   if (MayFoldVectorLoad(V2))
5689     CanFoldLoad = true;
5690
5691   // When V1 is a load, it can be folded later into a store in isel, example:
5692   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5693   //    turns into:
5694   //  (MOVLPSmr addr:$src1, VR128:$src2)
5695   // So, recognize this potential and also use MOVLPS or MOVLPD
5696   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5697     CanFoldLoad = true;
5698
5699   // Both of them can't be memory operations though.
5700   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5701     CanFoldLoad = false;
5702
5703   if (CanFoldLoad) {
5704     if (HasSSE2 && NumElems == 2)
5705       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5706
5707     if (NumElems == 4)
5708       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5709   }
5710
5711   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5712   // movl and movlp will both match v2i64, but v2i64 is never matched by
5713   // movl earlier because we make it strict to avoid messing with the movlp load
5714   // folding logic (see the code above getMOVLP call). Match it here then,
5715   // this is horrible, but will stay like this until we move all shuffle
5716   // matching to x86 specific nodes. Note that for the 1st condition all
5717   // types are matched with movsd.
5718   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5719     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5720   else if (HasSSE2)
5721     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5722
5723
5724   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5725
5726   // Invert the operand order and use SHUFPS to match it.
5727   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5728                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5729 }
5730
5731 static inline unsigned getUNPCKLOpcode(EVT VT) {
5732   switch(VT.getSimpleVT().SimpleTy) {
5733   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5734   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5735   case MVT::v4f32: return X86ISD::UNPCKLPS;
5736   case MVT::v2f64: return X86ISD::UNPCKLPD;
5737   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5738   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5739   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5740   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5741   default:
5742     llvm_unreachable("Unknown type for unpckl");
5743   }
5744   return 0;
5745 }
5746
5747 static inline unsigned getUNPCKHOpcode(EVT VT) {
5748   switch(VT.getSimpleVT().SimpleTy) {
5749   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5750   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5751   case MVT::v4f32: return X86ISD::UNPCKHPS;
5752   case MVT::v2f64: return X86ISD::UNPCKHPD;
5753   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5754   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5755   default:
5756     llvm_unreachable("Unknown type for unpckh");
5757   }
5758   return 0;
5759 }
5760
5761 static
5762 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5763                                const TargetLowering &TLI,
5764                                const X86Subtarget *Subtarget) {
5765   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5766   EVT VT = Op.getValueType();
5767   DebugLoc dl = Op.getDebugLoc();
5768   SDValue V1 = Op.getOperand(0);
5769   SDValue V2 = Op.getOperand(1);
5770
5771   if (isZeroShuffle(SVOp))
5772     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5773
5774   // Handle splat operations
5775   if (SVOp->isSplat()) {
5776     unsigned NumElem = VT.getVectorNumElements();
5777     // Special case, this is the only place now where it's allowed to return
5778     // a vector_shuffle operation without using a target specific node, because
5779     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
5780     // this be moved to DAGCombine instead?
5781     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5782       return Op;
5783
5784     // Since there's no native support for scalar_to_vector for 256-bit AVX, a
5785     // 128-bit scalar_to_vector + INSERT_SUBVECTOR is generated. Recognize this
5786     // idiom and do the shuffle before the insertion, this yields less
5787     // instructions in the end.
5788     if (VT.is256BitVector() &&
5789         V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
5790         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
5791         V1.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR)
5792       return PromoteVectorToScalarSplat(SVOp, DAG);
5793
5794     // Handle splats by matching through known shuffle masks
5795     if ((VT.is128BitVector() && NumElem <= 4) ||
5796         (VT.is256BitVector() && NumElem <= 8))
5797       return SDValue();
5798
5799     // All i16 and i8 vector types can't be used directly by a generic shuffle
5800     // instruction because the target has no such instruction. Generate shuffles
5801     // which repeat i16 and i8 several times until they fit in i32, and then can
5802     // be manipulated by target suported shuffles. After the insertion of the
5803     // necessary shuffles, the result is bitcasted back to v4f32 or v8f32.
5804     return PromoteSplat(SVOp, DAG);
5805   }
5806
5807   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5808   // do it!
5809   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5810     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5811     if (NewOp.getNode())
5812       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5813   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5814     // FIXME: Figure out a cleaner way to do this.
5815     // Try to make use of movq to zero out the top part.
5816     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5817       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5818       if (NewOp.getNode()) {
5819         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5820           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5821                               DAG, Subtarget, dl);
5822       }
5823     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5824       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5825       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5826         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5827                             DAG, Subtarget, dl);
5828     }
5829   }
5830   return SDValue();
5831 }
5832
5833 SDValue
5834 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5835   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5836   SDValue V1 = Op.getOperand(0);
5837   SDValue V2 = Op.getOperand(1);
5838   EVT VT = Op.getValueType();
5839   DebugLoc dl = Op.getDebugLoc();
5840   unsigned NumElems = VT.getVectorNumElements();
5841   bool isMMX = VT.getSizeInBits() == 64;
5842   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5843   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5844   bool V1IsSplat = false;
5845   bool V2IsSplat = false;
5846   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5847   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5848   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5849   MachineFunction &MF = DAG.getMachineFunction();
5850   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5851
5852   // Shuffle operations on MMX not supported.
5853   if (isMMX)
5854     return Op;
5855
5856   // Vector shuffle lowering takes 3 steps:
5857   //
5858   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5859   //    narrowing and commutation of operands should be handled.
5860   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5861   //    shuffle nodes.
5862   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5863   //    so the shuffle can be broken into other shuffles and the legalizer can
5864   //    try the lowering again.
5865   //
5866   // The general ideia is that no vector_shuffle operation should be left to
5867   // be matched during isel, all of them must be converted to a target specific
5868   // node here.
5869
5870   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5871   // narrowing and commutation of operands should be handled. The actual code
5872   // doesn't include all of those, work in progress...
5873   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5874   if (NewOp.getNode())
5875     return NewOp;
5876
5877   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5878   // unpckh_undef). Only use pshufd if speed is more important than size.
5879   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5880     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5881   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5882     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5883
5884   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5885       RelaxedMayFoldVectorLoad(V1))
5886     return getMOVDDup(Op, dl, V1, DAG);
5887
5888   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5889     return getMOVHighToLow(Op, dl, DAG);
5890
5891   // Use to match splats
5892   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5893       (VT == MVT::v2f64 || VT == MVT::v2i64))
5894     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5895
5896   if (X86::isPSHUFDMask(SVOp)) {
5897     // The actual implementation will match the mask in the if above and then
5898     // during isel it can match several different instructions, not only pshufd
5899     // as its name says, sad but true, emulate the behavior for now...
5900     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5901         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5902
5903     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5904
5905     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5906       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5907
5908     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5909       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5910                                   TargetMask, DAG);
5911
5912     if (VT == MVT::v4f32)
5913       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5914                                   TargetMask, DAG);
5915   }
5916
5917   // Check if this can be converted into a logical shift.
5918   bool isLeft = false;
5919   unsigned ShAmt = 0;
5920   SDValue ShVal;
5921   bool isShift = getSubtarget()->hasSSE2() &&
5922     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5923   if (isShift && ShVal.hasOneUse()) {
5924     // If the shifted value has multiple uses, it may be cheaper to use
5925     // v_set0 + movlhps or movhlps, etc.
5926     EVT EltVT = VT.getVectorElementType();
5927     ShAmt *= EltVT.getSizeInBits();
5928     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5929   }
5930
5931   if (X86::isMOVLMask(SVOp)) {
5932     if (V1IsUndef)
5933       return V2;
5934     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5935       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5936     if (!X86::isMOVLPMask(SVOp)) {
5937       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5938         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5939
5940       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5941         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5942     }
5943   }
5944
5945   // FIXME: fold these into legal mask.
5946   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5947     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5948
5949   if (X86::isMOVHLPSMask(SVOp))
5950     return getMOVHighToLow(Op, dl, DAG);
5951
5952   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
5953     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5954
5955   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
5956     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5957
5958   if (X86::isMOVLPMask(SVOp))
5959     return getMOVLP(Op, dl, DAG, HasSSE2);
5960
5961   if (ShouldXformToMOVHLPS(SVOp) ||
5962       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5963     return CommuteVectorShuffle(SVOp, DAG);
5964
5965   if (isShift) {
5966     // No better options. Use a vshl / vsrl.
5967     EVT EltVT = VT.getVectorElementType();
5968     ShAmt *= EltVT.getSizeInBits();
5969     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5970   }
5971
5972   bool Commuted = false;
5973   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5974   // 1,1,1,1 -> v8i16 though.
5975   V1IsSplat = isSplatVector(V1.getNode());
5976   V2IsSplat = isSplatVector(V2.getNode());
5977
5978   // Canonicalize the splat or undef, if present, to be on the RHS.
5979   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5980     Op = CommuteVectorShuffle(SVOp, DAG);
5981     SVOp = cast<ShuffleVectorSDNode>(Op);
5982     V1 = SVOp->getOperand(0);
5983     V2 = SVOp->getOperand(1);
5984     std::swap(V1IsSplat, V2IsSplat);
5985     std::swap(V1IsUndef, V2IsUndef);
5986     Commuted = true;
5987   }
5988
5989   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5990     // Shuffling low element of v1 into undef, just return v1.
5991     if (V2IsUndef)
5992       return V1;
5993     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5994     // the instruction selector will not match, so get a canonical MOVL with
5995     // swapped operands to undo the commute.
5996     return getMOVL(DAG, dl, VT, V2, V1);
5997   }
5998
5999   if (X86::isUNPCKLMask(SVOp))
6000     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6001
6002   if (X86::isUNPCKHMask(SVOp))
6003     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6004
6005   if (V2IsSplat) {
6006     // Normalize mask so all entries that point to V2 points to its first
6007     // element then try to match unpck{h|l} again. If match, return a
6008     // new vector_shuffle with the corrected mask.
6009     SDValue NewMask = NormalizeMask(SVOp, DAG);
6010     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6011     if (NSVOp != SVOp) {
6012       if (X86::isUNPCKLMask(NSVOp, true)) {
6013         return NewMask;
6014       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6015         return NewMask;
6016       }
6017     }
6018   }
6019
6020   if (Commuted) {
6021     // Commute is back and try unpck* again.
6022     // FIXME: this seems wrong.
6023     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6024     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6025
6026     if (X86::isUNPCKLMask(NewSVOp))
6027       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6028
6029     if (X86::isUNPCKHMask(NewSVOp))
6030       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6031   }
6032
6033   // Normalize the node to match x86 shuffle ops if needed
6034   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6035     return CommuteVectorShuffle(SVOp, DAG);
6036
6037   // The checks below are all present in isShuffleMaskLegal, but they are
6038   // inlined here right now to enable us to directly emit target specific
6039   // nodes, and remove one by one until they don't return Op anymore.
6040   SmallVector<int, 16> M;
6041   SVOp->getMask(M);
6042
6043   if (isPALIGNRMask(M, VT, HasSSSE3))
6044     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6045                                 X86::getShufflePALIGNRImmediate(SVOp),
6046                                 DAG);
6047
6048   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6049       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6050     if (VT == MVT::v2f64)
6051       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6052     if (VT == MVT::v2i64)
6053       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6054   }
6055
6056   if (isPSHUFHWMask(M, VT))
6057     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6058                                 X86::getShufflePSHUFHWImmediate(SVOp),
6059                                 DAG);
6060
6061   if (isPSHUFLWMask(M, VT))
6062     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6063                                 X86::getShufflePSHUFLWImmediate(SVOp),
6064                                 DAG);
6065
6066   if (isSHUFPMask(M, VT)) {
6067     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6068     if (VT == MVT::v4f32 || VT == MVT::v4i32)
6069       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6070                                   TargetMask, DAG);
6071     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6072       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6073                                   TargetMask, DAG);
6074   }
6075
6076   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6077     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6078   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6079     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6080
6081   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6082   if (VT == MVT::v8i16) {
6083     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6084     if (NewOp.getNode())
6085       return NewOp;
6086   }
6087
6088   if (VT == MVT::v16i8) {
6089     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6090     if (NewOp.getNode())
6091       return NewOp;
6092   }
6093
6094   // Handle all 128-bit wide vectors with 4 elements, and match them with
6095   // several different shuffle types.
6096   if (NumElems == 4 && VT.getSizeInBits() == 128)
6097     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6098
6099   //===--------------------------------------------------------------------===//
6100   //  Custom lower or generate target specific nodes for 256-bit shuffles.
6101
6102   // Handle VPERMIL permutations
6103   if (isVPERMILMask(M, VT)) {
6104     unsigned TargetMask = getShuffleVPERMILImmediate(SVOp);
6105     if (VT == MVT::v8f32)
6106       return getTargetShuffleNode(X86ISD::VPERMIL, dl, VT, V1, TargetMask, DAG);
6107   }
6108
6109   // Handle general 256-bit shuffles
6110   if (VT.is256BitVector())
6111     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6112
6113   return SDValue();
6114 }
6115
6116 SDValue
6117 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6118                                                 SelectionDAG &DAG) const {
6119   EVT VT = Op.getValueType();
6120   DebugLoc dl = Op.getDebugLoc();
6121   if (VT.getSizeInBits() == 8) {
6122     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6123                                     Op.getOperand(0), Op.getOperand(1));
6124     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6125                                     DAG.getValueType(VT));
6126     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6127   } else if (VT.getSizeInBits() == 16) {
6128     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6129     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6130     if (Idx == 0)
6131       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6132                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6133                                      DAG.getNode(ISD::BITCAST, dl,
6134                                                  MVT::v4i32,
6135                                                  Op.getOperand(0)),
6136                                      Op.getOperand(1)));
6137     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6138                                     Op.getOperand(0), Op.getOperand(1));
6139     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6140                                     DAG.getValueType(VT));
6141     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6142   } else if (VT == MVT::f32) {
6143     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6144     // the result back to FR32 register. It's only worth matching if the
6145     // result has a single use which is a store or a bitcast to i32.  And in
6146     // the case of a store, it's not worth it if the index is a constant 0,
6147     // because a MOVSSmr can be used instead, which is smaller and faster.
6148     if (!Op.hasOneUse())
6149       return SDValue();
6150     SDNode *User = *Op.getNode()->use_begin();
6151     if ((User->getOpcode() != ISD::STORE ||
6152          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6153           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6154         (User->getOpcode() != ISD::BITCAST ||
6155          User->getValueType(0) != MVT::i32))
6156       return SDValue();
6157     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6158                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6159                                               Op.getOperand(0)),
6160                                               Op.getOperand(1));
6161     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6162   } else if (VT == MVT::i32) {
6163     // ExtractPS works with constant index.
6164     if (isa<ConstantSDNode>(Op.getOperand(1)))
6165       return Op;
6166   }
6167   return SDValue();
6168 }
6169
6170
6171 SDValue
6172 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6173                                            SelectionDAG &DAG) const {
6174   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6175     return SDValue();
6176
6177   SDValue Vec = Op.getOperand(0);
6178   EVT VecVT = Vec.getValueType();
6179
6180   // If this is a 256-bit vector result, first extract the 128-bit
6181   // vector and then extract from the 128-bit vector.
6182   if (VecVT.getSizeInBits() > 128) {
6183     DebugLoc dl = Op.getNode()->getDebugLoc();
6184     unsigned NumElems = VecVT.getVectorNumElements();
6185     SDValue Idx = Op.getOperand(1);
6186
6187     if (!isa<ConstantSDNode>(Idx))
6188       return SDValue();
6189
6190     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6191     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6192
6193     // Get the 128-bit vector.
6194     bool Upper = IdxVal >= ExtractNumElems;
6195     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6196
6197     // Extract from it.
6198     SDValue ScaledIdx = Idx;
6199     if (Upper)
6200       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6201                               DAG.getConstant(ExtractNumElems,
6202                                               Idx.getValueType()));
6203     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6204                        ScaledIdx);
6205   }
6206
6207   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6208
6209   if (Subtarget->hasSSE41()) {
6210     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6211     if (Res.getNode())
6212       return Res;
6213   }
6214
6215   EVT VT = Op.getValueType();
6216   DebugLoc dl = Op.getDebugLoc();
6217   // TODO: handle v16i8.
6218   if (VT.getSizeInBits() == 16) {
6219     SDValue Vec = Op.getOperand(0);
6220     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6221     if (Idx == 0)
6222       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6223                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6224                                      DAG.getNode(ISD::BITCAST, dl,
6225                                                  MVT::v4i32, Vec),
6226                                      Op.getOperand(1)));
6227     // Transform it so it match pextrw which produces a 32-bit result.
6228     EVT EltVT = MVT::i32;
6229     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6230                                     Op.getOperand(0), Op.getOperand(1));
6231     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6232                                     DAG.getValueType(VT));
6233     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6234   } else if (VT.getSizeInBits() == 32) {
6235     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6236     if (Idx == 0)
6237       return Op;
6238
6239     // SHUFPS the element to the lowest double word, then movss.
6240     int Mask[4] = { Idx, -1, -1, -1 };
6241     EVT VVT = Op.getOperand(0).getValueType();
6242     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6243                                        DAG.getUNDEF(VVT), Mask);
6244     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6245                        DAG.getIntPtrConstant(0));
6246   } else if (VT.getSizeInBits() == 64) {
6247     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6248     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6249     //        to match extract_elt for f64.
6250     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6251     if (Idx == 0)
6252       return Op;
6253
6254     // UNPCKHPD the element to the lowest double word, then movsd.
6255     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6256     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6257     int Mask[2] = { 1, -1 };
6258     EVT VVT = Op.getOperand(0).getValueType();
6259     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6260                                        DAG.getUNDEF(VVT), Mask);
6261     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6262                        DAG.getIntPtrConstant(0));
6263   }
6264
6265   return SDValue();
6266 }
6267
6268 SDValue
6269 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6270                                                SelectionDAG &DAG) const {
6271   EVT VT = Op.getValueType();
6272   EVT EltVT = VT.getVectorElementType();
6273   DebugLoc dl = Op.getDebugLoc();
6274
6275   SDValue N0 = Op.getOperand(0);
6276   SDValue N1 = Op.getOperand(1);
6277   SDValue N2 = Op.getOperand(2);
6278
6279   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6280       isa<ConstantSDNode>(N2)) {
6281     unsigned Opc;
6282     if (VT == MVT::v8i16)
6283       Opc = X86ISD::PINSRW;
6284     else if (VT == MVT::v16i8)
6285       Opc = X86ISD::PINSRB;
6286     else
6287       Opc = X86ISD::PINSRB;
6288
6289     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6290     // argument.
6291     if (N1.getValueType() != MVT::i32)
6292       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6293     if (N2.getValueType() != MVT::i32)
6294       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6295     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6296   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6297     // Bits [7:6] of the constant are the source select.  This will always be
6298     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6299     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6300     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6301     // Bits [5:4] of the constant are the destination select.  This is the
6302     //  value of the incoming immediate.
6303     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6304     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6305     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6306     // Create this as a scalar to vector..
6307     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6308     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6309   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6310     // PINSR* works with constant index.
6311     return Op;
6312   }
6313   return SDValue();
6314 }
6315
6316 SDValue
6317 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6318   EVT VT = Op.getValueType();
6319   EVT EltVT = VT.getVectorElementType();
6320
6321   DebugLoc dl = Op.getDebugLoc();
6322   SDValue N0 = Op.getOperand(0);
6323   SDValue N1 = Op.getOperand(1);
6324   SDValue N2 = Op.getOperand(2);
6325
6326   // If this is a 256-bit vector result, first insert into a 128-bit
6327   // vector and then insert into the 256-bit vector.
6328   if (VT.getSizeInBits() > 128) {
6329     if (!isa<ConstantSDNode>(N2))
6330       return SDValue();
6331
6332     // Get the 128-bit vector.
6333     unsigned NumElems = VT.getVectorNumElements();
6334     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6335     bool Upper = IdxVal >= NumElems / 2;
6336
6337     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6338
6339     // Insert into it.
6340     SDValue ScaledN2 = N2;
6341     if (Upper)
6342       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6343                              DAG.getConstant(NumElems /
6344                                              (VT.getSizeInBits() / 128),
6345                                              N2.getValueType()));
6346     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6347                      N1, ScaledN2);
6348
6349     // Insert the 128-bit vector
6350     // FIXME: Why UNDEF?
6351     return Insert128BitVector(N0, Op, N2, DAG, dl);
6352   }
6353
6354   if (Subtarget->hasSSE41())
6355     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6356
6357   if (EltVT == MVT::i8)
6358     return SDValue();
6359
6360   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6361     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6362     // as its second argument.
6363     if (N1.getValueType() != MVT::i32)
6364       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6365     if (N2.getValueType() != MVT::i32)
6366       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6367     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6368   }
6369   return SDValue();
6370 }
6371
6372 SDValue
6373 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6374   LLVMContext *Context = DAG.getContext();
6375   DebugLoc dl = Op.getDebugLoc();
6376   EVT OpVT = Op.getValueType();
6377
6378   // If this is a 256-bit vector result, first insert into a 128-bit
6379   // vector and then insert into the 256-bit vector.
6380   if (OpVT.getSizeInBits() > 128) {
6381     // Insert into a 128-bit vector.
6382     EVT VT128 = EVT::getVectorVT(*Context,
6383                                  OpVT.getVectorElementType(),
6384                                  OpVT.getVectorNumElements() / 2);
6385
6386     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6387
6388     // Insert the 128-bit vector.
6389     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6390                               DAG.getConstant(0, MVT::i32),
6391                               DAG, dl);
6392   }
6393
6394   if (Op.getValueType() == MVT::v1i64 &&
6395       Op.getOperand(0).getValueType() == MVT::i64)
6396     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6397
6398   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6399   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6400          "Expected an SSE type!");
6401   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6402                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6403 }
6404
6405 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6406 // a simple subregister reference or explicit instructions to grab
6407 // upper bits of a vector.
6408 SDValue
6409 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6410   if (Subtarget->hasAVX()) {
6411     DebugLoc dl = Op.getNode()->getDebugLoc();
6412     SDValue Vec = Op.getNode()->getOperand(0);
6413     SDValue Idx = Op.getNode()->getOperand(1);
6414
6415     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6416         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6417         return Extract128BitVector(Vec, Idx, DAG, dl);
6418     }
6419   }
6420   return SDValue();
6421 }
6422
6423 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6424 // simple superregister reference or explicit instructions to insert
6425 // the upper bits of a vector.
6426 SDValue
6427 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6428   if (Subtarget->hasAVX()) {
6429     DebugLoc dl = Op.getNode()->getDebugLoc();
6430     SDValue Vec = Op.getNode()->getOperand(0);
6431     SDValue SubVec = Op.getNode()->getOperand(1);
6432     SDValue Idx = Op.getNode()->getOperand(2);
6433
6434     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6435         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6436       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6437     }
6438   }
6439   return SDValue();
6440 }
6441
6442 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6443 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6444 // one of the above mentioned nodes. It has to be wrapped because otherwise
6445 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6446 // be used to form addressing mode. These wrapped nodes will be selected
6447 // into MOV32ri.
6448 SDValue
6449 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6450   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6451
6452   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6453   // global base reg.
6454   unsigned char OpFlag = 0;
6455   unsigned WrapperKind = X86ISD::Wrapper;
6456   CodeModel::Model M = getTargetMachine().getCodeModel();
6457
6458   if (Subtarget->isPICStyleRIPRel() &&
6459       (M == CodeModel::Small || M == CodeModel::Kernel))
6460     WrapperKind = X86ISD::WrapperRIP;
6461   else if (Subtarget->isPICStyleGOT())
6462     OpFlag = X86II::MO_GOTOFF;
6463   else if (Subtarget->isPICStyleStubPIC())
6464     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6465
6466   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6467                                              CP->getAlignment(),
6468                                              CP->getOffset(), OpFlag);
6469   DebugLoc DL = CP->getDebugLoc();
6470   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6471   // With PIC, the address is actually $g + Offset.
6472   if (OpFlag) {
6473     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6474                          DAG.getNode(X86ISD::GlobalBaseReg,
6475                                      DebugLoc(), getPointerTy()),
6476                          Result);
6477   }
6478
6479   return Result;
6480 }
6481
6482 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6483   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6484
6485   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6486   // global base reg.
6487   unsigned char OpFlag = 0;
6488   unsigned WrapperKind = X86ISD::Wrapper;
6489   CodeModel::Model M = getTargetMachine().getCodeModel();
6490
6491   if (Subtarget->isPICStyleRIPRel() &&
6492       (M == CodeModel::Small || M == CodeModel::Kernel))
6493     WrapperKind = X86ISD::WrapperRIP;
6494   else if (Subtarget->isPICStyleGOT())
6495     OpFlag = X86II::MO_GOTOFF;
6496   else if (Subtarget->isPICStyleStubPIC())
6497     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6498
6499   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6500                                           OpFlag);
6501   DebugLoc DL = JT->getDebugLoc();
6502   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6503
6504   // With PIC, the address is actually $g + Offset.
6505   if (OpFlag)
6506     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6507                          DAG.getNode(X86ISD::GlobalBaseReg,
6508                                      DebugLoc(), getPointerTy()),
6509                          Result);
6510
6511   return Result;
6512 }
6513
6514 SDValue
6515 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6516   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6517
6518   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6519   // global base reg.
6520   unsigned char OpFlag = 0;
6521   unsigned WrapperKind = X86ISD::Wrapper;
6522   CodeModel::Model M = getTargetMachine().getCodeModel();
6523
6524   if (Subtarget->isPICStyleRIPRel() &&
6525       (M == CodeModel::Small || M == CodeModel::Kernel))
6526     WrapperKind = X86ISD::WrapperRIP;
6527   else if (Subtarget->isPICStyleGOT())
6528     OpFlag = X86II::MO_GOTOFF;
6529   else if (Subtarget->isPICStyleStubPIC())
6530     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6531
6532   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6533
6534   DebugLoc DL = Op.getDebugLoc();
6535   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6536
6537
6538   // With PIC, the address is actually $g + Offset.
6539   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6540       !Subtarget->is64Bit()) {
6541     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6542                          DAG.getNode(X86ISD::GlobalBaseReg,
6543                                      DebugLoc(), getPointerTy()),
6544                          Result);
6545   }
6546
6547   return Result;
6548 }
6549
6550 SDValue
6551 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6552   // Create the TargetBlockAddressAddress node.
6553   unsigned char OpFlags =
6554     Subtarget->ClassifyBlockAddressReference();
6555   CodeModel::Model M = getTargetMachine().getCodeModel();
6556   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6557   DebugLoc dl = Op.getDebugLoc();
6558   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6559                                        /*isTarget=*/true, OpFlags);
6560
6561   if (Subtarget->isPICStyleRIPRel() &&
6562       (M == CodeModel::Small || M == CodeModel::Kernel))
6563     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6564   else
6565     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6566
6567   // With PIC, the address is actually $g + Offset.
6568   if (isGlobalRelativeToPICBase(OpFlags)) {
6569     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6570                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6571                          Result);
6572   }
6573
6574   return Result;
6575 }
6576
6577 SDValue
6578 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6579                                       int64_t Offset,
6580                                       SelectionDAG &DAG) const {
6581   // Create the TargetGlobalAddress node, folding in the constant
6582   // offset if it is legal.
6583   unsigned char OpFlags =
6584     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6585   CodeModel::Model M = getTargetMachine().getCodeModel();
6586   SDValue Result;
6587   if (OpFlags == X86II::MO_NO_FLAG &&
6588       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6589     // A direct static reference to a global.
6590     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6591     Offset = 0;
6592   } else {
6593     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6594   }
6595
6596   if (Subtarget->isPICStyleRIPRel() &&
6597       (M == CodeModel::Small || M == CodeModel::Kernel))
6598     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6599   else
6600     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6601
6602   // With PIC, the address is actually $g + Offset.
6603   if (isGlobalRelativeToPICBase(OpFlags)) {
6604     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6605                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6606                          Result);
6607   }
6608
6609   // For globals that require a load from a stub to get the address, emit the
6610   // load.
6611   if (isGlobalStubReference(OpFlags))
6612     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6613                          MachinePointerInfo::getGOT(), false, false, 0);
6614
6615   // If there was a non-zero offset that we didn't fold, create an explicit
6616   // addition for it.
6617   if (Offset != 0)
6618     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6619                          DAG.getConstant(Offset, getPointerTy()));
6620
6621   return Result;
6622 }
6623
6624 SDValue
6625 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6626   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6627   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6628   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6629 }
6630
6631 static SDValue
6632 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6633            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6634            unsigned char OperandFlags) {
6635   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6636   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6637   DebugLoc dl = GA->getDebugLoc();
6638   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6639                                            GA->getValueType(0),
6640                                            GA->getOffset(),
6641                                            OperandFlags);
6642   if (InFlag) {
6643     SDValue Ops[] = { Chain,  TGA, *InFlag };
6644     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6645   } else {
6646     SDValue Ops[]  = { Chain, TGA };
6647     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6648   }
6649
6650   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6651   MFI->setAdjustsStack(true);
6652
6653   SDValue Flag = Chain.getValue(1);
6654   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6655 }
6656
6657 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6658 static SDValue
6659 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6660                                 const EVT PtrVT) {
6661   SDValue InFlag;
6662   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6663   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6664                                      DAG.getNode(X86ISD::GlobalBaseReg,
6665                                                  DebugLoc(), PtrVT), InFlag);
6666   InFlag = Chain.getValue(1);
6667
6668   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6669 }
6670
6671 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6672 static SDValue
6673 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6674                                 const EVT PtrVT) {
6675   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6676                     X86::RAX, X86II::MO_TLSGD);
6677 }
6678
6679 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6680 // "local exec" model.
6681 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6682                                    const EVT PtrVT, TLSModel::Model model,
6683                                    bool is64Bit) {
6684   DebugLoc dl = GA->getDebugLoc();
6685
6686   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6687   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6688                                                          is64Bit ? 257 : 256));
6689
6690   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6691                                       DAG.getIntPtrConstant(0),
6692                                       MachinePointerInfo(Ptr), false, false, 0);
6693
6694   unsigned char OperandFlags = 0;
6695   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6696   // initialexec.
6697   unsigned WrapperKind = X86ISD::Wrapper;
6698   if (model == TLSModel::LocalExec) {
6699     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6700   } else if (is64Bit) {
6701     assert(model == TLSModel::InitialExec);
6702     OperandFlags = X86II::MO_GOTTPOFF;
6703     WrapperKind = X86ISD::WrapperRIP;
6704   } else {
6705     assert(model == TLSModel::InitialExec);
6706     OperandFlags = X86II::MO_INDNTPOFF;
6707   }
6708
6709   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6710   // exec)
6711   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6712                                            GA->getValueType(0),
6713                                            GA->getOffset(), OperandFlags);
6714   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6715
6716   if (model == TLSModel::InitialExec)
6717     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6718                          MachinePointerInfo::getGOT(), false, false, 0);
6719
6720   // The address of the thread local variable is the add of the thread
6721   // pointer with the offset of the variable.
6722   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6723 }
6724
6725 SDValue
6726 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6727
6728   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6729   const GlobalValue *GV = GA->getGlobal();
6730
6731   if (Subtarget->isTargetELF()) {
6732     // TODO: implement the "local dynamic" model
6733     // TODO: implement the "initial exec"model for pic executables
6734
6735     // If GV is an alias then use the aliasee for determining
6736     // thread-localness.
6737     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6738       GV = GA->resolveAliasedGlobal(false);
6739
6740     TLSModel::Model model
6741       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6742
6743     switch (model) {
6744       case TLSModel::GeneralDynamic:
6745       case TLSModel::LocalDynamic: // not implemented
6746         if (Subtarget->is64Bit())
6747           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6748         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6749
6750       case TLSModel::InitialExec:
6751       case TLSModel::LocalExec:
6752         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6753                                    Subtarget->is64Bit());
6754     }
6755   } else if (Subtarget->isTargetDarwin()) {
6756     // Darwin only has one model of TLS.  Lower to that.
6757     unsigned char OpFlag = 0;
6758     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6759                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6760
6761     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6762     // global base reg.
6763     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6764                   !Subtarget->is64Bit();
6765     if (PIC32)
6766       OpFlag = X86II::MO_TLVP_PIC_BASE;
6767     else
6768       OpFlag = X86II::MO_TLVP;
6769     DebugLoc DL = Op.getDebugLoc();
6770     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6771                                                 GA->getValueType(0),
6772                                                 GA->getOffset(), OpFlag);
6773     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6774
6775     // With PIC32, the address is actually $g + Offset.
6776     if (PIC32)
6777       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6778                            DAG.getNode(X86ISD::GlobalBaseReg,
6779                                        DebugLoc(), getPointerTy()),
6780                            Offset);
6781
6782     // Lowering the machine isd will make sure everything is in the right
6783     // location.
6784     SDValue Chain = DAG.getEntryNode();
6785     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6786     SDValue Args[] = { Chain, Offset };
6787     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6788
6789     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6790     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6791     MFI->setAdjustsStack(true);
6792
6793     // And our return value (tls address) is in the standard call return value
6794     // location.
6795     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6796     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6797   }
6798
6799   assert(false &&
6800          "TLS not implemented for this target.");
6801
6802   llvm_unreachable("Unreachable");
6803   return SDValue();
6804 }
6805
6806
6807 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6808 /// take a 2 x i32 value to shift plus a shift amount.
6809 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6810   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6811   EVT VT = Op.getValueType();
6812   unsigned VTBits = VT.getSizeInBits();
6813   DebugLoc dl = Op.getDebugLoc();
6814   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6815   SDValue ShOpLo = Op.getOperand(0);
6816   SDValue ShOpHi = Op.getOperand(1);
6817   SDValue ShAmt  = Op.getOperand(2);
6818   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6819                                      DAG.getConstant(VTBits - 1, MVT::i8))
6820                        : DAG.getConstant(0, VT);
6821
6822   SDValue Tmp2, Tmp3;
6823   if (Op.getOpcode() == ISD::SHL_PARTS) {
6824     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6825     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6826   } else {
6827     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6828     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6829   }
6830
6831   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6832                                 DAG.getConstant(VTBits, MVT::i8));
6833   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6834                              AndNode, DAG.getConstant(0, MVT::i8));
6835
6836   SDValue Hi, Lo;
6837   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6838   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6839   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6840
6841   if (Op.getOpcode() == ISD::SHL_PARTS) {
6842     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6843     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6844   } else {
6845     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6846     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6847   }
6848
6849   SDValue Ops[2] = { Lo, Hi };
6850   return DAG.getMergeValues(Ops, 2, dl);
6851 }
6852
6853 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6854                                            SelectionDAG &DAG) const {
6855   EVT SrcVT = Op.getOperand(0).getValueType();
6856
6857   if (SrcVT.isVector())
6858     return SDValue();
6859
6860   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6861          "Unknown SINT_TO_FP to lower!");
6862
6863   // These are really Legal; return the operand so the caller accepts it as
6864   // Legal.
6865   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6866     return Op;
6867   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6868       Subtarget->is64Bit()) {
6869     return Op;
6870   }
6871
6872   DebugLoc dl = Op.getDebugLoc();
6873   unsigned Size = SrcVT.getSizeInBits()/8;
6874   MachineFunction &MF = DAG.getMachineFunction();
6875   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6876   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6877   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6878                                StackSlot,
6879                                MachinePointerInfo::getFixedStack(SSFI),
6880                                false, false, 0);
6881   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6882 }
6883
6884 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6885                                      SDValue StackSlot,
6886                                      SelectionDAG &DAG) const {
6887   // Build the FILD
6888   DebugLoc DL = Op.getDebugLoc();
6889   SDVTList Tys;
6890   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6891   if (useSSE)
6892     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6893   else
6894     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6895
6896   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6897
6898   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6899   MachineMemOperand *MMO;
6900   if (FI) {
6901     int SSFI = FI->getIndex();
6902     MMO =
6903       DAG.getMachineFunction()
6904       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6905                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6906   } else {
6907     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6908     StackSlot = StackSlot.getOperand(1);
6909   }
6910   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6911   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6912                                            X86ISD::FILD, DL,
6913                                            Tys, Ops, array_lengthof(Ops),
6914                                            SrcVT, MMO);
6915
6916   if (useSSE) {
6917     Chain = Result.getValue(1);
6918     SDValue InFlag = Result.getValue(2);
6919
6920     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6921     // shouldn't be necessary except that RFP cannot be live across
6922     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6923     MachineFunction &MF = DAG.getMachineFunction();
6924     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6925     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6926     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6927     Tys = DAG.getVTList(MVT::Other);
6928     SDValue Ops[] = {
6929       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6930     };
6931     MachineMemOperand *MMO =
6932       DAG.getMachineFunction()
6933       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6934                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6935
6936     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6937                                     Ops, array_lengthof(Ops),
6938                                     Op.getValueType(), MMO);
6939     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6940                          MachinePointerInfo::getFixedStack(SSFI),
6941                          false, false, 0);
6942   }
6943
6944   return Result;
6945 }
6946
6947 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6948 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6949                                                SelectionDAG &DAG) const {
6950   // This algorithm is not obvious. Here it is in C code, more or less:
6951   /*
6952     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6953       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6954       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6955
6956       // Copy ints to xmm registers.
6957       __m128i xh = _mm_cvtsi32_si128( hi );
6958       __m128i xl = _mm_cvtsi32_si128( lo );
6959
6960       // Combine into low half of a single xmm register.
6961       __m128i x = _mm_unpacklo_epi32( xh, xl );
6962       __m128d d;
6963       double sd;
6964
6965       // Merge in appropriate exponents to give the integer bits the right
6966       // magnitude.
6967       x = _mm_unpacklo_epi32( x, exp );
6968
6969       // Subtract away the biases to deal with the IEEE-754 double precision
6970       // implicit 1.
6971       d = _mm_sub_pd( (__m128d) x, bias );
6972
6973       // All conversions up to here are exact. The correctly rounded result is
6974       // calculated using the current rounding mode using the following
6975       // horizontal add.
6976       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6977       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6978                                 // store doesn't really need to be here (except
6979                                 // maybe to zero the other double)
6980       return sd;
6981     }
6982   */
6983
6984   DebugLoc dl = Op.getDebugLoc();
6985   LLVMContext *Context = DAG.getContext();
6986
6987   // Build some magic constants.
6988   std::vector<Constant*> CV0;
6989   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6990   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6991   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6992   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6993   Constant *C0 = ConstantVector::get(CV0);
6994   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6995
6996   std::vector<Constant*> CV1;
6997   CV1.push_back(
6998     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6999   CV1.push_back(
7000     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7001   Constant *C1 = ConstantVector::get(CV1);
7002   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7003
7004   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7005                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7006                                         Op.getOperand(0),
7007                                         DAG.getIntPtrConstant(1)));
7008   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7009                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7010                                         Op.getOperand(0),
7011                                         DAG.getIntPtrConstant(0)));
7012   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7013   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7014                               MachinePointerInfo::getConstantPool(),
7015                               false, false, 16);
7016   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7017   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7018   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7019                               MachinePointerInfo::getConstantPool(),
7020                               false, false, 16);
7021   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7022
7023   // Add the halves; easiest way is to swap them into another reg first.
7024   int ShufMask[2] = { 1, -1 };
7025   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7026                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7027   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7028   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7029                      DAG.getIntPtrConstant(0));
7030 }
7031
7032 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7033 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7034                                                SelectionDAG &DAG) const {
7035   DebugLoc dl = Op.getDebugLoc();
7036   // FP constant to bias correct the final result.
7037   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7038                                    MVT::f64);
7039
7040   // Load the 32-bit value into an XMM register.
7041   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7042                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7043                                          Op.getOperand(0),
7044                                          DAG.getIntPtrConstant(0)));
7045
7046   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7047                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7048                      DAG.getIntPtrConstant(0));
7049
7050   // Or the load with the bias.
7051   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7052                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7053                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7054                                                    MVT::v2f64, Load)),
7055                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7056                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7057                                                    MVT::v2f64, Bias)));
7058   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7059                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7060                    DAG.getIntPtrConstant(0));
7061
7062   // Subtract the bias.
7063   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7064
7065   // Handle final rounding.
7066   EVT DestVT = Op.getValueType();
7067
7068   if (DestVT.bitsLT(MVT::f64)) {
7069     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7070                        DAG.getIntPtrConstant(0));
7071   } else if (DestVT.bitsGT(MVT::f64)) {
7072     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7073   }
7074
7075   // Handle final rounding.
7076   return Sub;
7077 }
7078
7079 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7080                                            SelectionDAG &DAG) const {
7081   SDValue N0 = Op.getOperand(0);
7082   DebugLoc dl = Op.getDebugLoc();
7083
7084   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7085   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7086   // the optimization here.
7087   if (DAG.SignBitIsZero(N0))
7088     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7089
7090   EVT SrcVT = N0.getValueType();
7091   EVT DstVT = Op.getValueType();
7092   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7093     return LowerUINT_TO_FP_i64(Op, DAG);
7094   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7095     return LowerUINT_TO_FP_i32(Op, DAG);
7096
7097   // Make a 64-bit buffer, and use it to build an FILD.
7098   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7099   if (SrcVT == MVT::i32) {
7100     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7101     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7102                                      getPointerTy(), StackSlot, WordOff);
7103     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7104                                   StackSlot, MachinePointerInfo(),
7105                                   false, false, 0);
7106     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7107                                   OffsetSlot, MachinePointerInfo(),
7108                                   false, false, 0);
7109     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7110     return Fild;
7111   }
7112
7113   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7114   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7115                                 StackSlot, MachinePointerInfo(),
7116                                false, false, 0);
7117   // For i64 source, we need to add the appropriate power of 2 if the input
7118   // was negative.  This is the same as the optimization in
7119   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7120   // we must be careful to do the computation in x87 extended precision, not
7121   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7122   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7123   MachineMemOperand *MMO =
7124     DAG.getMachineFunction()
7125     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7126                           MachineMemOperand::MOLoad, 8, 8);
7127
7128   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7129   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7130   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7131                                          MVT::i64, MMO);
7132
7133   APInt FF(32, 0x5F800000ULL);
7134
7135   // Check whether the sign bit is set.
7136   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7137                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7138                                  ISD::SETLT);
7139
7140   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7141   SDValue FudgePtr = DAG.getConstantPool(
7142                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7143                                          getPointerTy());
7144
7145   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7146   SDValue Zero = DAG.getIntPtrConstant(0);
7147   SDValue Four = DAG.getIntPtrConstant(4);
7148   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7149                                Zero, Four);
7150   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7151
7152   // Load the value out, extending it from f32 to f80.
7153   // FIXME: Avoid the extend by constructing the right constant pool?
7154   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7155                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7156                                  MVT::f32, false, false, 4);
7157   // Extend everything to 80 bits to force it to be done on x87.
7158   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7159   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7160 }
7161
7162 std::pair<SDValue,SDValue> X86TargetLowering::
7163 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7164   DebugLoc DL = Op.getDebugLoc();
7165
7166   EVT DstTy = Op.getValueType();
7167
7168   if (!IsSigned) {
7169     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7170     DstTy = MVT::i64;
7171   }
7172
7173   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7174          DstTy.getSimpleVT() >= MVT::i16 &&
7175          "Unknown FP_TO_SINT to lower!");
7176
7177   // These are really Legal.
7178   if (DstTy == MVT::i32 &&
7179       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7180     return std::make_pair(SDValue(), SDValue());
7181   if (Subtarget->is64Bit() &&
7182       DstTy == MVT::i64 &&
7183       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7184     return std::make_pair(SDValue(), SDValue());
7185
7186   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7187   // stack slot.
7188   MachineFunction &MF = DAG.getMachineFunction();
7189   unsigned MemSize = DstTy.getSizeInBits()/8;
7190   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7191   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7192
7193
7194
7195   unsigned Opc;
7196   switch (DstTy.getSimpleVT().SimpleTy) {
7197   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7198   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7199   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7200   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7201   }
7202
7203   SDValue Chain = DAG.getEntryNode();
7204   SDValue Value = Op.getOperand(0);
7205   EVT TheVT = Op.getOperand(0).getValueType();
7206   if (isScalarFPTypeInSSEReg(TheVT)) {
7207     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7208     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7209                          MachinePointerInfo::getFixedStack(SSFI),
7210                          false, false, 0);
7211     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7212     SDValue Ops[] = {
7213       Chain, StackSlot, DAG.getValueType(TheVT)
7214     };
7215
7216     MachineMemOperand *MMO =
7217       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7218                               MachineMemOperand::MOLoad, MemSize, MemSize);
7219     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7220                                     DstTy, MMO);
7221     Chain = Value.getValue(1);
7222     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7223     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7224   }
7225
7226   MachineMemOperand *MMO =
7227     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7228                             MachineMemOperand::MOStore, MemSize, MemSize);
7229
7230   // Build the FP_TO_INT*_IN_MEM
7231   SDValue Ops[] = { Chain, Value, StackSlot };
7232   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7233                                          Ops, 3, DstTy, MMO);
7234
7235   return std::make_pair(FIST, StackSlot);
7236 }
7237
7238 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7239                                            SelectionDAG &DAG) const {
7240   if (Op.getValueType().isVector())
7241     return SDValue();
7242
7243   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7244   SDValue FIST = Vals.first, StackSlot = Vals.second;
7245   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7246   if (FIST.getNode() == 0) return Op;
7247
7248   // Load the result.
7249   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7250                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7251 }
7252
7253 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7254                                            SelectionDAG &DAG) const {
7255   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7256   SDValue FIST = Vals.first, StackSlot = Vals.second;
7257   assert(FIST.getNode() && "Unexpected failure");
7258
7259   // Load the result.
7260   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7261                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7262 }
7263
7264 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7265                                      SelectionDAG &DAG) const {
7266   LLVMContext *Context = DAG.getContext();
7267   DebugLoc dl = Op.getDebugLoc();
7268   EVT VT = Op.getValueType();
7269   EVT EltVT = VT;
7270   if (VT.isVector())
7271     EltVT = VT.getVectorElementType();
7272   std::vector<Constant*> CV;
7273   if (EltVT == MVT::f64) {
7274     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7275     CV.push_back(C);
7276     CV.push_back(C);
7277   } else {
7278     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7279     CV.push_back(C);
7280     CV.push_back(C);
7281     CV.push_back(C);
7282     CV.push_back(C);
7283   }
7284   Constant *C = ConstantVector::get(CV);
7285   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7286   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7287                              MachinePointerInfo::getConstantPool(),
7288                              false, false, 16);
7289   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7290 }
7291
7292 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7293   LLVMContext *Context = DAG.getContext();
7294   DebugLoc dl = Op.getDebugLoc();
7295   EVT VT = Op.getValueType();
7296   EVT EltVT = VT;
7297   if (VT.isVector())
7298     EltVT = VT.getVectorElementType();
7299   std::vector<Constant*> CV;
7300   if (EltVT == MVT::f64) {
7301     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7302     CV.push_back(C);
7303     CV.push_back(C);
7304   } else {
7305     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7306     CV.push_back(C);
7307     CV.push_back(C);
7308     CV.push_back(C);
7309     CV.push_back(C);
7310   }
7311   Constant *C = ConstantVector::get(CV);
7312   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7313   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7314                              MachinePointerInfo::getConstantPool(),
7315                              false, false, 16);
7316   if (VT.isVector()) {
7317     return DAG.getNode(ISD::BITCAST, dl, VT,
7318                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7319                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7320                                 Op.getOperand(0)),
7321                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7322   } else {
7323     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7324   }
7325 }
7326
7327 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7328   LLVMContext *Context = DAG.getContext();
7329   SDValue Op0 = Op.getOperand(0);
7330   SDValue Op1 = Op.getOperand(1);
7331   DebugLoc dl = Op.getDebugLoc();
7332   EVT VT = Op.getValueType();
7333   EVT SrcVT = Op1.getValueType();
7334
7335   // If second operand is smaller, extend it first.
7336   if (SrcVT.bitsLT(VT)) {
7337     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7338     SrcVT = VT;
7339   }
7340   // And if it is bigger, shrink it first.
7341   if (SrcVT.bitsGT(VT)) {
7342     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7343     SrcVT = VT;
7344   }
7345
7346   // At this point the operands and the result should have the same
7347   // type, and that won't be f80 since that is not custom lowered.
7348
7349   // First get the sign bit of second operand.
7350   std::vector<Constant*> CV;
7351   if (SrcVT == MVT::f64) {
7352     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7353     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7354   } else {
7355     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7356     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7357     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7358     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7359   }
7360   Constant *C = ConstantVector::get(CV);
7361   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7362   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7363                               MachinePointerInfo::getConstantPool(),
7364                               false, false, 16);
7365   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7366
7367   // Shift sign bit right or left if the two operands have different types.
7368   if (SrcVT.bitsGT(VT)) {
7369     // Op0 is MVT::f32, Op1 is MVT::f64.
7370     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7371     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7372                           DAG.getConstant(32, MVT::i32));
7373     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7374     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7375                           DAG.getIntPtrConstant(0));
7376   }
7377
7378   // Clear first operand sign bit.
7379   CV.clear();
7380   if (VT == MVT::f64) {
7381     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7382     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7383   } else {
7384     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7385     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7386     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7387     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7388   }
7389   C = ConstantVector::get(CV);
7390   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7391   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7392                               MachinePointerInfo::getConstantPool(),
7393                               false, false, 16);
7394   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7395
7396   // Or the value with the sign bit.
7397   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7398 }
7399
7400 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7401   SDValue N0 = Op.getOperand(0);
7402   DebugLoc dl = Op.getDebugLoc();
7403   EVT VT = Op.getValueType();
7404
7405   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7406   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7407                                   DAG.getConstant(1, VT));
7408   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7409 }
7410
7411 /// Emit nodes that will be selected as "test Op0,Op0", or something
7412 /// equivalent.
7413 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7414                                     SelectionDAG &DAG) const {
7415   DebugLoc dl = Op.getDebugLoc();
7416
7417   // CF and OF aren't always set the way we want. Determine which
7418   // of these we need.
7419   bool NeedCF = false;
7420   bool NeedOF = false;
7421   switch (X86CC) {
7422   default: break;
7423   case X86::COND_A: case X86::COND_AE:
7424   case X86::COND_B: case X86::COND_BE:
7425     NeedCF = true;
7426     break;
7427   case X86::COND_G: case X86::COND_GE:
7428   case X86::COND_L: case X86::COND_LE:
7429   case X86::COND_O: case X86::COND_NO:
7430     NeedOF = true;
7431     break;
7432   }
7433
7434   // See if we can use the EFLAGS value from the operand instead of
7435   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7436   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7437   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7438     // Emit a CMP with 0, which is the TEST pattern.
7439     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7440                        DAG.getConstant(0, Op.getValueType()));
7441
7442   unsigned Opcode = 0;
7443   unsigned NumOperands = 0;
7444   switch (Op.getNode()->getOpcode()) {
7445   case ISD::ADD:
7446     // Due to an isel shortcoming, be conservative if this add is likely to be
7447     // selected as part of a load-modify-store instruction. When the root node
7448     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7449     // uses of other nodes in the match, such as the ADD in this case. This
7450     // leads to the ADD being left around and reselected, with the result being
7451     // two adds in the output.  Alas, even if none our users are stores, that
7452     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7453     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7454     // climbing the DAG back to the root, and it doesn't seem to be worth the
7455     // effort.
7456     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7457            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7458       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7459         goto default_case;
7460
7461     if (ConstantSDNode *C =
7462         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7463       // An add of one will be selected as an INC.
7464       if (C->getAPIntValue() == 1) {
7465         Opcode = X86ISD::INC;
7466         NumOperands = 1;
7467         break;
7468       }
7469
7470       // An add of negative one (subtract of one) will be selected as a DEC.
7471       if (C->getAPIntValue().isAllOnesValue()) {
7472         Opcode = X86ISD::DEC;
7473         NumOperands = 1;
7474         break;
7475       }
7476     }
7477
7478     // Otherwise use a regular EFLAGS-setting add.
7479     Opcode = X86ISD::ADD;
7480     NumOperands = 2;
7481     break;
7482   case ISD::AND: {
7483     // If the primary and result isn't used, don't bother using X86ISD::AND,
7484     // because a TEST instruction will be better.
7485     bool NonFlagUse = false;
7486     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7487            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7488       SDNode *User = *UI;
7489       unsigned UOpNo = UI.getOperandNo();
7490       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7491         // Look pass truncate.
7492         UOpNo = User->use_begin().getOperandNo();
7493         User = *User->use_begin();
7494       }
7495
7496       if (User->getOpcode() != ISD::BRCOND &&
7497           User->getOpcode() != ISD::SETCC &&
7498           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7499         NonFlagUse = true;
7500         break;
7501       }
7502     }
7503
7504     if (!NonFlagUse)
7505       break;
7506   }
7507     // FALL THROUGH
7508   case ISD::SUB:
7509   case ISD::OR:
7510   case ISD::XOR:
7511     // Due to the ISEL shortcoming noted above, be conservative if this op is
7512     // likely to be selected as part of a load-modify-store instruction.
7513     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7514            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7515       if (UI->getOpcode() == ISD::STORE)
7516         goto default_case;
7517
7518     // Otherwise use a regular EFLAGS-setting instruction.
7519     switch (Op.getNode()->getOpcode()) {
7520     default: llvm_unreachable("unexpected operator!");
7521     case ISD::SUB: Opcode = X86ISD::SUB; break;
7522     case ISD::OR:  Opcode = X86ISD::OR;  break;
7523     case ISD::XOR: Opcode = X86ISD::XOR; break;
7524     case ISD::AND: Opcode = X86ISD::AND; break;
7525     }
7526
7527     NumOperands = 2;
7528     break;
7529   case X86ISD::ADD:
7530   case X86ISD::SUB:
7531   case X86ISD::INC:
7532   case X86ISD::DEC:
7533   case X86ISD::OR:
7534   case X86ISD::XOR:
7535   case X86ISD::AND:
7536     return SDValue(Op.getNode(), 1);
7537   default:
7538   default_case:
7539     break;
7540   }
7541
7542   if (Opcode == 0)
7543     // Emit a CMP with 0, which is the TEST pattern.
7544     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7545                        DAG.getConstant(0, Op.getValueType()));
7546
7547   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7548   SmallVector<SDValue, 4> Ops;
7549   for (unsigned i = 0; i != NumOperands; ++i)
7550     Ops.push_back(Op.getOperand(i));
7551
7552   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7553   DAG.ReplaceAllUsesWith(Op, New);
7554   return SDValue(New.getNode(), 1);
7555 }
7556
7557 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7558 /// equivalent.
7559 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7560                                    SelectionDAG &DAG) const {
7561   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7562     if (C->getAPIntValue() == 0)
7563       return EmitTest(Op0, X86CC, DAG);
7564
7565   DebugLoc dl = Op0.getDebugLoc();
7566   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7567 }
7568
7569 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7570 /// if it's possible.
7571 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7572                                      DebugLoc dl, SelectionDAG &DAG) const {
7573   SDValue Op0 = And.getOperand(0);
7574   SDValue Op1 = And.getOperand(1);
7575   if (Op0.getOpcode() == ISD::TRUNCATE)
7576     Op0 = Op0.getOperand(0);
7577   if (Op1.getOpcode() == ISD::TRUNCATE)
7578     Op1 = Op1.getOperand(0);
7579
7580   SDValue LHS, RHS;
7581   if (Op1.getOpcode() == ISD::SHL)
7582     std::swap(Op0, Op1);
7583   if (Op0.getOpcode() == ISD::SHL) {
7584     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7585       if (And00C->getZExtValue() == 1) {
7586         // If we looked past a truncate, check that it's only truncating away
7587         // known zeros.
7588         unsigned BitWidth = Op0.getValueSizeInBits();
7589         unsigned AndBitWidth = And.getValueSizeInBits();
7590         if (BitWidth > AndBitWidth) {
7591           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7592           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7593           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7594             return SDValue();
7595         }
7596         LHS = Op1;
7597         RHS = Op0.getOperand(1);
7598       }
7599   } else if (Op1.getOpcode() == ISD::Constant) {
7600     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7601     SDValue AndLHS = Op0;
7602     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7603       LHS = AndLHS.getOperand(0);
7604       RHS = AndLHS.getOperand(1);
7605     }
7606   }
7607
7608   if (LHS.getNode()) {
7609     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7610     // instruction.  Since the shift amount is in-range-or-undefined, we know
7611     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7612     // the encoding for the i16 version is larger than the i32 version.
7613     // Also promote i16 to i32 for performance / code size reason.
7614     if (LHS.getValueType() == MVT::i8 ||
7615         LHS.getValueType() == MVT::i16)
7616       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7617
7618     // If the operand types disagree, extend the shift amount to match.  Since
7619     // BT ignores high bits (like shifts) we can use anyextend.
7620     if (LHS.getValueType() != RHS.getValueType())
7621       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7622
7623     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7624     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7625     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7626                        DAG.getConstant(Cond, MVT::i8), BT);
7627   }
7628
7629   return SDValue();
7630 }
7631
7632 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7633   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7634   SDValue Op0 = Op.getOperand(0);
7635   SDValue Op1 = Op.getOperand(1);
7636   DebugLoc dl = Op.getDebugLoc();
7637   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7638
7639   // Optimize to BT if possible.
7640   // Lower (X & (1 << N)) == 0 to BT(X, N).
7641   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7642   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7643   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7644       Op1.getOpcode() == ISD::Constant &&
7645       cast<ConstantSDNode>(Op1)->isNullValue() &&
7646       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7647     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7648     if (NewSetCC.getNode())
7649       return NewSetCC;
7650   }
7651
7652   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7653   // these.
7654   if (Op1.getOpcode() == ISD::Constant &&
7655       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7656        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7657       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7658
7659     // If the input is a setcc, then reuse the input setcc or use a new one with
7660     // the inverted condition.
7661     if (Op0.getOpcode() == X86ISD::SETCC) {
7662       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7663       bool Invert = (CC == ISD::SETNE) ^
7664         cast<ConstantSDNode>(Op1)->isNullValue();
7665       if (!Invert) return Op0;
7666
7667       CCode = X86::GetOppositeBranchCondition(CCode);
7668       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7669                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7670     }
7671   }
7672
7673   bool isFP = Op1.getValueType().isFloatingPoint();
7674   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7675   if (X86CC == X86::COND_INVALID)
7676     return SDValue();
7677
7678   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7679   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7680                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7681 }
7682
7683 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7684   SDValue Cond;
7685   SDValue Op0 = Op.getOperand(0);
7686   SDValue Op1 = Op.getOperand(1);
7687   SDValue CC = Op.getOperand(2);
7688   EVT VT = Op.getValueType();
7689   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7690   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7691   DebugLoc dl = Op.getDebugLoc();
7692
7693   if (isFP) {
7694     unsigned SSECC = 8;
7695     EVT VT0 = Op0.getValueType();
7696     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7697     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7698     bool Swap = false;
7699
7700     switch (SetCCOpcode) {
7701     default: break;
7702     case ISD::SETOEQ:
7703     case ISD::SETEQ:  SSECC = 0; break;
7704     case ISD::SETOGT:
7705     case ISD::SETGT: Swap = true; // Fallthrough
7706     case ISD::SETLT:
7707     case ISD::SETOLT: SSECC = 1; break;
7708     case ISD::SETOGE:
7709     case ISD::SETGE: Swap = true; // Fallthrough
7710     case ISD::SETLE:
7711     case ISD::SETOLE: SSECC = 2; break;
7712     case ISD::SETUO:  SSECC = 3; break;
7713     case ISD::SETUNE:
7714     case ISD::SETNE:  SSECC = 4; break;
7715     case ISD::SETULE: Swap = true;
7716     case ISD::SETUGE: SSECC = 5; break;
7717     case ISD::SETULT: Swap = true;
7718     case ISD::SETUGT: SSECC = 6; break;
7719     case ISD::SETO:   SSECC = 7; break;
7720     }
7721     if (Swap)
7722       std::swap(Op0, Op1);
7723
7724     // In the two special cases we can't handle, emit two comparisons.
7725     if (SSECC == 8) {
7726       if (SetCCOpcode == ISD::SETUEQ) {
7727         SDValue UNORD, EQ;
7728         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7729         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7730         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7731       }
7732       else if (SetCCOpcode == ISD::SETONE) {
7733         SDValue ORD, NEQ;
7734         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7735         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7736         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7737       }
7738       llvm_unreachable("Illegal FP comparison");
7739     }
7740     // Handle all other FP comparisons here.
7741     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7742   }
7743
7744   // We are handling one of the integer comparisons here.  Since SSE only has
7745   // GT and EQ comparisons for integer, swapping operands and multiple
7746   // operations may be required for some comparisons.
7747   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7748   bool Swap = false, Invert = false, FlipSigns = false;
7749
7750   switch (VT.getSimpleVT().SimpleTy) {
7751   default: break;
7752   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7753   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7754   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7755   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7756   }
7757
7758   switch (SetCCOpcode) {
7759   default: break;
7760   case ISD::SETNE:  Invert = true;
7761   case ISD::SETEQ:  Opc = EQOpc; break;
7762   case ISD::SETLT:  Swap = true;
7763   case ISD::SETGT:  Opc = GTOpc; break;
7764   case ISD::SETGE:  Swap = true;
7765   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7766   case ISD::SETULT: Swap = true;
7767   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7768   case ISD::SETUGE: Swap = true;
7769   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7770   }
7771   if (Swap)
7772     std::swap(Op0, Op1);
7773
7774   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7775   // bits of the inputs before performing those operations.
7776   if (FlipSigns) {
7777     EVT EltVT = VT.getVectorElementType();
7778     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7779                                       EltVT);
7780     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7781     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7782                                     SignBits.size());
7783     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7784     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7785   }
7786
7787   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7788
7789   // If the logical-not of the result is required, perform that now.
7790   if (Invert)
7791     Result = DAG.getNOT(dl, Result, VT);
7792
7793   return Result;
7794 }
7795
7796 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7797 static bool isX86LogicalCmp(SDValue Op) {
7798   unsigned Opc = Op.getNode()->getOpcode();
7799   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7800     return true;
7801   if (Op.getResNo() == 1 &&
7802       (Opc == X86ISD::ADD ||
7803        Opc == X86ISD::SUB ||
7804        Opc == X86ISD::ADC ||
7805        Opc == X86ISD::SBB ||
7806        Opc == X86ISD::SMUL ||
7807        Opc == X86ISD::UMUL ||
7808        Opc == X86ISD::INC ||
7809        Opc == X86ISD::DEC ||
7810        Opc == X86ISD::OR ||
7811        Opc == X86ISD::XOR ||
7812        Opc == X86ISD::AND))
7813     return true;
7814
7815   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7816     return true;
7817
7818   return false;
7819 }
7820
7821 static bool isZero(SDValue V) {
7822   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7823   return C && C->isNullValue();
7824 }
7825
7826 static bool isAllOnes(SDValue V) {
7827   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7828   return C && C->isAllOnesValue();
7829 }
7830
7831 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7832   bool addTest = true;
7833   SDValue Cond  = Op.getOperand(0);
7834   SDValue Op1 = Op.getOperand(1);
7835   SDValue Op2 = Op.getOperand(2);
7836   DebugLoc DL = Op.getDebugLoc();
7837   SDValue CC;
7838
7839   if (Cond.getOpcode() == ISD::SETCC) {
7840     SDValue NewCond = LowerSETCC(Cond, DAG);
7841     if (NewCond.getNode())
7842       Cond = NewCond;
7843   }
7844
7845   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7846   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7847   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7848   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7849   if (Cond.getOpcode() == X86ISD::SETCC &&
7850       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7851       isZero(Cond.getOperand(1).getOperand(1))) {
7852     SDValue Cmp = Cond.getOperand(1);
7853
7854     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7855
7856     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7857         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7858       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7859
7860       SDValue CmpOp0 = Cmp.getOperand(0);
7861       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7862                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7863
7864       SDValue Res =   // Res = 0 or -1.
7865         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7866                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7867
7868       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7869         Res = DAG.getNOT(DL, Res, Res.getValueType());
7870
7871       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7872       if (N2C == 0 || !N2C->isNullValue())
7873         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7874       return Res;
7875     }
7876   }
7877
7878   // Look past (and (setcc_carry (cmp ...)), 1).
7879   if (Cond.getOpcode() == ISD::AND &&
7880       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7881     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7882     if (C && C->getAPIntValue() == 1)
7883       Cond = Cond.getOperand(0);
7884   }
7885
7886   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7887   // setting operand in place of the X86ISD::SETCC.
7888   if (Cond.getOpcode() == X86ISD::SETCC ||
7889       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7890     CC = Cond.getOperand(0);
7891
7892     SDValue Cmp = Cond.getOperand(1);
7893     unsigned Opc = Cmp.getOpcode();
7894     EVT VT = Op.getValueType();
7895
7896     bool IllegalFPCMov = false;
7897     if (VT.isFloatingPoint() && !VT.isVector() &&
7898         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7899       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7900
7901     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7902         Opc == X86ISD::BT) { // FIXME
7903       Cond = Cmp;
7904       addTest = false;
7905     }
7906   }
7907
7908   if (addTest) {
7909     // Look pass the truncate.
7910     if (Cond.getOpcode() == ISD::TRUNCATE)
7911       Cond = Cond.getOperand(0);
7912
7913     // We know the result of AND is compared against zero. Try to match
7914     // it to BT.
7915     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7916       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7917       if (NewSetCC.getNode()) {
7918         CC = NewSetCC.getOperand(0);
7919         Cond = NewSetCC.getOperand(1);
7920         addTest = false;
7921       }
7922     }
7923   }
7924
7925   if (addTest) {
7926     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7927     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7928   }
7929
7930   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7931   // a <  b ?  0 : -1 -> RES = setcc_carry
7932   // a >= b ? -1 :  0 -> RES = setcc_carry
7933   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7934   if (Cond.getOpcode() == X86ISD::CMP) {
7935     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7936
7937     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7938         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7939       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7940                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7941       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7942         return DAG.getNOT(DL, Res, Res.getValueType());
7943       return Res;
7944     }
7945   }
7946
7947   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7948   // condition is true.
7949   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7950   SDValue Ops[] = { Op2, Op1, CC, Cond };
7951   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7952 }
7953
7954 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7955 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7956 // from the AND / OR.
7957 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7958   Opc = Op.getOpcode();
7959   if (Opc != ISD::OR && Opc != ISD::AND)
7960     return false;
7961   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7962           Op.getOperand(0).hasOneUse() &&
7963           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7964           Op.getOperand(1).hasOneUse());
7965 }
7966
7967 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7968 // 1 and that the SETCC node has a single use.
7969 static bool isXor1OfSetCC(SDValue Op) {
7970   if (Op.getOpcode() != ISD::XOR)
7971     return false;
7972   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7973   if (N1C && N1C->getAPIntValue() == 1) {
7974     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7975       Op.getOperand(0).hasOneUse();
7976   }
7977   return false;
7978 }
7979
7980 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7981   bool addTest = true;
7982   SDValue Chain = Op.getOperand(0);
7983   SDValue Cond  = Op.getOperand(1);
7984   SDValue Dest  = Op.getOperand(2);
7985   DebugLoc dl = Op.getDebugLoc();
7986   SDValue CC;
7987
7988   if (Cond.getOpcode() == ISD::SETCC) {
7989     SDValue NewCond = LowerSETCC(Cond, DAG);
7990     if (NewCond.getNode())
7991       Cond = NewCond;
7992   }
7993 #if 0
7994   // FIXME: LowerXALUO doesn't handle these!!
7995   else if (Cond.getOpcode() == X86ISD::ADD  ||
7996            Cond.getOpcode() == X86ISD::SUB  ||
7997            Cond.getOpcode() == X86ISD::SMUL ||
7998            Cond.getOpcode() == X86ISD::UMUL)
7999     Cond = LowerXALUO(Cond, DAG);
8000 #endif
8001
8002   // Look pass (and (setcc_carry (cmp ...)), 1).
8003   if (Cond.getOpcode() == ISD::AND &&
8004       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8005     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8006     if (C && C->getAPIntValue() == 1)
8007       Cond = Cond.getOperand(0);
8008   }
8009
8010   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8011   // setting operand in place of the X86ISD::SETCC.
8012   if (Cond.getOpcode() == X86ISD::SETCC ||
8013       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8014     CC = Cond.getOperand(0);
8015
8016     SDValue Cmp = Cond.getOperand(1);
8017     unsigned Opc = Cmp.getOpcode();
8018     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8019     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8020       Cond = Cmp;
8021       addTest = false;
8022     } else {
8023       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8024       default: break;
8025       case X86::COND_O:
8026       case X86::COND_B:
8027         // These can only come from an arithmetic instruction with overflow,
8028         // e.g. SADDO, UADDO.
8029         Cond = Cond.getNode()->getOperand(1);
8030         addTest = false;
8031         break;
8032       }
8033     }
8034   } else {
8035     unsigned CondOpc;
8036     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8037       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8038       if (CondOpc == ISD::OR) {
8039         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8040         // two branches instead of an explicit OR instruction with a
8041         // separate test.
8042         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8043             isX86LogicalCmp(Cmp)) {
8044           CC = Cond.getOperand(0).getOperand(0);
8045           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8046                               Chain, Dest, CC, Cmp);
8047           CC = Cond.getOperand(1).getOperand(0);
8048           Cond = Cmp;
8049           addTest = false;
8050         }
8051       } else { // ISD::AND
8052         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8053         // two branches instead of an explicit AND instruction with a
8054         // separate test. However, we only do this if this block doesn't
8055         // have a fall-through edge, because this requires an explicit
8056         // jmp when the condition is false.
8057         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8058             isX86LogicalCmp(Cmp) &&
8059             Op.getNode()->hasOneUse()) {
8060           X86::CondCode CCode =
8061             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8062           CCode = X86::GetOppositeBranchCondition(CCode);
8063           CC = DAG.getConstant(CCode, MVT::i8);
8064           SDNode *User = *Op.getNode()->use_begin();
8065           // Look for an unconditional branch following this conditional branch.
8066           // We need this because we need to reverse the successors in order
8067           // to implement FCMP_OEQ.
8068           if (User->getOpcode() == ISD::BR) {
8069             SDValue FalseBB = User->getOperand(1);
8070             SDNode *NewBR =
8071               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8072             assert(NewBR == User);
8073             (void)NewBR;
8074             Dest = FalseBB;
8075
8076             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8077                                 Chain, Dest, CC, Cmp);
8078             X86::CondCode CCode =
8079               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8080             CCode = X86::GetOppositeBranchCondition(CCode);
8081             CC = DAG.getConstant(CCode, MVT::i8);
8082             Cond = Cmp;
8083             addTest = false;
8084           }
8085         }
8086       }
8087     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8088       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8089       // It should be transformed during dag combiner except when the condition
8090       // is set by a arithmetics with overflow node.
8091       X86::CondCode CCode =
8092         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8093       CCode = X86::GetOppositeBranchCondition(CCode);
8094       CC = DAG.getConstant(CCode, MVT::i8);
8095       Cond = Cond.getOperand(0).getOperand(1);
8096       addTest = false;
8097     }
8098   }
8099
8100   if (addTest) {
8101     // Look pass the truncate.
8102     if (Cond.getOpcode() == ISD::TRUNCATE)
8103       Cond = Cond.getOperand(0);
8104
8105     // We know the result of AND is compared against zero. Try to match
8106     // it to BT.
8107     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8108       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8109       if (NewSetCC.getNode()) {
8110         CC = NewSetCC.getOperand(0);
8111         Cond = NewSetCC.getOperand(1);
8112         addTest = false;
8113       }
8114     }
8115   }
8116
8117   if (addTest) {
8118     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8119     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8120   }
8121   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8122                      Chain, Dest, CC, Cond);
8123 }
8124
8125
8126 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8127 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8128 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8129 // that the guard pages used by the OS virtual memory manager are allocated in
8130 // correct sequence.
8131 SDValue
8132 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8133                                            SelectionDAG &DAG) const {
8134   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8135          "This should be used only on Windows targets");
8136   assert(!Subtarget->isTargetEnvMacho());
8137   DebugLoc dl = Op.getDebugLoc();
8138
8139   // Get the inputs.
8140   SDValue Chain = Op.getOperand(0);
8141   SDValue Size  = Op.getOperand(1);
8142   // FIXME: Ensure alignment here
8143
8144   SDValue Flag;
8145
8146   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8147   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8148
8149   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8150   Flag = Chain.getValue(1);
8151
8152   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8153
8154   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8155   Flag = Chain.getValue(1);
8156
8157   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8158
8159   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8160   return DAG.getMergeValues(Ops1, 2, dl);
8161 }
8162
8163 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8164   MachineFunction &MF = DAG.getMachineFunction();
8165   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8166
8167   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8168   DebugLoc DL = Op.getDebugLoc();
8169
8170   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8171     // vastart just stores the address of the VarArgsFrameIndex slot into the
8172     // memory location argument.
8173     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8174                                    getPointerTy());
8175     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8176                         MachinePointerInfo(SV), false, false, 0);
8177   }
8178
8179   // __va_list_tag:
8180   //   gp_offset         (0 - 6 * 8)
8181   //   fp_offset         (48 - 48 + 8 * 16)
8182   //   overflow_arg_area (point to parameters coming in memory).
8183   //   reg_save_area
8184   SmallVector<SDValue, 8> MemOps;
8185   SDValue FIN = Op.getOperand(1);
8186   // Store gp_offset
8187   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8188                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8189                                                MVT::i32),
8190                                FIN, MachinePointerInfo(SV), false, false, 0);
8191   MemOps.push_back(Store);
8192
8193   // Store fp_offset
8194   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8195                     FIN, DAG.getIntPtrConstant(4));
8196   Store = DAG.getStore(Op.getOperand(0), DL,
8197                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8198                                        MVT::i32),
8199                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8200   MemOps.push_back(Store);
8201
8202   // Store ptr to overflow_arg_area
8203   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8204                     FIN, DAG.getIntPtrConstant(4));
8205   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8206                                     getPointerTy());
8207   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8208                        MachinePointerInfo(SV, 8),
8209                        false, false, 0);
8210   MemOps.push_back(Store);
8211
8212   // Store ptr to reg_save_area.
8213   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8214                     FIN, DAG.getIntPtrConstant(8));
8215   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8216                                     getPointerTy());
8217   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8218                        MachinePointerInfo(SV, 16), false, false, 0);
8219   MemOps.push_back(Store);
8220   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8221                      &MemOps[0], MemOps.size());
8222 }
8223
8224 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8225   assert(Subtarget->is64Bit() &&
8226          "LowerVAARG only handles 64-bit va_arg!");
8227   assert((Subtarget->isTargetLinux() ||
8228           Subtarget->isTargetDarwin()) &&
8229           "Unhandled target in LowerVAARG");
8230   assert(Op.getNode()->getNumOperands() == 4);
8231   SDValue Chain = Op.getOperand(0);
8232   SDValue SrcPtr = Op.getOperand(1);
8233   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8234   unsigned Align = Op.getConstantOperandVal(3);
8235   DebugLoc dl = Op.getDebugLoc();
8236
8237   EVT ArgVT = Op.getNode()->getValueType(0);
8238   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8239   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8240   uint8_t ArgMode;
8241
8242   // Decide which area this value should be read from.
8243   // TODO: Implement the AMD64 ABI in its entirety. This simple
8244   // selection mechanism works only for the basic types.
8245   if (ArgVT == MVT::f80) {
8246     llvm_unreachable("va_arg for f80 not yet implemented");
8247   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8248     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8249   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8250     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8251   } else {
8252     llvm_unreachable("Unhandled argument type in LowerVAARG");
8253   }
8254
8255   if (ArgMode == 2) {
8256     // Sanity Check: Make sure using fp_offset makes sense.
8257     assert(!UseSoftFloat &&
8258            !(DAG.getMachineFunction()
8259                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8260            Subtarget->hasXMM());
8261   }
8262
8263   // Insert VAARG_64 node into the DAG
8264   // VAARG_64 returns two values: Variable Argument Address, Chain
8265   SmallVector<SDValue, 11> InstOps;
8266   InstOps.push_back(Chain);
8267   InstOps.push_back(SrcPtr);
8268   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8269   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8270   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8271   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8272   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8273                                           VTs, &InstOps[0], InstOps.size(),
8274                                           MVT::i64,
8275                                           MachinePointerInfo(SV),
8276                                           /*Align=*/0,
8277                                           /*Volatile=*/false,
8278                                           /*ReadMem=*/true,
8279                                           /*WriteMem=*/true);
8280   Chain = VAARG.getValue(1);
8281
8282   // Load the next argument and return it
8283   return DAG.getLoad(ArgVT, dl,
8284                      Chain,
8285                      VAARG,
8286                      MachinePointerInfo(),
8287                      false, false, 0);
8288 }
8289
8290 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8291   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8292   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8293   SDValue Chain = Op.getOperand(0);
8294   SDValue DstPtr = Op.getOperand(1);
8295   SDValue SrcPtr = Op.getOperand(2);
8296   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8297   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8298   DebugLoc DL = Op.getDebugLoc();
8299
8300   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8301                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8302                        false,
8303                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8304 }
8305
8306 SDValue
8307 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8308   DebugLoc dl = Op.getDebugLoc();
8309   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8310   switch (IntNo) {
8311   default: return SDValue();    // Don't custom lower most intrinsics.
8312   // Comparison intrinsics.
8313   case Intrinsic::x86_sse_comieq_ss:
8314   case Intrinsic::x86_sse_comilt_ss:
8315   case Intrinsic::x86_sse_comile_ss:
8316   case Intrinsic::x86_sse_comigt_ss:
8317   case Intrinsic::x86_sse_comige_ss:
8318   case Intrinsic::x86_sse_comineq_ss:
8319   case Intrinsic::x86_sse_ucomieq_ss:
8320   case Intrinsic::x86_sse_ucomilt_ss:
8321   case Intrinsic::x86_sse_ucomile_ss:
8322   case Intrinsic::x86_sse_ucomigt_ss:
8323   case Intrinsic::x86_sse_ucomige_ss:
8324   case Intrinsic::x86_sse_ucomineq_ss:
8325   case Intrinsic::x86_sse2_comieq_sd:
8326   case Intrinsic::x86_sse2_comilt_sd:
8327   case Intrinsic::x86_sse2_comile_sd:
8328   case Intrinsic::x86_sse2_comigt_sd:
8329   case Intrinsic::x86_sse2_comige_sd:
8330   case Intrinsic::x86_sse2_comineq_sd:
8331   case Intrinsic::x86_sse2_ucomieq_sd:
8332   case Intrinsic::x86_sse2_ucomilt_sd:
8333   case Intrinsic::x86_sse2_ucomile_sd:
8334   case Intrinsic::x86_sse2_ucomigt_sd:
8335   case Intrinsic::x86_sse2_ucomige_sd:
8336   case Intrinsic::x86_sse2_ucomineq_sd: {
8337     unsigned Opc = 0;
8338     ISD::CondCode CC = ISD::SETCC_INVALID;
8339     switch (IntNo) {
8340     default: break;
8341     case Intrinsic::x86_sse_comieq_ss:
8342     case Intrinsic::x86_sse2_comieq_sd:
8343       Opc = X86ISD::COMI;
8344       CC = ISD::SETEQ;
8345       break;
8346     case Intrinsic::x86_sse_comilt_ss:
8347     case Intrinsic::x86_sse2_comilt_sd:
8348       Opc = X86ISD::COMI;
8349       CC = ISD::SETLT;
8350       break;
8351     case Intrinsic::x86_sse_comile_ss:
8352     case Intrinsic::x86_sse2_comile_sd:
8353       Opc = X86ISD::COMI;
8354       CC = ISD::SETLE;
8355       break;
8356     case Intrinsic::x86_sse_comigt_ss:
8357     case Intrinsic::x86_sse2_comigt_sd:
8358       Opc = X86ISD::COMI;
8359       CC = ISD::SETGT;
8360       break;
8361     case Intrinsic::x86_sse_comige_ss:
8362     case Intrinsic::x86_sse2_comige_sd:
8363       Opc = X86ISD::COMI;
8364       CC = ISD::SETGE;
8365       break;
8366     case Intrinsic::x86_sse_comineq_ss:
8367     case Intrinsic::x86_sse2_comineq_sd:
8368       Opc = X86ISD::COMI;
8369       CC = ISD::SETNE;
8370       break;
8371     case Intrinsic::x86_sse_ucomieq_ss:
8372     case Intrinsic::x86_sse2_ucomieq_sd:
8373       Opc = X86ISD::UCOMI;
8374       CC = ISD::SETEQ;
8375       break;
8376     case Intrinsic::x86_sse_ucomilt_ss:
8377     case Intrinsic::x86_sse2_ucomilt_sd:
8378       Opc = X86ISD::UCOMI;
8379       CC = ISD::SETLT;
8380       break;
8381     case Intrinsic::x86_sse_ucomile_ss:
8382     case Intrinsic::x86_sse2_ucomile_sd:
8383       Opc = X86ISD::UCOMI;
8384       CC = ISD::SETLE;
8385       break;
8386     case Intrinsic::x86_sse_ucomigt_ss:
8387     case Intrinsic::x86_sse2_ucomigt_sd:
8388       Opc = X86ISD::UCOMI;
8389       CC = ISD::SETGT;
8390       break;
8391     case Intrinsic::x86_sse_ucomige_ss:
8392     case Intrinsic::x86_sse2_ucomige_sd:
8393       Opc = X86ISD::UCOMI;
8394       CC = ISD::SETGE;
8395       break;
8396     case Intrinsic::x86_sse_ucomineq_ss:
8397     case Intrinsic::x86_sse2_ucomineq_sd:
8398       Opc = X86ISD::UCOMI;
8399       CC = ISD::SETNE;
8400       break;
8401     }
8402
8403     SDValue LHS = Op.getOperand(1);
8404     SDValue RHS = Op.getOperand(2);
8405     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8406     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8407     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8408     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8409                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8410     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8411   }
8412   // ptest and testp intrinsics. The intrinsic these come from are designed to
8413   // return an integer value, not just an instruction so lower it to the ptest
8414   // or testp pattern and a setcc for the result.
8415   case Intrinsic::x86_sse41_ptestz:
8416   case Intrinsic::x86_sse41_ptestc:
8417   case Intrinsic::x86_sse41_ptestnzc:
8418   case Intrinsic::x86_avx_ptestz_256:
8419   case Intrinsic::x86_avx_ptestc_256:
8420   case Intrinsic::x86_avx_ptestnzc_256:
8421   case Intrinsic::x86_avx_vtestz_ps:
8422   case Intrinsic::x86_avx_vtestc_ps:
8423   case Intrinsic::x86_avx_vtestnzc_ps:
8424   case Intrinsic::x86_avx_vtestz_pd:
8425   case Intrinsic::x86_avx_vtestc_pd:
8426   case Intrinsic::x86_avx_vtestnzc_pd:
8427   case Intrinsic::x86_avx_vtestz_ps_256:
8428   case Intrinsic::x86_avx_vtestc_ps_256:
8429   case Intrinsic::x86_avx_vtestnzc_ps_256:
8430   case Intrinsic::x86_avx_vtestz_pd_256:
8431   case Intrinsic::x86_avx_vtestc_pd_256:
8432   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8433     bool IsTestPacked = false;
8434     unsigned X86CC = 0;
8435     switch (IntNo) {
8436     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8437     case Intrinsic::x86_avx_vtestz_ps:
8438     case Intrinsic::x86_avx_vtestz_pd:
8439     case Intrinsic::x86_avx_vtestz_ps_256:
8440     case Intrinsic::x86_avx_vtestz_pd_256:
8441       IsTestPacked = true; // Fallthrough
8442     case Intrinsic::x86_sse41_ptestz:
8443     case Intrinsic::x86_avx_ptestz_256:
8444       // ZF = 1
8445       X86CC = X86::COND_E;
8446       break;
8447     case Intrinsic::x86_avx_vtestc_ps:
8448     case Intrinsic::x86_avx_vtestc_pd:
8449     case Intrinsic::x86_avx_vtestc_ps_256:
8450     case Intrinsic::x86_avx_vtestc_pd_256:
8451       IsTestPacked = true; // Fallthrough
8452     case Intrinsic::x86_sse41_ptestc:
8453     case Intrinsic::x86_avx_ptestc_256:
8454       // CF = 1
8455       X86CC = X86::COND_B;
8456       break;
8457     case Intrinsic::x86_avx_vtestnzc_ps:
8458     case Intrinsic::x86_avx_vtestnzc_pd:
8459     case Intrinsic::x86_avx_vtestnzc_ps_256:
8460     case Intrinsic::x86_avx_vtestnzc_pd_256:
8461       IsTestPacked = true; // Fallthrough
8462     case Intrinsic::x86_sse41_ptestnzc:
8463     case Intrinsic::x86_avx_ptestnzc_256:
8464       // ZF and CF = 0
8465       X86CC = X86::COND_A;
8466       break;
8467     }
8468
8469     SDValue LHS = Op.getOperand(1);
8470     SDValue RHS = Op.getOperand(2);
8471     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8472     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8473     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8474     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8475     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8476   }
8477
8478   // Fix vector shift instructions where the last operand is a non-immediate
8479   // i32 value.
8480   case Intrinsic::x86_sse2_pslli_w:
8481   case Intrinsic::x86_sse2_pslli_d:
8482   case Intrinsic::x86_sse2_pslli_q:
8483   case Intrinsic::x86_sse2_psrli_w:
8484   case Intrinsic::x86_sse2_psrli_d:
8485   case Intrinsic::x86_sse2_psrli_q:
8486   case Intrinsic::x86_sse2_psrai_w:
8487   case Intrinsic::x86_sse2_psrai_d:
8488   case Intrinsic::x86_mmx_pslli_w:
8489   case Intrinsic::x86_mmx_pslli_d:
8490   case Intrinsic::x86_mmx_pslli_q:
8491   case Intrinsic::x86_mmx_psrli_w:
8492   case Intrinsic::x86_mmx_psrli_d:
8493   case Intrinsic::x86_mmx_psrli_q:
8494   case Intrinsic::x86_mmx_psrai_w:
8495   case Intrinsic::x86_mmx_psrai_d: {
8496     SDValue ShAmt = Op.getOperand(2);
8497     if (isa<ConstantSDNode>(ShAmt))
8498       return SDValue();
8499
8500     unsigned NewIntNo = 0;
8501     EVT ShAmtVT = MVT::v4i32;
8502     switch (IntNo) {
8503     case Intrinsic::x86_sse2_pslli_w:
8504       NewIntNo = Intrinsic::x86_sse2_psll_w;
8505       break;
8506     case Intrinsic::x86_sse2_pslli_d:
8507       NewIntNo = Intrinsic::x86_sse2_psll_d;
8508       break;
8509     case Intrinsic::x86_sse2_pslli_q:
8510       NewIntNo = Intrinsic::x86_sse2_psll_q;
8511       break;
8512     case Intrinsic::x86_sse2_psrli_w:
8513       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8514       break;
8515     case Intrinsic::x86_sse2_psrli_d:
8516       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8517       break;
8518     case Intrinsic::x86_sse2_psrli_q:
8519       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8520       break;
8521     case Intrinsic::x86_sse2_psrai_w:
8522       NewIntNo = Intrinsic::x86_sse2_psra_w;
8523       break;
8524     case Intrinsic::x86_sse2_psrai_d:
8525       NewIntNo = Intrinsic::x86_sse2_psra_d;
8526       break;
8527     default: {
8528       ShAmtVT = MVT::v2i32;
8529       switch (IntNo) {
8530       case Intrinsic::x86_mmx_pslli_w:
8531         NewIntNo = Intrinsic::x86_mmx_psll_w;
8532         break;
8533       case Intrinsic::x86_mmx_pslli_d:
8534         NewIntNo = Intrinsic::x86_mmx_psll_d;
8535         break;
8536       case Intrinsic::x86_mmx_pslli_q:
8537         NewIntNo = Intrinsic::x86_mmx_psll_q;
8538         break;
8539       case Intrinsic::x86_mmx_psrli_w:
8540         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8541         break;
8542       case Intrinsic::x86_mmx_psrli_d:
8543         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8544         break;
8545       case Intrinsic::x86_mmx_psrli_q:
8546         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8547         break;
8548       case Intrinsic::x86_mmx_psrai_w:
8549         NewIntNo = Intrinsic::x86_mmx_psra_w;
8550         break;
8551       case Intrinsic::x86_mmx_psrai_d:
8552         NewIntNo = Intrinsic::x86_mmx_psra_d;
8553         break;
8554       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8555       }
8556       break;
8557     }
8558     }
8559
8560     // The vector shift intrinsics with scalars uses 32b shift amounts but
8561     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8562     // to be zero.
8563     SDValue ShOps[4];
8564     ShOps[0] = ShAmt;
8565     ShOps[1] = DAG.getConstant(0, MVT::i32);
8566     if (ShAmtVT == MVT::v4i32) {
8567       ShOps[2] = DAG.getUNDEF(MVT::i32);
8568       ShOps[3] = DAG.getUNDEF(MVT::i32);
8569       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8570     } else {
8571       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8572 // FIXME this must be lowered to get rid of the invalid type.
8573     }
8574
8575     EVT VT = Op.getValueType();
8576     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8577     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8578                        DAG.getConstant(NewIntNo, MVT::i32),
8579                        Op.getOperand(1), ShAmt);
8580   }
8581   }
8582 }
8583
8584 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8585                                            SelectionDAG &DAG) const {
8586   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8587   MFI->setReturnAddressIsTaken(true);
8588
8589   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8590   DebugLoc dl = Op.getDebugLoc();
8591
8592   if (Depth > 0) {
8593     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8594     SDValue Offset =
8595       DAG.getConstant(TD->getPointerSize(),
8596                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8597     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8598                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8599                                    FrameAddr, Offset),
8600                        MachinePointerInfo(), false, false, 0);
8601   }
8602
8603   // Just load the return address.
8604   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8605   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8606                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8607 }
8608
8609 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8610   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8611   MFI->setFrameAddressIsTaken(true);
8612
8613   EVT VT = Op.getValueType();
8614   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8615   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8616   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8617   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8618   while (Depth--)
8619     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8620                             MachinePointerInfo(),
8621                             false, false, 0);
8622   return FrameAddr;
8623 }
8624
8625 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8626                                                      SelectionDAG &DAG) const {
8627   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8628 }
8629
8630 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8631   MachineFunction &MF = DAG.getMachineFunction();
8632   SDValue Chain     = Op.getOperand(0);
8633   SDValue Offset    = Op.getOperand(1);
8634   SDValue Handler   = Op.getOperand(2);
8635   DebugLoc dl       = Op.getDebugLoc();
8636
8637   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8638                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8639                                      getPointerTy());
8640   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8641
8642   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8643                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8644   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8645   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8646                        false, false, 0);
8647   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8648   MF.getRegInfo().addLiveOut(StoreAddrReg);
8649
8650   return DAG.getNode(X86ISD::EH_RETURN, dl,
8651                      MVT::Other,
8652                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8653 }
8654
8655 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8656                                              SelectionDAG &DAG) const {
8657   SDValue Root = Op.getOperand(0);
8658   SDValue Trmp = Op.getOperand(1); // trampoline
8659   SDValue FPtr = Op.getOperand(2); // nested function
8660   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8661   DebugLoc dl  = Op.getDebugLoc();
8662
8663   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8664
8665   if (Subtarget->is64Bit()) {
8666     SDValue OutChains[6];
8667
8668     // Large code-model.
8669     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8670     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8671
8672     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8673     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8674
8675     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8676
8677     // Load the pointer to the nested function into R11.
8678     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8679     SDValue Addr = Trmp;
8680     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8681                                 Addr, MachinePointerInfo(TrmpAddr),
8682                                 false, false, 0);
8683
8684     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8685                        DAG.getConstant(2, MVT::i64));
8686     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8687                                 MachinePointerInfo(TrmpAddr, 2),
8688                                 false, false, 2);
8689
8690     // Load the 'nest' parameter value into R10.
8691     // R10 is specified in X86CallingConv.td
8692     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8693     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8694                        DAG.getConstant(10, MVT::i64));
8695     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8696                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8697                                 false, false, 0);
8698
8699     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8700                        DAG.getConstant(12, MVT::i64));
8701     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8702                                 MachinePointerInfo(TrmpAddr, 12),
8703                                 false, false, 2);
8704
8705     // Jump to the nested function.
8706     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8707     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8708                        DAG.getConstant(20, MVT::i64));
8709     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8710                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8711                                 false, false, 0);
8712
8713     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8714     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8715                        DAG.getConstant(22, MVT::i64));
8716     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8717                                 MachinePointerInfo(TrmpAddr, 22),
8718                                 false, false, 0);
8719
8720     SDValue Ops[] =
8721       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8722     return DAG.getMergeValues(Ops, 2, dl);
8723   } else {
8724     const Function *Func =
8725       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8726     CallingConv::ID CC = Func->getCallingConv();
8727     unsigned NestReg;
8728
8729     switch (CC) {
8730     default:
8731       llvm_unreachable("Unsupported calling convention");
8732     case CallingConv::C:
8733     case CallingConv::X86_StdCall: {
8734       // Pass 'nest' parameter in ECX.
8735       // Must be kept in sync with X86CallingConv.td
8736       NestReg = X86::ECX;
8737
8738       // Check that ECX wasn't needed by an 'inreg' parameter.
8739       FunctionType *FTy = Func->getFunctionType();
8740       const AttrListPtr &Attrs = Func->getAttributes();
8741
8742       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8743         unsigned InRegCount = 0;
8744         unsigned Idx = 1;
8745
8746         for (FunctionType::param_iterator I = FTy->param_begin(),
8747              E = FTy->param_end(); I != E; ++I, ++Idx)
8748           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8749             // FIXME: should only count parameters that are lowered to integers.
8750             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8751
8752         if (InRegCount > 2) {
8753           report_fatal_error("Nest register in use - reduce number of inreg"
8754                              " parameters!");
8755         }
8756       }
8757       break;
8758     }
8759     case CallingConv::X86_FastCall:
8760     case CallingConv::X86_ThisCall:
8761     case CallingConv::Fast:
8762       // Pass 'nest' parameter in EAX.
8763       // Must be kept in sync with X86CallingConv.td
8764       NestReg = X86::EAX;
8765       break;
8766     }
8767
8768     SDValue OutChains[4];
8769     SDValue Addr, Disp;
8770
8771     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8772                        DAG.getConstant(10, MVT::i32));
8773     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8774
8775     // This is storing the opcode for MOV32ri.
8776     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8777     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
8778     OutChains[0] = DAG.getStore(Root, dl,
8779                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8780                                 Trmp, MachinePointerInfo(TrmpAddr),
8781                                 false, false, 0);
8782
8783     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8784                        DAG.getConstant(1, MVT::i32));
8785     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8786                                 MachinePointerInfo(TrmpAddr, 1),
8787                                 false, false, 1);
8788
8789     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8790     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8791                        DAG.getConstant(5, MVT::i32));
8792     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8793                                 MachinePointerInfo(TrmpAddr, 5),
8794                                 false, false, 1);
8795
8796     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8797                        DAG.getConstant(6, MVT::i32));
8798     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8799                                 MachinePointerInfo(TrmpAddr, 6),
8800                                 false, false, 1);
8801
8802     SDValue Ops[] =
8803       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8804     return DAG.getMergeValues(Ops, 2, dl);
8805   }
8806 }
8807
8808 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8809                                             SelectionDAG &DAG) const {
8810   /*
8811    The rounding mode is in bits 11:10 of FPSR, and has the following
8812    settings:
8813      00 Round to nearest
8814      01 Round to -inf
8815      10 Round to +inf
8816      11 Round to 0
8817
8818   FLT_ROUNDS, on the other hand, expects the following:
8819     -1 Undefined
8820      0 Round to 0
8821      1 Round to nearest
8822      2 Round to +inf
8823      3 Round to -inf
8824
8825   To perform the conversion, we do:
8826     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8827   */
8828
8829   MachineFunction &MF = DAG.getMachineFunction();
8830   const TargetMachine &TM = MF.getTarget();
8831   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8832   unsigned StackAlignment = TFI.getStackAlignment();
8833   EVT VT = Op.getValueType();
8834   DebugLoc DL = Op.getDebugLoc();
8835
8836   // Save FP Control Word to stack slot
8837   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8838   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8839
8840
8841   MachineMemOperand *MMO =
8842    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8843                            MachineMemOperand::MOStore, 2, 2);
8844
8845   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8846   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8847                                           DAG.getVTList(MVT::Other),
8848                                           Ops, 2, MVT::i16, MMO);
8849
8850   // Load FP Control Word from stack slot
8851   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8852                             MachinePointerInfo(), false, false, 0);
8853
8854   // Transform as necessary
8855   SDValue CWD1 =
8856     DAG.getNode(ISD::SRL, DL, MVT::i16,
8857                 DAG.getNode(ISD::AND, DL, MVT::i16,
8858                             CWD, DAG.getConstant(0x800, MVT::i16)),
8859                 DAG.getConstant(11, MVT::i8));
8860   SDValue CWD2 =
8861     DAG.getNode(ISD::SRL, DL, MVT::i16,
8862                 DAG.getNode(ISD::AND, DL, MVT::i16,
8863                             CWD, DAG.getConstant(0x400, MVT::i16)),
8864                 DAG.getConstant(9, MVT::i8));
8865
8866   SDValue RetVal =
8867     DAG.getNode(ISD::AND, DL, MVT::i16,
8868                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8869                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8870                             DAG.getConstant(1, MVT::i16)),
8871                 DAG.getConstant(3, MVT::i16));
8872
8873
8874   return DAG.getNode((VT.getSizeInBits() < 16 ?
8875                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8876 }
8877
8878 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8879   EVT VT = Op.getValueType();
8880   EVT OpVT = VT;
8881   unsigned NumBits = VT.getSizeInBits();
8882   DebugLoc dl = Op.getDebugLoc();
8883
8884   Op = Op.getOperand(0);
8885   if (VT == MVT::i8) {
8886     // Zero extend to i32 since there is not an i8 bsr.
8887     OpVT = MVT::i32;
8888     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8889   }
8890
8891   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8892   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8893   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8894
8895   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8896   SDValue Ops[] = {
8897     Op,
8898     DAG.getConstant(NumBits+NumBits-1, OpVT),
8899     DAG.getConstant(X86::COND_E, MVT::i8),
8900     Op.getValue(1)
8901   };
8902   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8903
8904   // Finally xor with NumBits-1.
8905   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8906
8907   if (VT == MVT::i8)
8908     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8909   return Op;
8910 }
8911
8912 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8913   EVT VT = Op.getValueType();
8914   EVT OpVT = VT;
8915   unsigned NumBits = VT.getSizeInBits();
8916   DebugLoc dl = Op.getDebugLoc();
8917
8918   Op = Op.getOperand(0);
8919   if (VT == MVT::i8) {
8920     OpVT = MVT::i32;
8921     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8922   }
8923
8924   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8925   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8926   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8927
8928   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8929   SDValue Ops[] = {
8930     Op,
8931     DAG.getConstant(NumBits, OpVT),
8932     DAG.getConstant(X86::COND_E, MVT::i8),
8933     Op.getValue(1)
8934   };
8935   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8936
8937   if (VT == MVT::i8)
8938     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8939   return Op;
8940 }
8941
8942 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8943   EVT VT = Op.getValueType();
8944   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8945   DebugLoc dl = Op.getDebugLoc();
8946
8947   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8948   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8949   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8950   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8951   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8952   //
8953   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8954   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8955   //  return AloBlo + AloBhi + AhiBlo;
8956
8957   SDValue A = Op.getOperand(0);
8958   SDValue B = Op.getOperand(1);
8959
8960   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8961                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8962                        A, DAG.getConstant(32, MVT::i32));
8963   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8964                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8965                        B, DAG.getConstant(32, MVT::i32));
8966   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8967                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8968                        A, B);
8969   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8970                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8971                        A, Bhi);
8972   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8973                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8974                        Ahi, B);
8975   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8976                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8977                        AloBhi, DAG.getConstant(32, MVT::i32));
8978   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8979                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8980                        AhiBlo, DAG.getConstant(32, MVT::i32));
8981   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8982   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8983   return Res;
8984 }
8985
8986 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8987
8988   EVT VT = Op.getValueType();
8989   DebugLoc dl = Op.getDebugLoc();
8990   SDValue R = Op.getOperand(0);
8991   SDValue Amt = Op.getOperand(1);
8992
8993   LLVMContext *Context = DAG.getContext();
8994
8995   // Must have SSE2.
8996   if (!Subtarget->hasSSE2()) return SDValue();
8997
8998   // Optimize shl/srl/sra with constant shift amount.
8999   if (isSplatVector(Amt.getNode())) {
9000     SDValue SclrAmt = Amt->getOperand(0);
9001     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9002       uint64_t ShiftAmt = C->getZExtValue();
9003
9004       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9005        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9006                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9007                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9008
9009       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9010        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9011                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9012                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9013
9014       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9015        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9016                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9017                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9018
9019       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9020        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9021                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9022                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9023
9024       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9025        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9026                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9027                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9028
9029       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9030        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9031                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9032                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9033
9034       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9035        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9036                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9037                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9038
9039       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9040        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9041                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9042                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9043     }
9044   }
9045
9046   // Lower SHL with variable shift amount.
9047   // Cannot lower SHL without SSE2 or later.
9048   if (!Subtarget->hasSSE2()) return SDValue();
9049
9050   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9051     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9052                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9053                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9054
9055     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9056
9057     std::vector<Constant*> CV(4, CI);
9058     Constant *C = ConstantVector::get(CV);
9059     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9060     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9061                                  MachinePointerInfo::getConstantPool(),
9062                                  false, false, 16);
9063
9064     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9065     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9066     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9067     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9068   }
9069   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9070     // a = a << 5;
9071     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9072                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9073                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9074
9075     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9076     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9077
9078     std::vector<Constant*> CVM1(16, CM1);
9079     std::vector<Constant*> CVM2(16, CM2);
9080     Constant *C = ConstantVector::get(CVM1);
9081     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9082     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9083                             MachinePointerInfo::getConstantPool(),
9084                             false, false, 16);
9085
9086     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9087     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9088     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9089                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9090                     DAG.getConstant(4, MVT::i32));
9091     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9092     // a += a
9093     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9094
9095     C = ConstantVector::get(CVM2);
9096     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9097     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9098                     MachinePointerInfo::getConstantPool(),
9099                     false, false, 16);
9100
9101     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9102     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9103     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9104                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9105                     DAG.getConstant(2, MVT::i32));
9106     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9107     // a += a
9108     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9109
9110     // return pblendv(r, r+r, a);
9111     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9112                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9113     return R;
9114   }
9115   return SDValue();
9116 }
9117
9118 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9119   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9120   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9121   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9122   // has only one use.
9123   SDNode *N = Op.getNode();
9124   SDValue LHS = N->getOperand(0);
9125   SDValue RHS = N->getOperand(1);
9126   unsigned BaseOp = 0;
9127   unsigned Cond = 0;
9128   DebugLoc DL = Op.getDebugLoc();
9129   switch (Op.getOpcode()) {
9130   default: llvm_unreachable("Unknown ovf instruction!");
9131   case ISD::SADDO:
9132     // A subtract of one will be selected as a INC. Note that INC doesn't
9133     // set CF, so we can't do this for UADDO.
9134     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9135       if (C->isOne()) {
9136         BaseOp = X86ISD::INC;
9137         Cond = X86::COND_O;
9138         break;
9139       }
9140     BaseOp = X86ISD::ADD;
9141     Cond = X86::COND_O;
9142     break;
9143   case ISD::UADDO:
9144     BaseOp = X86ISD::ADD;
9145     Cond = X86::COND_B;
9146     break;
9147   case ISD::SSUBO:
9148     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9149     // set CF, so we can't do this for USUBO.
9150     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9151       if (C->isOne()) {
9152         BaseOp = X86ISD::DEC;
9153         Cond = X86::COND_O;
9154         break;
9155       }
9156     BaseOp = X86ISD::SUB;
9157     Cond = X86::COND_O;
9158     break;
9159   case ISD::USUBO:
9160     BaseOp = X86ISD::SUB;
9161     Cond = X86::COND_B;
9162     break;
9163   case ISD::SMULO:
9164     BaseOp = X86ISD::SMUL;
9165     Cond = X86::COND_O;
9166     break;
9167   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9168     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9169                                  MVT::i32);
9170     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9171
9172     SDValue SetCC =
9173       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9174                   DAG.getConstant(X86::COND_O, MVT::i32),
9175                   SDValue(Sum.getNode(), 2));
9176
9177     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9178   }
9179   }
9180
9181   // Also sets EFLAGS.
9182   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9183   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9184
9185   SDValue SetCC =
9186     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9187                 DAG.getConstant(Cond, MVT::i32),
9188                 SDValue(Sum.getNode(), 1));
9189
9190   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9191 }
9192
9193 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9194   DebugLoc dl = Op.getDebugLoc();
9195   SDNode* Node = Op.getNode();
9196   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9197   EVT VT = Node->getValueType(0);
9198
9199   if (Subtarget->hasSSE2() && VT.isVector()) {
9200     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9201                         ExtraVT.getScalarType().getSizeInBits();
9202     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9203
9204     unsigned SHLIntrinsicsID = 0;
9205     unsigned SRAIntrinsicsID = 0;
9206     switch (VT.getSimpleVT().SimpleTy) {
9207       default:
9208         return SDValue();
9209       case MVT::v2i64: {
9210         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9211         SRAIntrinsicsID = 0;
9212         break;
9213       }
9214       case MVT::v4i32: {
9215         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9216         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9217         break;
9218       }
9219       case MVT::v8i16: {
9220         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9221         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9222         break;
9223       }
9224     }
9225
9226     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9227                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9228                          Node->getOperand(0), ShAmt);
9229
9230     // In case of 1 bit sext, no need to shr
9231     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9232
9233     if (SRAIntrinsicsID) {
9234       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9235                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9236                          Tmp1, ShAmt);
9237     }
9238     return Tmp1;
9239   }
9240
9241   return SDValue();
9242 }
9243
9244
9245 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9246   DebugLoc dl = Op.getDebugLoc();
9247
9248   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9249   // There isn't any reason to disable it if the target processor supports it.
9250   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9251     SDValue Chain = Op.getOperand(0);
9252     SDValue Zero = DAG.getConstant(0, MVT::i32);
9253     SDValue Ops[] = {
9254       DAG.getRegister(X86::ESP, MVT::i32), // Base
9255       DAG.getTargetConstant(1, MVT::i8),   // Scale
9256       DAG.getRegister(0, MVT::i32),        // Index
9257       DAG.getTargetConstant(0, MVT::i32),  // Disp
9258       DAG.getRegister(0, MVT::i32),        // Segment.
9259       Zero,
9260       Chain
9261     };
9262     SDNode *Res =
9263       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9264                           array_lengthof(Ops));
9265     return SDValue(Res, 0);
9266   }
9267
9268   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9269   if (!isDev)
9270     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9271
9272   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9273   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9274   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9275   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9276
9277   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9278   if (!Op1 && !Op2 && !Op3 && Op4)
9279     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9280
9281   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9282   if (Op1 && !Op2 && !Op3 && !Op4)
9283     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9284
9285   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9286   //           (MFENCE)>;
9287   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9288 }
9289
9290 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9291   EVT T = Op.getValueType();
9292   DebugLoc DL = Op.getDebugLoc();
9293   unsigned Reg = 0;
9294   unsigned size = 0;
9295   switch(T.getSimpleVT().SimpleTy) {
9296   default:
9297     assert(false && "Invalid value type!");
9298   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9299   case MVT::i16: Reg = X86::AX;  size = 2; break;
9300   case MVT::i32: Reg = X86::EAX; size = 4; break;
9301   case MVT::i64:
9302     assert(Subtarget->is64Bit() && "Node not type legal!");
9303     Reg = X86::RAX; size = 8;
9304     break;
9305   }
9306   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9307                                     Op.getOperand(2), SDValue());
9308   SDValue Ops[] = { cpIn.getValue(0),
9309                     Op.getOperand(1),
9310                     Op.getOperand(3),
9311                     DAG.getTargetConstant(size, MVT::i8),
9312                     cpIn.getValue(1) };
9313   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9314   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9315   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9316                                            Ops, 5, T, MMO);
9317   SDValue cpOut =
9318     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9319   return cpOut;
9320 }
9321
9322 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9323                                                  SelectionDAG &DAG) const {
9324   assert(Subtarget->is64Bit() && "Result not type legalized?");
9325   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9326   SDValue TheChain = Op.getOperand(0);
9327   DebugLoc dl = Op.getDebugLoc();
9328   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9329   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9330   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9331                                    rax.getValue(2));
9332   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9333                             DAG.getConstant(32, MVT::i8));
9334   SDValue Ops[] = {
9335     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9336     rdx.getValue(1)
9337   };
9338   return DAG.getMergeValues(Ops, 2, dl);
9339 }
9340
9341 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9342                                             SelectionDAG &DAG) const {
9343   EVT SrcVT = Op.getOperand(0).getValueType();
9344   EVT DstVT = Op.getValueType();
9345   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9346          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9347   assert((DstVT == MVT::i64 ||
9348           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9349          "Unexpected custom BITCAST");
9350   // i64 <=> MMX conversions are Legal.
9351   if (SrcVT==MVT::i64 && DstVT.isVector())
9352     return Op;
9353   if (DstVT==MVT::i64 && SrcVT.isVector())
9354     return Op;
9355   // MMX <=> MMX conversions are Legal.
9356   if (SrcVT.isVector() && DstVT.isVector())
9357     return Op;
9358   // All other conversions need to be expanded.
9359   return SDValue();
9360 }
9361
9362 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9363   SDNode *Node = Op.getNode();
9364   DebugLoc dl = Node->getDebugLoc();
9365   EVT T = Node->getValueType(0);
9366   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9367                               DAG.getConstant(0, T), Node->getOperand(2));
9368   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9369                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9370                        Node->getOperand(0),
9371                        Node->getOperand(1), negOp,
9372                        cast<AtomicSDNode>(Node)->getSrcValue(),
9373                        cast<AtomicSDNode>(Node)->getAlignment());
9374 }
9375
9376 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9377   EVT VT = Op.getNode()->getValueType(0);
9378
9379   // Let legalize expand this if it isn't a legal type yet.
9380   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9381     return SDValue();
9382
9383   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9384
9385   unsigned Opc;
9386   bool ExtraOp = false;
9387   switch (Op.getOpcode()) {
9388   default: assert(0 && "Invalid code");
9389   case ISD::ADDC: Opc = X86ISD::ADD; break;
9390   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9391   case ISD::SUBC: Opc = X86ISD::SUB; break;
9392   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9393   }
9394
9395   if (!ExtraOp)
9396     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9397                        Op.getOperand(1));
9398   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9399                      Op.getOperand(1), Op.getOperand(2));
9400 }
9401
9402 /// LowerOperation - Provide custom lowering hooks for some operations.
9403 ///
9404 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9405   switch (Op.getOpcode()) {
9406   default: llvm_unreachable("Should not custom lower this!");
9407   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
9408   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9409   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9410   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9411   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9412   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9413   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9414   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9415   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9416   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9417   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9418   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9419   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9420   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9421   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9422   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9423   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9424   case ISD::SHL_PARTS:
9425   case ISD::SRA_PARTS:
9426   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9427   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9428   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9429   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9430   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9431   case ISD::FABS:               return LowerFABS(Op, DAG);
9432   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9433   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9434   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9435   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9436   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9437   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9438   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9439   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9440   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9441   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9442   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9443   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9444   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9445   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9446   case ISD::FRAME_TO_ARGS_OFFSET:
9447                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9448   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9449   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9450   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9451   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9452   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9453   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9454   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9455   case ISD::SRA:
9456   case ISD::SRL:
9457   case ISD::SHL:                return LowerShift(Op, DAG);
9458   case ISD::SADDO:
9459   case ISD::UADDO:
9460   case ISD::SSUBO:
9461   case ISD::USUBO:
9462   case ISD::SMULO:
9463   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9464   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9465   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9466   case ISD::ADDC:
9467   case ISD::ADDE:
9468   case ISD::SUBC:
9469   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9470   }
9471 }
9472
9473 void X86TargetLowering::
9474 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9475                         SelectionDAG &DAG, unsigned NewOp) const {
9476   EVT T = Node->getValueType(0);
9477   DebugLoc dl = Node->getDebugLoc();
9478   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9479
9480   SDValue Chain = Node->getOperand(0);
9481   SDValue In1 = Node->getOperand(1);
9482   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9483                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9484   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9485                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9486   SDValue Ops[] = { Chain, In1, In2L, In2H };
9487   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9488   SDValue Result =
9489     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9490                             cast<MemSDNode>(Node)->getMemOperand());
9491   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9492   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9493   Results.push_back(Result.getValue(2));
9494 }
9495
9496 /// ReplaceNodeResults - Replace a node with an illegal result type
9497 /// with a new node built out of custom code.
9498 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9499                                            SmallVectorImpl<SDValue>&Results,
9500                                            SelectionDAG &DAG) const {
9501   DebugLoc dl = N->getDebugLoc();
9502   switch (N->getOpcode()) {
9503   default:
9504     assert(false && "Do not know how to custom type legalize this operation!");
9505     return;
9506   case ISD::SIGN_EXTEND_INREG:
9507   case ISD::ADDC:
9508   case ISD::ADDE:
9509   case ISD::SUBC:
9510   case ISD::SUBE:
9511     // We don't want to expand or promote these.
9512     return;
9513   case ISD::FP_TO_SINT: {
9514     std::pair<SDValue,SDValue> Vals =
9515         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9516     SDValue FIST = Vals.first, StackSlot = Vals.second;
9517     if (FIST.getNode() != 0) {
9518       EVT VT = N->getValueType(0);
9519       // Return a load from the stack slot.
9520       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9521                                     MachinePointerInfo(), false, false, 0));
9522     }
9523     return;
9524   }
9525   case ISD::READCYCLECOUNTER: {
9526     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9527     SDValue TheChain = N->getOperand(0);
9528     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9529     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9530                                      rd.getValue(1));
9531     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9532                                      eax.getValue(2));
9533     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9534     SDValue Ops[] = { eax, edx };
9535     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9536     Results.push_back(edx.getValue(1));
9537     return;
9538   }
9539   case ISD::ATOMIC_CMP_SWAP: {
9540     EVT T = N->getValueType(0);
9541     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9542     SDValue cpInL, cpInH;
9543     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9544                         DAG.getConstant(0, MVT::i32));
9545     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9546                         DAG.getConstant(1, MVT::i32));
9547     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9548     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9549                              cpInL.getValue(1));
9550     SDValue swapInL, swapInH;
9551     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9552                           DAG.getConstant(0, MVT::i32));
9553     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9554                           DAG.getConstant(1, MVT::i32));
9555     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9556                                cpInH.getValue(1));
9557     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9558                                swapInL.getValue(1));
9559     SDValue Ops[] = { swapInH.getValue(0),
9560                       N->getOperand(1),
9561                       swapInH.getValue(1) };
9562     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9563     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9564     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9565                                              Ops, 3, T, MMO);
9566     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9567                                         MVT::i32, Result.getValue(1));
9568     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9569                                         MVT::i32, cpOutL.getValue(2));
9570     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9571     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9572     Results.push_back(cpOutH.getValue(1));
9573     return;
9574   }
9575   case ISD::ATOMIC_LOAD_ADD:
9576     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9577     return;
9578   case ISD::ATOMIC_LOAD_AND:
9579     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9580     return;
9581   case ISD::ATOMIC_LOAD_NAND:
9582     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9583     return;
9584   case ISD::ATOMIC_LOAD_OR:
9585     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9586     return;
9587   case ISD::ATOMIC_LOAD_SUB:
9588     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9589     return;
9590   case ISD::ATOMIC_LOAD_XOR:
9591     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9592     return;
9593   case ISD::ATOMIC_SWAP:
9594     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9595     return;
9596   }
9597 }
9598
9599 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9600   switch (Opcode) {
9601   default: return NULL;
9602   case X86ISD::BSF:                return "X86ISD::BSF";
9603   case X86ISD::BSR:                return "X86ISD::BSR";
9604   case X86ISD::SHLD:               return "X86ISD::SHLD";
9605   case X86ISD::SHRD:               return "X86ISD::SHRD";
9606   case X86ISD::FAND:               return "X86ISD::FAND";
9607   case X86ISD::FOR:                return "X86ISD::FOR";
9608   case X86ISD::FXOR:               return "X86ISD::FXOR";
9609   case X86ISD::FSRL:               return "X86ISD::FSRL";
9610   case X86ISD::FILD:               return "X86ISD::FILD";
9611   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9612   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9613   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9614   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9615   case X86ISD::FLD:                return "X86ISD::FLD";
9616   case X86ISD::FST:                return "X86ISD::FST";
9617   case X86ISD::CALL:               return "X86ISD::CALL";
9618   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9619   case X86ISD::BT:                 return "X86ISD::BT";
9620   case X86ISD::CMP:                return "X86ISD::CMP";
9621   case X86ISD::COMI:               return "X86ISD::COMI";
9622   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9623   case X86ISD::SETCC:              return "X86ISD::SETCC";
9624   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9625   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9626   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9627   case X86ISD::CMOV:               return "X86ISD::CMOV";
9628   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9629   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9630   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9631   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9632   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9633   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9634   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9635   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9636   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9637   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9638   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9639   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9640   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9641   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9642   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9643   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9644   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9645   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9646   case X86ISD::FMAX:               return "X86ISD::FMAX";
9647   case X86ISD::FMIN:               return "X86ISD::FMIN";
9648   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9649   case X86ISD::FRCP:               return "X86ISD::FRCP";
9650   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9651   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9652   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9653   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9654   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9655   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9656   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9657   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9658   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9659   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9660   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9661   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9662   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9663   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9664   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9665   case X86ISD::VSHL:               return "X86ISD::VSHL";
9666   case X86ISD::VSRL:               return "X86ISD::VSRL";
9667   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9668   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9669   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9670   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9671   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9672   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9673   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9674   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9675   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9676   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9677   case X86ISD::ADD:                return "X86ISD::ADD";
9678   case X86ISD::SUB:                return "X86ISD::SUB";
9679   case X86ISD::ADC:                return "X86ISD::ADC";
9680   case X86ISD::SBB:                return "X86ISD::SBB";
9681   case X86ISD::SMUL:               return "X86ISD::SMUL";
9682   case X86ISD::UMUL:               return "X86ISD::UMUL";
9683   case X86ISD::INC:                return "X86ISD::INC";
9684   case X86ISD::DEC:                return "X86ISD::DEC";
9685   case X86ISD::OR:                 return "X86ISD::OR";
9686   case X86ISD::XOR:                return "X86ISD::XOR";
9687   case X86ISD::AND:                return "X86ISD::AND";
9688   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9689   case X86ISD::PTEST:              return "X86ISD::PTEST";
9690   case X86ISD::TESTP:              return "X86ISD::TESTP";
9691   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9692   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9693   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9694   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9695   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9696   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9697   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9698   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9699   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9700   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9701   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9702   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9703   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9704   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9705   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9706   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9707   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9708   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9709   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9710   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9711   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9712   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9713   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9714   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9715   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9716   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9717   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9718   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9719   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9720   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9721   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9722   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9723   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9724   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9725   case X86ISD::VPERMIL:            return "X86ISD::VPERMIL";
9726   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9727   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9728   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9729   }
9730 }
9731
9732 // isLegalAddressingMode - Return true if the addressing mode represented
9733 // by AM is legal for this target, for a load/store of the specified type.
9734 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9735                                               Type *Ty) const {
9736   // X86 supports extremely general addressing modes.
9737   CodeModel::Model M = getTargetMachine().getCodeModel();
9738   Reloc::Model R = getTargetMachine().getRelocationModel();
9739
9740   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9741   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9742     return false;
9743
9744   if (AM.BaseGV) {
9745     unsigned GVFlags =
9746       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9747
9748     // If a reference to this global requires an extra load, we can't fold it.
9749     if (isGlobalStubReference(GVFlags))
9750       return false;
9751
9752     // If BaseGV requires a register for the PIC base, we cannot also have a
9753     // BaseReg specified.
9754     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9755       return false;
9756
9757     // If lower 4G is not available, then we must use rip-relative addressing.
9758     if ((M != CodeModel::Small || R != Reloc::Static) &&
9759         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9760       return false;
9761   }
9762
9763   switch (AM.Scale) {
9764   case 0:
9765   case 1:
9766   case 2:
9767   case 4:
9768   case 8:
9769     // These scales always work.
9770     break;
9771   case 3:
9772   case 5:
9773   case 9:
9774     // These scales are formed with basereg+scalereg.  Only accept if there is
9775     // no basereg yet.
9776     if (AM.HasBaseReg)
9777       return false;
9778     break;
9779   default:  // Other stuff never works.
9780     return false;
9781   }
9782
9783   return true;
9784 }
9785
9786
9787 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9788   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9789     return false;
9790   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9791   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9792   if (NumBits1 <= NumBits2)
9793     return false;
9794   return true;
9795 }
9796
9797 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9798   if (!VT1.isInteger() || !VT2.isInteger())
9799     return false;
9800   unsigned NumBits1 = VT1.getSizeInBits();
9801   unsigned NumBits2 = VT2.getSizeInBits();
9802   if (NumBits1 <= NumBits2)
9803     return false;
9804   return true;
9805 }
9806
9807 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9808   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9809   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9810 }
9811
9812 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9813   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9814   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9815 }
9816
9817 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9818   // i16 instructions are longer (0x66 prefix) and potentially slower.
9819   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9820 }
9821
9822 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9823 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9824 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9825 /// are assumed to be legal.
9826 bool
9827 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9828                                       EVT VT) const {
9829   // Very little shuffling can be done for 64-bit vectors right now.
9830   if (VT.getSizeInBits() == 64)
9831     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9832
9833   // FIXME: pshufb, blends, shifts.
9834   return (VT.getVectorNumElements() == 2 ||
9835           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9836           isMOVLMask(M, VT) ||
9837           isSHUFPMask(M, VT) ||
9838           isPSHUFDMask(M, VT) ||
9839           isPSHUFHWMask(M, VT) ||
9840           isPSHUFLWMask(M, VT) ||
9841           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9842           isUNPCKLMask(M, VT) ||
9843           isUNPCKHMask(M, VT) ||
9844           isUNPCKL_v_undef_Mask(M, VT) ||
9845           isUNPCKH_v_undef_Mask(M, VT));
9846 }
9847
9848 bool
9849 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9850                                           EVT VT) const {
9851   unsigned NumElts = VT.getVectorNumElements();
9852   // FIXME: This collection of masks seems suspect.
9853   if (NumElts == 2)
9854     return true;
9855   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9856     return (isMOVLMask(Mask, VT)  ||
9857             isCommutedMOVLMask(Mask, VT, true) ||
9858             isSHUFPMask(Mask, VT) ||
9859             isCommutedSHUFPMask(Mask, VT));
9860   }
9861   return false;
9862 }
9863
9864 //===----------------------------------------------------------------------===//
9865 //                           X86 Scheduler Hooks
9866 //===----------------------------------------------------------------------===//
9867
9868 // private utility function
9869 MachineBasicBlock *
9870 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9871                                                        MachineBasicBlock *MBB,
9872                                                        unsigned regOpc,
9873                                                        unsigned immOpc,
9874                                                        unsigned LoadOpc,
9875                                                        unsigned CXchgOpc,
9876                                                        unsigned notOpc,
9877                                                        unsigned EAXreg,
9878                                                        TargetRegisterClass *RC,
9879                                                        bool invSrc) const {
9880   // For the atomic bitwise operator, we generate
9881   //   thisMBB:
9882   //   newMBB:
9883   //     ld  t1 = [bitinstr.addr]
9884   //     op  t2 = t1, [bitinstr.val]
9885   //     mov EAX = t1
9886   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9887   //     bz  newMBB
9888   //     fallthrough -->nextMBB
9889   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9890   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9891   MachineFunction::iterator MBBIter = MBB;
9892   ++MBBIter;
9893
9894   /// First build the CFG
9895   MachineFunction *F = MBB->getParent();
9896   MachineBasicBlock *thisMBB = MBB;
9897   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9898   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9899   F->insert(MBBIter, newMBB);
9900   F->insert(MBBIter, nextMBB);
9901
9902   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9903   nextMBB->splice(nextMBB->begin(), thisMBB,
9904                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9905                   thisMBB->end());
9906   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9907
9908   // Update thisMBB to fall through to newMBB
9909   thisMBB->addSuccessor(newMBB);
9910
9911   // newMBB jumps to itself and fall through to nextMBB
9912   newMBB->addSuccessor(nextMBB);
9913   newMBB->addSuccessor(newMBB);
9914
9915   // Insert instructions into newMBB based on incoming instruction
9916   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9917          "unexpected number of operands");
9918   DebugLoc dl = bInstr->getDebugLoc();
9919   MachineOperand& destOper = bInstr->getOperand(0);
9920   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9921   int numArgs = bInstr->getNumOperands() - 1;
9922   for (int i=0; i < numArgs; ++i)
9923     argOpers[i] = &bInstr->getOperand(i+1);
9924
9925   // x86 address has 4 operands: base, index, scale, and displacement
9926   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9927   int valArgIndx = lastAddrIndx + 1;
9928
9929   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9930   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9931   for (int i=0; i <= lastAddrIndx; ++i)
9932     (*MIB).addOperand(*argOpers[i]);
9933
9934   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9935   if (invSrc) {
9936     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9937   }
9938   else
9939     tt = t1;
9940
9941   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9942   assert((argOpers[valArgIndx]->isReg() ||
9943           argOpers[valArgIndx]->isImm()) &&
9944          "invalid operand");
9945   if (argOpers[valArgIndx]->isReg())
9946     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9947   else
9948     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9949   MIB.addReg(tt);
9950   (*MIB).addOperand(*argOpers[valArgIndx]);
9951
9952   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9953   MIB.addReg(t1);
9954
9955   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9956   for (int i=0; i <= lastAddrIndx; ++i)
9957     (*MIB).addOperand(*argOpers[i]);
9958   MIB.addReg(t2);
9959   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9960   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9961                     bInstr->memoperands_end());
9962
9963   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9964   MIB.addReg(EAXreg);
9965
9966   // insert branch
9967   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9968
9969   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9970   return nextMBB;
9971 }
9972
9973 // private utility function:  64 bit atomics on 32 bit host.
9974 MachineBasicBlock *
9975 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9976                                                        MachineBasicBlock *MBB,
9977                                                        unsigned regOpcL,
9978                                                        unsigned regOpcH,
9979                                                        unsigned immOpcL,
9980                                                        unsigned immOpcH,
9981                                                        bool invSrc) const {
9982   // For the atomic bitwise operator, we generate
9983   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9984   //     ld t1,t2 = [bitinstr.addr]
9985   //   newMBB:
9986   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9987   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9988   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9989   //     mov ECX, EBX <- t5, t6
9990   //     mov EAX, EDX <- t1, t2
9991   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9992   //     mov t3, t4 <- EAX, EDX
9993   //     bz  newMBB
9994   //     result in out1, out2
9995   //     fallthrough -->nextMBB
9996
9997   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9998   const unsigned LoadOpc = X86::MOV32rm;
9999   const unsigned NotOpc = X86::NOT32r;
10000   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10001   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10002   MachineFunction::iterator MBBIter = MBB;
10003   ++MBBIter;
10004
10005   /// First build the CFG
10006   MachineFunction *F = MBB->getParent();
10007   MachineBasicBlock *thisMBB = MBB;
10008   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10009   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10010   F->insert(MBBIter, newMBB);
10011   F->insert(MBBIter, nextMBB);
10012
10013   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10014   nextMBB->splice(nextMBB->begin(), thisMBB,
10015                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10016                   thisMBB->end());
10017   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10018
10019   // Update thisMBB to fall through to newMBB
10020   thisMBB->addSuccessor(newMBB);
10021
10022   // newMBB jumps to itself and fall through to nextMBB
10023   newMBB->addSuccessor(nextMBB);
10024   newMBB->addSuccessor(newMBB);
10025
10026   DebugLoc dl = bInstr->getDebugLoc();
10027   // Insert instructions into newMBB based on incoming instruction
10028   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10029   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10030          "unexpected number of operands");
10031   MachineOperand& dest1Oper = bInstr->getOperand(0);
10032   MachineOperand& dest2Oper = bInstr->getOperand(1);
10033   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10034   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10035     argOpers[i] = &bInstr->getOperand(i+2);
10036
10037     // We use some of the operands multiple times, so conservatively just
10038     // clear any kill flags that might be present.
10039     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10040       argOpers[i]->setIsKill(false);
10041   }
10042
10043   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10044   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10045
10046   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10047   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10048   for (int i=0; i <= lastAddrIndx; ++i)
10049     (*MIB).addOperand(*argOpers[i]);
10050   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10051   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10052   // add 4 to displacement.
10053   for (int i=0; i <= lastAddrIndx-2; ++i)
10054     (*MIB).addOperand(*argOpers[i]);
10055   MachineOperand newOp3 = *(argOpers[3]);
10056   if (newOp3.isImm())
10057     newOp3.setImm(newOp3.getImm()+4);
10058   else
10059     newOp3.setOffset(newOp3.getOffset()+4);
10060   (*MIB).addOperand(newOp3);
10061   (*MIB).addOperand(*argOpers[lastAddrIndx]);
10062
10063   // t3/4 are defined later, at the bottom of the loop
10064   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10065   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10066   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10067     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10068   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10069     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10070
10071   // The subsequent operations should be using the destination registers of
10072   //the PHI instructions.
10073   if (invSrc) {
10074     t1 = F->getRegInfo().createVirtualRegister(RC);
10075     t2 = F->getRegInfo().createVirtualRegister(RC);
10076     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10077     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10078   } else {
10079     t1 = dest1Oper.getReg();
10080     t2 = dest2Oper.getReg();
10081   }
10082
10083   int valArgIndx = lastAddrIndx + 1;
10084   assert((argOpers[valArgIndx]->isReg() ||
10085           argOpers[valArgIndx]->isImm()) &&
10086          "invalid operand");
10087   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10088   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10089   if (argOpers[valArgIndx]->isReg())
10090     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10091   else
10092     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10093   if (regOpcL != X86::MOV32rr)
10094     MIB.addReg(t1);
10095   (*MIB).addOperand(*argOpers[valArgIndx]);
10096   assert(argOpers[valArgIndx + 1]->isReg() ==
10097          argOpers[valArgIndx]->isReg());
10098   assert(argOpers[valArgIndx + 1]->isImm() ==
10099          argOpers[valArgIndx]->isImm());
10100   if (argOpers[valArgIndx + 1]->isReg())
10101     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10102   else
10103     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10104   if (regOpcH != X86::MOV32rr)
10105     MIB.addReg(t2);
10106   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10107
10108   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10109   MIB.addReg(t1);
10110   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10111   MIB.addReg(t2);
10112
10113   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10114   MIB.addReg(t5);
10115   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10116   MIB.addReg(t6);
10117
10118   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10119   for (int i=0; i <= lastAddrIndx; ++i)
10120     (*MIB).addOperand(*argOpers[i]);
10121
10122   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10123   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10124                     bInstr->memoperands_end());
10125
10126   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10127   MIB.addReg(X86::EAX);
10128   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10129   MIB.addReg(X86::EDX);
10130
10131   // insert branch
10132   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10133
10134   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10135   return nextMBB;
10136 }
10137
10138 // private utility function
10139 MachineBasicBlock *
10140 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10141                                                       MachineBasicBlock *MBB,
10142                                                       unsigned cmovOpc) const {
10143   // For the atomic min/max operator, we generate
10144   //   thisMBB:
10145   //   newMBB:
10146   //     ld t1 = [min/max.addr]
10147   //     mov t2 = [min/max.val]
10148   //     cmp  t1, t2
10149   //     cmov[cond] t2 = t1
10150   //     mov EAX = t1
10151   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10152   //     bz   newMBB
10153   //     fallthrough -->nextMBB
10154   //
10155   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10156   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10157   MachineFunction::iterator MBBIter = MBB;
10158   ++MBBIter;
10159
10160   /// First build the CFG
10161   MachineFunction *F = MBB->getParent();
10162   MachineBasicBlock *thisMBB = MBB;
10163   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10164   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10165   F->insert(MBBIter, newMBB);
10166   F->insert(MBBIter, nextMBB);
10167
10168   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10169   nextMBB->splice(nextMBB->begin(), thisMBB,
10170                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10171                   thisMBB->end());
10172   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10173
10174   // Update thisMBB to fall through to newMBB
10175   thisMBB->addSuccessor(newMBB);
10176
10177   // newMBB jumps to newMBB and fall through to nextMBB
10178   newMBB->addSuccessor(nextMBB);
10179   newMBB->addSuccessor(newMBB);
10180
10181   DebugLoc dl = mInstr->getDebugLoc();
10182   // Insert instructions into newMBB based on incoming instruction
10183   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10184          "unexpected number of operands");
10185   MachineOperand& destOper = mInstr->getOperand(0);
10186   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10187   int numArgs = mInstr->getNumOperands() - 1;
10188   for (int i=0; i < numArgs; ++i)
10189     argOpers[i] = &mInstr->getOperand(i+1);
10190
10191   // x86 address has 4 operands: base, index, scale, and displacement
10192   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10193   int valArgIndx = lastAddrIndx + 1;
10194
10195   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10196   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10197   for (int i=0; i <= lastAddrIndx; ++i)
10198     (*MIB).addOperand(*argOpers[i]);
10199
10200   // We only support register and immediate values
10201   assert((argOpers[valArgIndx]->isReg() ||
10202           argOpers[valArgIndx]->isImm()) &&
10203          "invalid operand");
10204
10205   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10206   if (argOpers[valArgIndx]->isReg())
10207     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10208   else
10209     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10210   (*MIB).addOperand(*argOpers[valArgIndx]);
10211
10212   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10213   MIB.addReg(t1);
10214
10215   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10216   MIB.addReg(t1);
10217   MIB.addReg(t2);
10218
10219   // Generate movc
10220   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10221   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10222   MIB.addReg(t2);
10223   MIB.addReg(t1);
10224
10225   // Cmp and exchange if none has modified the memory location
10226   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10227   for (int i=0; i <= lastAddrIndx; ++i)
10228     (*MIB).addOperand(*argOpers[i]);
10229   MIB.addReg(t3);
10230   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10231   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10232                     mInstr->memoperands_end());
10233
10234   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10235   MIB.addReg(X86::EAX);
10236
10237   // insert branch
10238   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10239
10240   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10241   return nextMBB;
10242 }
10243
10244 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10245 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10246 // in the .td file.
10247 MachineBasicBlock *
10248 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10249                             unsigned numArgs, bool memArg) const {
10250   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10251          "Target must have SSE4.2 or AVX features enabled");
10252
10253   DebugLoc dl = MI->getDebugLoc();
10254   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10255   unsigned Opc;
10256   if (!Subtarget->hasAVX()) {
10257     if (memArg)
10258       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10259     else
10260       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10261   } else {
10262     if (memArg)
10263       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10264     else
10265       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10266   }
10267
10268   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10269   for (unsigned i = 0; i < numArgs; ++i) {
10270     MachineOperand &Op = MI->getOperand(i+1);
10271     if (!(Op.isReg() && Op.isImplicit()))
10272       MIB.addOperand(Op);
10273   }
10274   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10275     .addReg(X86::XMM0);
10276
10277   MI->eraseFromParent();
10278   return BB;
10279 }
10280
10281 MachineBasicBlock *
10282 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10283   DebugLoc dl = MI->getDebugLoc();
10284   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10285
10286   // Address into RAX/EAX, other two args into ECX, EDX.
10287   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10288   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10289   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10290   for (int i = 0; i < X86::AddrNumOperands; ++i)
10291     MIB.addOperand(MI->getOperand(i));
10292
10293   unsigned ValOps = X86::AddrNumOperands;
10294   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10295     .addReg(MI->getOperand(ValOps).getReg());
10296   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10297     .addReg(MI->getOperand(ValOps+1).getReg());
10298
10299   // The instruction doesn't actually take any operands though.
10300   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10301
10302   MI->eraseFromParent(); // The pseudo is gone now.
10303   return BB;
10304 }
10305
10306 MachineBasicBlock *
10307 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10308   DebugLoc dl = MI->getDebugLoc();
10309   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10310
10311   // First arg in ECX, the second in EAX.
10312   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10313     .addReg(MI->getOperand(0).getReg());
10314   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10315     .addReg(MI->getOperand(1).getReg());
10316
10317   // The instruction doesn't actually take any operands though.
10318   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10319
10320   MI->eraseFromParent(); // The pseudo is gone now.
10321   return BB;
10322 }
10323
10324 MachineBasicBlock *
10325 X86TargetLowering::EmitVAARG64WithCustomInserter(
10326                    MachineInstr *MI,
10327                    MachineBasicBlock *MBB) const {
10328   // Emit va_arg instruction on X86-64.
10329
10330   // Operands to this pseudo-instruction:
10331   // 0  ) Output        : destination address (reg)
10332   // 1-5) Input         : va_list address (addr, i64mem)
10333   // 6  ) ArgSize       : Size (in bytes) of vararg type
10334   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10335   // 8  ) Align         : Alignment of type
10336   // 9  ) EFLAGS (implicit-def)
10337
10338   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10339   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10340
10341   unsigned DestReg = MI->getOperand(0).getReg();
10342   MachineOperand &Base = MI->getOperand(1);
10343   MachineOperand &Scale = MI->getOperand(2);
10344   MachineOperand &Index = MI->getOperand(3);
10345   MachineOperand &Disp = MI->getOperand(4);
10346   MachineOperand &Segment = MI->getOperand(5);
10347   unsigned ArgSize = MI->getOperand(6).getImm();
10348   unsigned ArgMode = MI->getOperand(7).getImm();
10349   unsigned Align = MI->getOperand(8).getImm();
10350
10351   // Memory Reference
10352   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10353   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10354   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10355
10356   // Machine Information
10357   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10358   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10359   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10360   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10361   DebugLoc DL = MI->getDebugLoc();
10362
10363   // struct va_list {
10364   //   i32   gp_offset
10365   //   i32   fp_offset
10366   //   i64   overflow_area (address)
10367   //   i64   reg_save_area (address)
10368   // }
10369   // sizeof(va_list) = 24
10370   // alignment(va_list) = 8
10371
10372   unsigned TotalNumIntRegs = 6;
10373   unsigned TotalNumXMMRegs = 8;
10374   bool UseGPOffset = (ArgMode == 1);
10375   bool UseFPOffset = (ArgMode == 2);
10376   unsigned MaxOffset = TotalNumIntRegs * 8 +
10377                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10378
10379   /* Align ArgSize to a multiple of 8 */
10380   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10381   bool NeedsAlign = (Align > 8);
10382
10383   MachineBasicBlock *thisMBB = MBB;
10384   MachineBasicBlock *overflowMBB;
10385   MachineBasicBlock *offsetMBB;
10386   MachineBasicBlock *endMBB;
10387
10388   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10389   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10390   unsigned OffsetReg = 0;
10391
10392   if (!UseGPOffset && !UseFPOffset) {
10393     // If we only pull from the overflow region, we don't create a branch.
10394     // We don't need to alter control flow.
10395     OffsetDestReg = 0; // unused
10396     OverflowDestReg = DestReg;
10397
10398     offsetMBB = NULL;
10399     overflowMBB = thisMBB;
10400     endMBB = thisMBB;
10401   } else {
10402     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10403     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10404     // If not, pull from overflow_area. (branch to overflowMBB)
10405     //
10406     //       thisMBB
10407     //         |     .
10408     //         |        .
10409     //     offsetMBB   overflowMBB
10410     //         |        .
10411     //         |     .
10412     //        endMBB
10413
10414     // Registers for the PHI in endMBB
10415     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10416     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10417
10418     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10419     MachineFunction *MF = MBB->getParent();
10420     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10421     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10422     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10423
10424     MachineFunction::iterator MBBIter = MBB;
10425     ++MBBIter;
10426
10427     // Insert the new basic blocks
10428     MF->insert(MBBIter, offsetMBB);
10429     MF->insert(MBBIter, overflowMBB);
10430     MF->insert(MBBIter, endMBB);
10431
10432     // Transfer the remainder of MBB and its successor edges to endMBB.
10433     endMBB->splice(endMBB->begin(), thisMBB,
10434                     llvm::next(MachineBasicBlock::iterator(MI)),
10435                     thisMBB->end());
10436     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10437
10438     // Make offsetMBB and overflowMBB successors of thisMBB
10439     thisMBB->addSuccessor(offsetMBB);
10440     thisMBB->addSuccessor(overflowMBB);
10441
10442     // endMBB is a successor of both offsetMBB and overflowMBB
10443     offsetMBB->addSuccessor(endMBB);
10444     overflowMBB->addSuccessor(endMBB);
10445
10446     // Load the offset value into a register
10447     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10448     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10449       .addOperand(Base)
10450       .addOperand(Scale)
10451       .addOperand(Index)
10452       .addDisp(Disp, UseFPOffset ? 4 : 0)
10453       .addOperand(Segment)
10454       .setMemRefs(MMOBegin, MMOEnd);
10455
10456     // Check if there is enough room left to pull this argument.
10457     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10458       .addReg(OffsetReg)
10459       .addImm(MaxOffset + 8 - ArgSizeA8);
10460
10461     // Branch to "overflowMBB" if offset >= max
10462     // Fall through to "offsetMBB" otherwise
10463     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10464       .addMBB(overflowMBB);
10465   }
10466
10467   // In offsetMBB, emit code to use the reg_save_area.
10468   if (offsetMBB) {
10469     assert(OffsetReg != 0);
10470
10471     // Read the reg_save_area address.
10472     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10473     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10474       .addOperand(Base)
10475       .addOperand(Scale)
10476       .addOperand(Index)
10477       .addDisp(Disp, 16)
10478       .addOperand(Segment)
10479       .setMemRefs(MMOBegin, MMOEnd);
10480
10481     // Zero-extend the offset
10482     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10483       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10484         .addImm(0)
10485         .addReg(OffsetReg)
10486         .addImm(X86::sub_32bit);
10487
10488     // Add the offset to the reg_save_area to get the final address.
10489     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10490       .addReg(OffsetReg64)
10491       .addReg(RegSaveReg);
10492
10493     // Compute the offset for the next argument
10494     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10495     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10496       .addReg(OffsetReg)
10497       .addImm(UseFPOffset ? 16 : 8);
10498
10499     // Store it back into the va_list.
10500     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10501       .addOperand(Base)
10502       .addOperand(Scale)
10503       .addOperand(Index)
10504       .addDisp(Disp, UseFPOffset ? 4 : 0)
10505       .addOperand(Segment)
10506       .addReg(NextOffsetReg)
10507       .setMemRefs(MMOBegin, MMOEnd);
10508
10509     // Jump to endMBB
10510     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10511       .addMBB(endMBB);
10512   }
10513
10514   //
10515   // Emit code to use overflow area
10516   //
10517
10518   // Load the overflow_area address into a register.
10519   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10520   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10521     .addOperand(Base)
10522     .addOperand(Scale)
10523     .addOperand(Index)
10524     .addDisp(Disp, 8)
10525     .addOperand(Segment)
10526     .setMemRefs(MMOBegin, MMOEnd);
10527
10528   // If we need to align it, do so. Otherwise, just copy the address
10529   // to OverflowDestReg.
10530   if (NeedsAlign) {
10531     // Align the overflow address
10532     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10533     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10534
10535     // aligned_addr = (addr + (align-1)) & ~(align-1)
10536     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10537       .addReg(OverflowAddrReg)
10538       .addImm(Align-1);
10539
10540     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10541       .addReg(TmpReg)
10542       .addImm(~(uint64_t)(Align-1));
10543   } else {
10544     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10545       .addReg(OverflowAddrReg);
10546   }
10547
10548   // Compute the next overflow address after this argument.
10549   // (the overflow address should be kept 8-byte aligned)
10550   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10551   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10552     .addReg(OverflowDestReg)
10553     .addImm(ArgSizeA8);
10554
10555   // Store the new overflow address.
10556   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10557     .addOperand(Base)
10558     .addOperand(Scale)
10559     .addOperand(Index)
10560     .addDisp(Disp, 8)
10561     .addOperand(Segment)
10562     .addReg(NextAddrReg)
10563     .setMemRefs(MMOBegin, MMOEnd);
10564
10565   // If we branched, emit the PHI to the front of endMBB.
10566   if (offsetMBB) {
10567     BuildMI(*endMBB, endMBB->begin(), DL,
10568             TII->get(X86::PHI), DestReg)
10569       .addReg(OffsetDestReg).addMBB(offsetMBB)
10570       .addReg(OverflowDestReg).addMBB(overflowMBB);
10571   }
10572
10573   // Erase the pseudo instruction
10574   MI->eraseFromParent();
10575
10576   return endMBB;
10577 }
10578
10579 MachineBasicBlock *
10580 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10581                                                  MachineInstr *MI,
10582                                                  MachineBasicBlock *MBB) const {
10583   // Emit code to save XMM registers to the stack. The ABI says that the
10584   // number of registers to save is given in %al, so it's theoretically
10585   // possible to do an indirect jump trick to avoid saving all of them,
10586   // however this code takes a simpler approach and just executes all
10587   // of the stores if %al is non-zero. It's less code, and it's probably
10588   // easier on the hardware branch predictor, and stores aren't all that
10589   // expensive anyway.
10590
10591   // Create the new basic blocks. One block contains all the XMM stores,
10592   // and one block is the final destination regardless of whether any
10593   // stores were performed.
10594   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10595   MachineFunction *F = MBB->getParent();
10596   MachineFunction::iterator MBBIter = MBB;
10597   ++MBBIter;
10598   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10599   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10600   F->insert(MBBIter, XMMSaveMBB);
10601   F->insert(MBBIter, EndMBB);
10602
10603   // Transfer the remainder of MBB and its successor edges to EndMBB.
10604   EndMBB->splice(EndMBB->begin(), MBB,
10605                  llvm::next(MachineBasicBlock::iterator(MI)),
10606                  MBB->end());
10607   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10608
10609   // The original block will now fall through to the XMM save block.
10610   MBB->addSuccessor(XMMSaveMBB);
10611   // The XMMSaveMBB will fall through to the end block.
10612   XMMSaveMBB->addSuccessor(EndMBB);
10613
10614   // Now add the instructions.
10615   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10616   DebugLoc DL = MI->getDebugLoc();
10617
10618   unsigned CountReg = MI->getOperand(0).getReg();
10619   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10620   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10621
10622   if (!Subtarget->isTargetWin64()) {
10623     // If %al is 0, branch around the XMM save block.
10624     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10625     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10626     MBB->addSuccessor(EndMBB);
10627   }
10628
10629   // In the XMM save block, save all the XMM argument registers.
10630   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10631     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10632     MachineMemOperand *MMO =
10633       F->getMachineMemOperand(
10634           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10635         MachineMemOperand::MOStore,
10636         /*Size=*/16, /*Align=*/16);
10637     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10638       .addFrameIndex(RegSaveFrameIndex)
10639       .addImm(/*Scale=*/1)
10640       .addReg(/*IndexReg=*/0)
10641       .addImm(/*Disp=*/Offset)
10642       .addReg(/*Segment=*/0)
10643       .addReg(MI->getOperand(i).getReg())
10644       .addMemOperand(MMO);
10645   }
10646
10647   MI->eraseFromParent();   // The pseudo instruction is gone now.
10648
10649   return EndMBB;
10650 }
10651
10652 MachineBasicBlock *
10653 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10654                                      MachineBasicBlock *BB) const {
10655   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10656   DebugLoc DL = MI->getDebugLoc();
10657
10658   // To "insert" a SELECT_CC instruction, we actually have to insert the
10659   // diamond control-flow pattern.  The incoming instruction knows the
10660   // destination vreg to set, the condition code register to branch on, the
10661   // true/false values to select between, and a branch opcode to use.
10662   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10663   MachineFunction::iterator It = BB;
10664   ++It;
10665
10666   //  thisMBB:
10667   //  ...
10668   //   TrueVal = ...
10669   //   cmpTY ccX, r1, r2
10670   //   bCC copy1MBB
10671   //   fallthrough --> copy0MBB
10672   MachineBasicBlock *thisMBB = BB;
10673   MachineFunction *F = BB->getParent();
10674   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10675   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10676   F->insert(It, copy0MBB);
10677   F->insert(It, sinkMBB);
10678
10679   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10680   // live into the sink and copy blocks.
10681   const MachineFunction *MF = BB->getParent();
10682   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10683   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10684
10685   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10686     const MachineOperand &MO = MI->getOperand(I);
10687     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10688     unsigned Reg = MO.getReg();
10689     if (Reg != X86::EFLAGS) continue;
10690     copy0MBB->addLiveIn(Reg);
10691     sinkMBB->addLiveIn(Reg);
10692   }
10693
10694   // Transfer the remainder of BB and its successor edges to sinkMBB.
10695   sinkMBB->splice(sinkMBB->begin(), BB,
10696                   llvm::next(MachineBasicBlock::iterator(MI)),
10697                   BB->end());
10698   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10699
10700   // Add the true and fallthrough blocks as its successors.
10701   BB->addSuccessor(copy0MBB);
10702   BB->addSuccessor(sinkMBB);
10703
10704   // Create the conditional branch instruction.
10705   unsigned Opc =
10706     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10707   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10708
10709   //  copy0MBB:
10710   //   %FalseValue = ...
10711   //   # fallthrough to sinkMBB
10712   copy0MBB->addSuccessor(sinkMBB);
10713
10714   //  sinkMBB:
10715   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10716   //  ...
10717   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10718           TII->get(X86::PHI), MI->getOperand(0).getReg())
10719     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10720     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10721
10722   MI->eraseFromParent();   // The pseudo instruction is gone now.
10723   return sinkMBB;
10724 }
10725
10726 MachineBasicBlock *
10727 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10728                                           MachineBasicBlock *BB) const {
10729   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10730   DebugLoc DL = MI->getDebugLoc();
10731
10732   assert(!Subtarget->isTargetEnvMacho());
10733
10734   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10735   // non-trivial part is impdef of ESP.
10736
10737   if (Subtarget->isTargetWin64()) {
10738     if (Subtarget->isTargetCygMing()) {
10739       // ___chkstk(Mingw64):
10740       // Clobbers R10, R11, RAX and EFLAGS.
10741       // Updates RSP.
10742       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10743         .addExternalSymbol("___chkstk")
10744         .addReg(X86::RAX, RegState::Implicit)
10745         .addReg(X86::RSP, RegState::Implicit)
10746         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10747         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10748         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10749     } else {
10750       // __chkstk(MSVCRT): does not update stack pointer.
10751       // Clobbers R10, R11 and EFLAGS.
10752       // FIXME: RAX(allocated size) might be reused and not killed.
10753       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10754         .addExternalSymbol("__chkstk")
10755         .addReg(X86::RAX, RegState::Implicit)
10756         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10757       // RAX has the offset to subtracted from RSP.
10758       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10759         .addReg(X86::RSP)
10760         .addReg(X86::RAX);
10761     }
10762   } else {
10763     const char *StackProbeSymbol =
10764       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10765
10766     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10767       .addExternalSymbol(StackProbeSymbol)
10768       .addReg(X86::EAX, RegState::Implicit)
10769       .addReg(X86::ESP, RegState::Implicit)
10770       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10771       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10772       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10773   }
10774
10775   MI->eraseFromParent();   // The pseudo instruction is gone now.
10776   return BB;
10777 }
10778
10779 MachineBasicBlock *
10780 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10781                                       MachineBasicBlock *BB) const {
10782   // This is pretty easy.  We're taking the value that we received from
10783   // our load from the relocation, sticking it in either RDI (x86-64)
10784   // or EAX and doing an indirect call.  The return value will then
10785   // be in the normal return register.
10786   const X86InstrInfo *TII
10787     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10788   DebugLoc DL = MI->getDebugLoc();
10789   MachineFunction *F = BB->getParent();
10790
10791   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10792   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10793
10794   if (Subtarget->is64Bit()) {
10795     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10796                                       TII->get(X86::MOV64rm), X86::RDI)
10797     .addReg(X86::RIP)
10798     .addImm(0).addReg(0)
10799     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10800                       MI->getOperand(3).getTargetFlags())
10801     .addReg(0);
10802     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10803     addDirectMem(MIB, X86::RDI);
10804   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10805     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10806                                       TII->get(X86::MOV32rm), X86::EAX)
10807     .addReg(0)
10808     .addImm(0).addReg(0)
10809     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10810                       MI->getOperand(3).getTargetFlags())
10811     .addReg(0);
10812     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10813     addDirectMem(MIB, X86::EAX);
10814   } else {
10815     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10816                                       TII->get(X86::MOV32rm), X86::EAX)
10817     .addReg(TII->getGlobalBaseReg(F))
10818     .addImm(0).addReg(0)
10819     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10820                       MI->getOperand(3).getTargetFlags())
10821     .addReg(0);
10822     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10823     addDirectMem(MIB, X86::EAX);
10824   }
10825
10826   MI->eraseFromParent(); // The pseudo instruction is gone now.
10827   return BB;
10828 }
10829
10830 MachineBasicBlock *
10831 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10832                                                MachineBasicBlock *BB) const {
10833   switch (MI->getOpcode()) {
10834   default: assert(false && "Unexpected instr type to insert");
10835   case X86::TAILJMPd64:
10836   case X86::TAILJMPr64:
10837   case X86::TAILJMPm64:
10838     assert(!"TAILJMP64 would not be touched here.");
10839   case X86::TCRETURNdi64:
10840   case X86::TCRETURNri64:
10841   case X86::TCRETURNmi64:
10842     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10843     // On AMD64, additional defs should be added before register allocation.
10844     if (!Subtarget->isTargetWin64()) {
10845       MI->addRegisterDefined(X86::RSI);
10846       MI->addRegisterDefined(X86::RDI);
10847       MI->addRegisterDefined(X86::XMM6);
10848       MI->addRegisterDefined(X86::XMM7);
10849       MI->addRegisterDefined(X86::XMM8);
10850       MI->addRegisterDefined(X86::XMM9);
10851       MI->addRegisterDefined(X86::XMM10);
10852       MI->addRegisterDefined(X86::XMM11);
10853       MI->addRegisterDefined(X86::XMM12);
10854       MI->addRegisterDefined(X86::XMM13);
10855       MI->addRegisterDefined(X86::XMM14);
10856       MI->addRegisterDefined(X86::XMM15);
10857     }
10858     return BB;
10859   case X86::WIN_ALLOCA:
10860     return EmitLoweredWinAlloca(MI, BB);
10861   case X86::TLSCall_32:
10862   case X86::TLSCall_64:
10863     return EmitLoweredTLSCall(MI, BB);
10864   case X86::CMOV_GR8:
10865   case X86::CMOV_FR32:
10866   case X86::CMOV_FR64:
10867   case X86::CMOV_V4F32:
10868   case X86::CMOV_V2F64:
10869   case X86::CMOV_V2I64:
10870   case X86::CMOV_GR16:
10871   case X86::CMOV_GR32:
10872   case X86::CMOV_RFP32:
10873   case X86::CMOV_RFP64:
10874   case X86::CMOV_RFP80:
10875     return EmitLoweredSelect(MI, BB);
10876
10877   case X86::FP32_TO_INT16_IN_MEM:
10878   case X86::FP32_TO_INT32_IN_MEM:
10879   case X86::FP32_TO_INT64_IN_MEM:
10880   case X86::FP64_TO_INT16_IN_MEM:
10881   case X86::FP64_TO_INT32_IN_MEM:
10882   case X86::FP64_TO_INT64_IN_MEM:
10883   case X86::FP80_TO_INT16_IN_MEM:
10884   case X86::FP80_TO_INT32_IN_MEM:
10885   case X86::FP80_TO_INT64_IN_MEM: {
10886     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10887     DebugLoc DL = MI->getDebugLoc();
10888
10889     // Change the floating point control register to use "round towards zero"
10890     // mode when truncating to an integer value.
10891     MachineFunction *F = BB->getParent();
10892     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10893     addFrameReference(BuildMI(*BB, MI, DL,
10894                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10895
10896     // Load the old value of the high byte of the control word...
10897     unsigned OldCW =
10898       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10899     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10900                       CWFrameIdx);
10901
10902     // Set the high part to be round to zero...
10903     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10904       .addImm(0xC7F);
10905
10906     // Reload the modified control word now...
10907     addFrameReference(BuildMI(*BB, MI, DL,
10908                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10909
10910     // Restore the memory image of control word to original value
10911     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10912       .addReg(OldCW);
10913
10914     // Get the X86 opcode to use.
10915     unsigned Opc;
10916     switch (MI->getOpcode()) {
10917     default: llvm_unreachable("illegal opcode!");
10918     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10919     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10920     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10921     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10922     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10923     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10924     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10925     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10926     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10927     }
10928
10929     X86AddressMode AM;
10930     MachineOperand &Op = MI->getOperand(0);
10931     if (Op.isReg()) {
10932       AM.BaseType = X86AddressMode::RegBase;
10933       AM.Base.Reg = Op.getReg();
10934     } else {
10935       AM.BaseType = X86AddressMode::FrameIndexBase;
10936       AM.Base.FrameIndex = Op.getIndex();
10937     }
10938     Op = MI->getOperand(1);
10939     if (Op.isImm())
10940       AM.Scale = Op.getImm();
10941     Op = MI->getOperand(2);
10942     if (Op.isImm())
10943       AM.IndexReg = Op.getImm();
10944     Op = MI->getOperand(3);
10945     if (Op.isGlobal()) {
10946       AM.GV = Op.getGlobal();
10947     } else {
10948       AM.Disp = Op.getImm();
10949     }
10950     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10951                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10952
10953     // Reload the original control word now.
10954     addFrameReference(BuildMI(*BB, MI, DL,
10955                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10956
10957     MI->eraseFromParent();   // The pseudo instruction is gone now.
10958     return BB;
10959   }
10960     // String/text processing lowering.
10961   case X86::PCMPISTRM128REG:
10962   case X86::VPCMPISTRM128REG:
10963     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10964   case X86::PCMPISTRM128MEM:
10965   case X86::VPCMPISTRM128MEM:
10966     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10967   case X86::PCMPESTRM128REG:
10968   case X86::VPCMPESTRM128REG:
10969     return EmitPCMP(MI, BB, 5, false /* in mem */);
10970   case X86::PCMPESTRM128MEM:
10971   case X86::VPCMPESTRM128MEM:
10972     return EmitPCMP(MI, BB, 5, true /* in mem */);
10973
10974     // Thread synchronization.
10975   case X86::MONITOR:
10976     return EmitMonitor(MI, BB);
10977   case X86::MWAIT:
10978     return EmitMwait(MI, BB);
10979
10980     // Atomic Lowering.
10981   case X86::ATOMAND32:
10982     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10983                                                X86::AND32ri, X86::MOV32rm,
10984                                                X86::LCMPXCHG32,
10985                                                X86::NOT32r, X86::EAX,
10986                                                X86::GR32RegisterClass);
10987   case X86::ATOMOR32:
10988     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10989                                                X86::OR32ri, X86::MOV32rm,
10990                                                X86::LCMPXCHG32,
10991                                                X86::NOT32r, X86::EAX,
10992                                                X86::GR32RegisterClass);
10993   case X86::ATOMXOR32:
10994     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10995                                                X86::XOR32ri, X86::MOV32rm,
10996                                                X86::LCMPXCHG32,
10997                                                X86::NOT32r, X86::EAX,
10998                                                X86::GR32RegisterClass);
10999   case X86::ATOMNAND32:
11000     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11001                                                X86::AND32ri, X86::MOV32rm,
11002                                                X86::LCMPXCHG32,
11003                                                X86::NOT32r, X86::EAX,
11004                                                X86::GR32RegisterClass, true);
11005   case X86::ATOMMIN32:
11006     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11007   case X86::ATOMMAX32:
11008     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11009   case X86::ATOMUMIN32:
11010     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11011   case X86::ATOMUMAX32:
11012     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11013
11014   case X86::ATOMAND16:
11015     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11016                                                X86::AND16ri, X86::MOV16rm,
11017                                                X86::LCMPXCHG16,
11018                                                X86::NOT16r, X86::AX,
11019                                                X86::GR16RegisterClass);
11020   case X86::ATOMOR16:
11021     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11022                                                X86::OR16ri, X86::MOV16rm,
11023                                                X86::LCMPXCHG16,
11024                                                X86::NOT16r, X86::AX,
11025                                                X86::GR16RegisterClass);
11026   case X86::ATOMXOR16:
11027     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11028                                                X86::XOR16ri, X86::MOV16rm,
11029                                                X86::LCMPXCHG16,
11030                                                X86::NOT16r, X86::AX,
11031                                                X86::GR16RegisterClass);
11032   case X86::ATOMNAND16:
11033     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11034                                                X86::AND16ri, X86::MOV16rm,
11035                                                X86::LCMPXCHG16,
11036                                                X86::NOT16r, X86::AX,
11037                                                X86::GR16RegisterClass, true);
11038   case X86::ATOMMIN16:
11039     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11040   case X86::ATOMMAX16:
11041     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11042   case X86::ATOMUMIN16:
11043     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11044   case X86::ATOMUMAX16:
11045     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11046
11047   case X86::ATOMAND8:
11048     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11049                                                X86::AND8ri, X86::MOV8rm,
11050                                                X86::LCMPXCHG8,
11051                                                X86::NOT8r, X86::AL,
11052                                                X86::GR8RegisterClass);
11053   case X86::ATOMOR8:
11054     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11055                                                X86::OR8ri, X86::MOV8rm,
11056                                                X86::LCMPXCHG8,
11057                                                X86::NOT8r, X86::AL,
11058                                                X86::GR8RegisterClass);
11059   case X86::ATOMXOR8:
11060     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11061                                                X86::XOR8ri, X86::MOV8rm,
11062                                                X86::LCMPXCHG8,
11063                                                X86::NOT8r, X86::AL,
11064                                                X86::GR8RegisterClass);
11065   case X86::ATOMNAND8:
11066     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11067                                                X86::AND8ri, X86::MOV8rm,
11068                                                X86::LCMPXCHG8,
11069                                                X86::NOT8r, X86::AL,
11070                                                X86::GR8RegisterClass, true);
11071   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11072   // This group is for 64-bit host.
11073   case X86::ATOMAND64:
11074     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11075                                                X86::AND64ri32, X86::MOV64rm,
11076                                                X86::LCMPXCHG64,
11077                                                X86::NOT64r, X86::RAX,
11078                                                X86::GR64RegisterClass);
11079   case X86::ATOMOR64:
11080     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11081                                                X86::OR64ri32, X86::MOV64rm,
11082                                                X86::LCMPXCHG64,
11083                                                X86::NOT64r, X86::RAX,
11084                                                X86::GR64RegisterClass);
11085   case X86::ATOMXOR64:
11086     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11087                                                X86::XOR64ri32, X86::MOV64rm,
11088                                                X86::LCMPXCHG64,
11089                                                X86::NOT64r, X86::RAX,
11090                                                X86::GR64RegisterClass);
11091   case X86::ATOMNAND64:
11092     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11093                                                X86::AND64ri32, X86::MOV64rm,
11094                                                X86::LCMPXCHG64,
11095                                                X86::NOT64r, X86::RAX,
11096                                                X86::GR64RegisterClass, true);
11097   case X86::ATOMMIN64:
11098     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11099   case X86::ATOMMAX64:
11100     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11101   case X86::ATOMUMIN64:
11102     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11103   case X86::ATOMUMAX64:
11104     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11105
11106   // This group does 64-bit operations on a 32-bit host.
11107   case X86::ATOMAND6432:
11108     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11109                                                X86::AND32rr, X86::AND32rr,
11110                                                X86::AND32ri, X86::AND32ri,
11111                                                false);
11112   case X86::ATOMOR6432:
11113     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11114                                                X86::OR32rr, X86::OR32rr,
11115                                                X86::OR32ri, X86::OR32ri,
11116                                                false);
11117   case X86::ATOMXOR6432:
11118     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11119                                                X86::XOR32rr, X86::XOR32rr,
11120                                                X86::XOR32ri, X86::XOR32ri,
11121                                                false);
11122   case X86::ATOMNAND6432:
11123     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11124                                                X86::AND32rr, X86::AND32rr,
11125                                                X86::AND32ri, X86::AND32ri,
11126                                                true);
11127   case X86::ATOMADD6432:
11128     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11129                                                X86::ADD32rr, X86::ADC32rr,
11130                                                X86::ADD32ri, X86::ADC32ri,
11131                                                false);
11132   case X86::ATOMSUB6432:
11133     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11134                                                X86::SUB32rr, X86::SBB32rr,
11135                                                X86::SUB32ri, X86::SBB32ri,
11136                                                false);
11137   case X86::ATOMSWAP6432:
11138     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11139                                                X86::MOV32rr, X86::MOV32rr,
11140                                                X86::MOV32ri, X86::MOV32ri,
11141                                                false);
11142   case X86::VASTART_SAVE_XMM_REGS:
11143     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11144
11145   case X86::VAARG_64:
11146     return EmitVAARG64WithCustomInserter(MI, BB);
11147   }
11148 }
11149
11150 //===----------------------------------------------------------------------===//
11151 //                           X86 Optimization Hooks
11152 //===----------------------------------------------------------------------===//
11153
11154 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11155                                                        const APInt &Mask,
11156                                                        APInt &KnownZero,
11157                                                        APInt &KnownOne,
11158                                                        const SelectionDAG &DAG,
11159                                                        unsigned Depth) const {
11160   unsigned Opc = Op.getOpcode();
11161   assert((Opc >= ISD::BUILTIN_OP_END ||
11162           Opc == ISD::INTRINSIC_WO_CHAIN ||
11163           Opc == ISD::INTRINSIC_W_CHAIN ||
11164           Opc == ISD::INTRINSIC_VOID) &&
11165          "Should use MaskedValueIsZero if you don't know whether Op"
11166          " is a target node!");
11167
11168   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11169   switch (Opc) {
11170   default: break;
11171   case X86ISD::ADD:
11172   case X86ISD::SUB:
11173   case X86ISD::ADC:
11174   case X86ISD::SBB:
11175   case X86ISD::SMUL:
11176   case X86ISD::UMUL:
11177   case X86ISD::INC:
11178   case X86ISD::DEC:
11179   case X86ISD::OR:
11180   case X86ISD::XOR:
11181   case X86ISD::AND:
11182     // These nodes' second result is a boolean.
11183     if (Op.getResNo() == 0)
11184       break;
11185     // Fallthrough
11186   case X86ISD::SETCC:
11187     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11188                                        Mask.getBitWidth() - 1);
11189     break;
11190   }
11191 }
11192
11193 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11194                                                          unsigned Depth) const {
11195   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11196   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11197     return Op.getValueType().getScalarType().getSizeInBits();
11198
11199   // Fallback case.
11200   return 1;
11201 }
11202
11203 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11204 /// node is a GlobalAddress + offset.
11205 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11206                                        const GlobalValue* &GA,
11207                                        int64_t &Offset) const {
11208   if (N->getOpcode() == X86ISD::Wrapper) {
11209     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11210       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11211       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11212       return true;
11213     }
11214   }
11215   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11216 }
11217
11218 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
11219 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
11220                                         TargetLowering::DAGCombinerInfo &DCI) {
11221   DebugLoc dl = N->getDebugLoc();
11222   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
11223   SDValue V1 = SVOp->getOperand(0);
11224   SDValue V2 = SVOp->getOperand(1);
11225   EVT VT = SVOp->getValueType(0);
11226
11227   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
11228       V2.getOpcode() == ISD::CONCAT_VECTORS) {
11229     //
11230     //                   0,0,0,...
11231     //                      |
11232     //    V      UNDEF    BUILD_VECTOR    UNDEF
11233     //     \      /           \           /
11234     //  CONCAT_VECTOR         CONCAT_VECTOR
11235     //         \                  /
11236     //          \                /
11237     //          RESULT: V + zero extended
11238     //
11239     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
11240         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
11241         V1.getOperand(1).getOpcode() != ISD::UNDEF)
11242       return SDValue();
11243
11244     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
11245       return SDValue();
11246
11247     // To match the shuffle mask, the first half of the mask should
11248     // be exactly the first vector, and all the rest a splat with the
11249     // first element of the second one.
11250     int NumElems = VT.getVectorNumElements();
11251     for (int i = 0; i < NumElems/2; ++i)
11252       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
11253           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
11254         return SDValue();
11255
11256     // Emit a zeroed vector and insert the desired subvector on its
11257     // first half.
11258     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
11259     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
11260                          DAG.getConstant(0, MVT::i32), DAG, dl);
11261     return DCI.CombineTo(N, InsV);
11262   }
11263
11264   return SDValue();
11265 }
11266
11267 /// PerformShuffleCombine - Performs several different shuffle combines.
11268 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11269                                      TargetLowering::DAGCombinerInfo &DCI) {
11270   DebugLoc dl = N->getDebugLoc();
11271   EVT VT = N->getValueType(0);
11272
11273   // Don't create instructions with illegal types after legalize types has run.
11274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11275   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11276     return SDValue();
11277
11278   // Only handle pure VECTOR_SHUFFLE nodes.
11279   if (VT.getSizeInBits() == 256 && N->getOpcode() == ISD::VECTOR_SHUFFLE)
11280     return PerformShuffleCombine256(N, DAG, DCI);
11281
11282   // Only handle 128 wide vector from here on.
11283   if (VT.getSizeInBits() != 128)
11284     return SDValue();
11285
11286   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
11287   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
11288   // consecutive, non-overlapping, and in the right order.
11289   SmallVector<SDValue, 16> Elts;
11290   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11291     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11292
11293   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11294 }
11295
11296 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11297 /// generation and convert it from being a bunch of shuffles and extracts
11298 /// to a simple store and scalar loads to extract the elements.
11299 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11300                                                 const TargetLowering &TLI) {
11301   SDValue InputVector = N->getOperand(0);
11302
11303   // Only operate on vectors of 4 elements, where the alternative shuffling
11304   // gets to be more expensive.
11305   if (InputVector.getValueType() != MVT::v4i32)
11306     return SDValue();
11307
11308   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11309   // single use which is a sign-extend or zero-extend, and all elements are
11310   // used.
11311   SmallVector<SDNode *, 4> Uses;
11312   unsigned ExtractedElements = 0;
11313   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11314        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11315     if (UI.getUse().getResNo() != InputVector.getResNo())
11316       return SDValue();
11317
11318     SDNode *Extract = *UI;
11319     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11320       return SDValue();
11321
11322     if (Extract->getValueType(0) != MVT::i32)
11323       return SDValue();
11324     if (!Extract->hasOneUse())
11325       return SDValue();
11326     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11327         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11328       return SDValue();
11329     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11330       return SDValue();
11331
11332     // Record which element was extracted.
11333     ExtractedElements |=
11334       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11335
11336     Uses.push_back(Extract);
11337   }
11338
11339   // If not all the elements were used, this may not be worthwhile.
11340   if (ExtractedElements != 15)
11341     return SDValue();
11342
11343   // Ok, we've now decided to do the transformation.
11344   DebugLoc dl = InputVector.getDebugLoc();
11345
11346   // Store the value to a temporary stack slot.
11347   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11348   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11349                             MachinePointerInfo(), false, false, 0);
11350
11351   // Replace each use (extract) with a load of the appropriate element.
11352   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11353        UE = Uses.end(); UI != UE; ++UI) {
11354     SDNode *Extract = *UI;
11355
11356     // cOMpute the element's address.
11357     SDValue Idx = Extract->getOperand(1);
11358     unsigned EltSize =
11359         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11360     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11361     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11362
11363     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11364                                      StackPtr, OffsetVal);
11365
11366     // Load the scalar.
11367     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11368                                      ScalarAddr, MachinePointerInfo(),
11369                                      false, false, 0);
11370
11371     // Replace the exact with the load.
11372     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11373   }
11374
11375   // The replacement was made in place; don't return anything.
11376   return SDValue();
11377 }
11378
11379 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11380 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11381                                     const X86Subtarget *Subtarget) {
11382   DebugLoc DL = N->getDebugLoc();
11383   SDValue Cond = N->getOperand(0);
11384   // Get the LHS/RHS of the select.
11385   SDValue LHS = N->getOperand(1);
11386   SDValue RHS = N->getOperand(2);
11387
11388   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11389   // instructions match the semantics of the common C idiom x<y?x:y but not
11390   // x<=y?x:y, because of how they handle negative zero (which can be
11391   // ignored in unsafe-math mode).
11392   if (Subtarget->hasSSE2() &&
11393       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11394       Cond.getOpcode() == ISD::SETCC) {
11395     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11396
11397     unsigned Opcode = 0;
11398     // Check for x CC y ? x : y.
11399     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11400         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11401       switch (CC) {
11402       default: break;
11403       case ISD::SETULT:
11404         // Converting this to a min would handle NaNs incorrectly, and swapping
11405         // the operands would cause it to handle comparisons between positive
11406         // and negative zero incorrectly.
11407         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11408           if (!UnsafeFPMath &&
11409               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11410             break;
11411           std::swap(LHS, RHS);
11412         }
11413         Opcode = X86ISD::FMIN;
11414         break;
11415       case ISD::SETOLE:
11416         // Converting this to a min would handle comparisons between positive
11417         // and negative zero incorrectly.
11418         if (!UnsafeFPMath &&
11419             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11420           break;
11421         Opcode = X86ISD::FMIN;
11422         break;
11423       case ISD::SETULE:
11424         // Converting this to a min would handle both negative zeros and NaNs
11425         // incorrectly, but we can swap the operands to fix both.
11426         std::swap(LHS, RHS);
11427       case ISD::SETOLT:
11428       case ISD::SETLT:
11429       case ISD::SETLE:
11430         Opcode = X86ISD::FMIN;
11431         break;
11432
11433       case ISD::SETOGE:
11434         // Converting this to a max would handle comparisons between positive
11435         // and negative zero incorrectly.
11436         if (!UnsafeFPMath &&
11437             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11438           break;
11439         Opcode = X86ISD::FMAX;
11440         break;
11441       case ISD::SETUGT:
11442         // Converting this to a max would handle NaNs incorrectly, and swapping
11443         // the operands would cause it to handle comparisons between positive
11444         // and negative zero incorrectly.
11445         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11446           if (!UnsafeFPMath &&
11447               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11448             break;
11449           std::swap(LHS, RHS);
11450         }
11451         Opcode = X86ISD::FMAX;
11452         break;
11453       case ISD::SETUGE:
11454         // Converting this to a max would handle both negative zeros and NaNs
11455         // incorrectly, but we can swap the operands to fix both.
11456         std::swap(LHS, RHS);
11457       case ISD::SETOGT:
11458       case ISD::SETGT:
11459       case ISD::SETGE:
11460         Opcode = X86ISD::FMAX;
11461         break;
11462       }
11463     // Check for x CC y ? y : x -- a min/max with reversed arms.
11464     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11465                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11466       switch (CC) {
11467       default: break;
11468       case ISD::SETOGE:
11469         // Converting this to a min would handle comparisons between positive
11470         // and negative zero incorrectly, and swapping the operands would
11471         // cause it to handle NaNs incorrectly.
11472         if (!UnsafeFPMath &&
11473             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11474           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11475             break;
11476           std::swap(LHS, RHS);
11477         }
11478         Opcode = X86ISD::FMIN;
11479         break;
11480       case ISD::SETUGT:
11481         // Converting this to a min would handle NaNs incorrectly.
11482         if (!UnsafeFPMath &&
11483             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11484           break;
11485         Opcode = X86ISD::FMIN;
11486         break;
11487       case ISD::SETUGE:
11488         // Converting this to a min would handle both negative zeros and NaNs
11489         // incorrectly, but we can swap the operands to fix both.
11490         std::swap(LHS, RHS);
11491       case ISD::SETOGT:
11492       case ISD::SETGT:
11493       case ISD::SETGE:
11494         Opcode = X86ISD::FMIN;
11495         break;
11496
11497       case ISD::SETULT:
11498         // Converting this to a max would handle NaNs incorrectly.
11499         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11500           break;
11501         Opcode = X86ISD::FMAX;
11502         break;
11503       case ISD::SETOLE:
11504         // Converting this to a max would handle comparisons between positive
11505         // and negative zero incorrectly, and swapping the operands would
11506         // cause it to handle NaNs incorrectly.
11507         if (!UnsafeFPMath &&
11508             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11509           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11510             break;
11511           std::swap(LHS, RHS);
11512         }
11513         Opcode = X86ISD::FMAX;
11514         break;
11515       case ISD::SETULE:
11516         // Converting this to a max would handle both negative zeros and NaNs
11517         // incorrectly, but we can swap the operands to fix both.
11518         std::swap(LHS, RHS);
11519       case ISD::SETOLT:
11520       case ISD::SETLT:
11521       case ISD::SETLE:
11522         Opcode = X86ISD::FMAX;
11523         break;
11524       }
11525     }
11526
11527     if (Opcode)
11528       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11529   }
11530
11531   // If this is a select between two integer constants, try to do some
11532   // optimizations.
11533   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11534     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11535       // Don't do this for crazy integer types.
11536       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11537         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11538         // so that TrueC (the true value) is larger than FalseC.
11539         bool NeedsCondInvert = false;
11540
11541         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11542             // Efficiently invertible.
11543             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11544              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11545               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11546           NeedsCondInvert = true;
11547           std::swap(TrueC, FalseC);
11548         }
11549
11550         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11551         if (FalseC->getAPIntValue() == 0 &&
11552             TrueC->getAPIntValue().isPowerOf2()) {
11553           if (NeedsCondInvert) // Invert the condition if needed.
11554             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11555                                DAG.getConstant(1, Cond.getValueType()));
11556
11557           // Zero extend the condition if needed.
11558           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11559
11560           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11561           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11562                              DAG.getConstant(ShAmt, MVT::i8));
11563         }
11564
11565         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11566         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11567           if (NeedsCondInvert) // Invert the condition if needed.
11568             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11569                                DAG.getConstant(1, Cond.getValueType()));
11570
11571           // Zero extend the condition if needed.
11572           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11573                              FalseC->getValueType(0), Cond);
11574           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11575                              SDValue(FalseC, 0));
11576         }
11577
11578         // Optimize cases that will turn into an LEA instruction.  This requires
11579         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11580         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11581           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11582           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11583
11584           bool isFastMultiplier = false;
11585           if (Diff < 10) {
11586             switch ((unsigned char)Diff) {
11587               default: break;
11588               case 1:  // result = add base, cond
11589               case 2:  // result = lea base(    , cond*2)
11590               case 3:  // result = lea base(cond, cond*2)
11591               case 4:  // result = lea base(    , cond*4)
11592               case 5:  // result = lea base(cond, cond*4)
11593               case 8:  // result = lea base(    , cond*8)
11594               case 9:  // result = lea base(cond, cond*8)
11595                 isFastMultiplier = true;
11596                 break;
11597             }
11598           }
11599
11600           if (isFastMultiplier) {
11601             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11602             if (NeedsCondInvert) // Invert the condition if needed.
11603               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11604                                  DAG.getConstant(1, Cond.getValueType()));
11605
11606             // Zero extend the condition if needed.
11607             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11608                                Cond);
11609             // Scale the condition by the difference.
11610             if (Diff != 1)
11611               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11612                                  DAG.getConstant(Diff, Cond.getValueType()));
11613
11614             // Add the base if non-zero.
11615             if (FalseC->getAPIntValue() != 0)
11616               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11617                                  SDValue(FalseC, 0));
11618             return Cond;
11619           }
11620         }
11621       }
11622   }
11623
11624   return SDValue();
11625 }
11626
11627 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11628 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11629                                   TargetLowering::DAGCombinerInfo &DCI) {
11630   DebugLoc DL = N->getDebugLoc();
11631
11632   // If the flag operand isn't dead, don't touch this CMOV.
11633   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11634     return SDValue();
11635
11636   SDValue FalseOp = N->getOperand(0);
11637   SDValue TrueOp = N->getOperand(1);
11638   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11639   SDValue Cond = N->getOperand(3);
11640   if (CC == X86::COND_E || CC == X86::COND_NE) {
11641     switch (Cond.getOpcode()) {
11642     default: break;
11643     case X86ISD::BSR:
11644     case X86ISD::BSF:
11645       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11646       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11647         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11648     }
11649   }
11650
11651   // If this is a select between two integer constants, try to do some
11652   // optimizations.  Note that the operands are ordered the opposite of SELECT
11653   // operands.
11654   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11655     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11656       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11657       // larger than FalseC (the false value).
11658       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11659         CC = X86::GetOppositeBranchCondition(CC);
11660         std::swap(TrueC, FalseC);
11661       }
11662
11663       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11664       // This is efficient for any integer data type (including i8/i16) and
11665       // shift amount.
11666       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11667         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11668                            DAG.getConstant(CC, MVT::i8), Cond);
11669
11670         // Zero extend the condition if needed.
11671         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11672
11673         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11674         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11675                            DAG.getConstant(ShAmt, MVT::i8));
11676         if (N->getNumValues() == 2)  // Dead flag value?
11677           return DCI.CombineTo(N, Cond, SDValue());
11678         return Cond;
11679       }
11680
11681       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11682       // for any integer data type, including i8/i16.
11683       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11684         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11685                            DAG.getConstant(CC, MVT::i8), Cond);
11686
11687         // Zero extend the condition if needed.
11688         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11689                            FalseC->getValueType(0), Cond);
11690         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11691                            SDValue(FalseC, 0));
11692
11693         if (N->getNumValues() == 2)  // Dead flag value?
11694           return DCI.CombineTo(N, Cond, SDValue());
11695         return Cond;
11696       }
11697
11698       // Optimize cases that will turn into an LEA instruction.  This requires
11699       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11700       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11701         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11702         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11703
11704         bool isFastMultiplier = false;
11705         if (Diff < 10) {
11706           switch ((unsigned char)Diff) {
11707           default: break;
11708           case 1:  // result = add base, cond
11709           case 2:  // result = lea base(    , cond*2)
11710           case 3:  // result = lea base(cond, cond*2)
11711           case 4:  // result = lea base(    , cond*4)
11712           case 5:  // result = lea base(cond, cond*4)
11713           case 8:  // result = lea base(    , cond*8)
11714           case 9:  // result = lea base(cond, cond*8)
11715             isFastMultiplier = true;
11716             break;
11717           }
11718         }
11719
11720         if (isFastMultiplier) {
11721           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11722           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11723                              DAG.getConstant(CC, MVT::i8), Cond);
11724           // Zero extend the condition if needed.
11725           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11726                              Cond);
11727           // Scale the condition by the difference.
11728           if (Diff != 1)
11729             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11730                                DAG.getConstant(Diff, Cond.getValueType()));
11731
11732           // Add the base if non-zero.
11733           if (FalseC->getAPIntValue() != 0)
11734             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11735                                SDValue(FalseC, 0));
11736           if (N->getNumValues() == 2)  // Dead flag value?
11737             return DCI.CombineTo(N, Cond, SDValue());
11738           return Cond;
11739         }
11740       }
11741     }
11742   }
11743   return SDValue();
11744 }
11745
11746
11747 /// PerformMulCombine - Optimize a single multiply with constant into two
11748 /// in order to implement it with two cheaper instructions, e.g.
11749 /// LEA + SHL, LEA + LEA.
11750 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11751                                  TargetLowering::DAGCombinerInfo &DCI) {
11752   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11753     return SDValue();
11754
11755   EVT VT = N->getValueType(0);
11756   if (VT != MVT::i64)
11757     return SDValue();
11758
11759   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11760   if (!C)
11761     return SDValue();
11762   uint64_t MulAmt = C->getZExtValue();
11763   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11764     return SDValue();
11765
11766   uint64_t MulAmt1 = 0;
11767   uint64_t MulAmt2 = 0;
11768   if ((MulAmt % 9) == 0) {
11769     MulAmt1 = 9;
11770     MulAmt2 = MulAmt / 9;
11771   } else if ((MulAmt % 5) == 0) {
11772     MulAmt1 = 5;
11773     MulAmt2 = MulAmt / 5;
11774   } else if ((MulAmt % 3) == 0) {
11775     MulAmt1 = 3;
11776     MulAmt2 = MulAmt / 3;
11777   }
11778   if (MulAmt2 &&
11779       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11780     DebugLoc DL = N->getDebugLoc();
11781
11782     if (isPowerOf2_64(MulAmt2) &&
11783         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11784       // If second multiplifer is pow2, issue it first. We want the multiply by
11785       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11786       // is an add.
11787       std::swap(MulAmt1, MulAmt2);
11788
11789     SDValue NewMul;
11790     if (isPowerOf2_64(MulAmt1))
11791       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11792                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11793     else
11794       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11795                            DAG.getConstant(MulAmt1, VT));
11796
11797     if (isPowerOf2_64(MulAmt2))
11798       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11799                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11800     else
11801       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11802                            DAG.getConstant(MulAmt2, VT));
11803
11804     // Do not add new nodes to DAG combiner worklist.
11805     DCI.CombineTo(N, NewMul, false);
11806   }
11807   return SDValue();
11808 }
11809
11810 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11811   SDValue N0 = N->getOperand(0);
11812   SDValue N1 = N->getOperand(1);
11813   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11814   EVT VT = N0.getValueType();
11815
11816   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11817   // since the result of setcc_c is all zero's or all ones.
11818   if (N1C && N0.getOpcode() == ISD::AND &&
11819       N0.getOperand(1).getOpcode() == ISD::Constant) {
11820     SDValue N00 = N0.getOperand(0);
11821     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11822         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11823           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11824          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11825       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11826       APInt ShAmt = N1C->getAPIntValue();
11827       Mask = Mask.shl(ShAmt);
11828       if (Mask != 0)
11829         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11830                            N00, DAG.getConstant(Mask, VT));
11831     }
11832   }
11833
11834   return SDValue();
11835 }
11836
11837 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11838 ///                       when possible.
11839 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11840                                    const X86Subtarget *Subtarget) {
11841   EVT VT = N->getValueType(0);
11842   if (!VT.isVector() && VT.isInteger() &&
11843       N->getOpcode() == ISD::SHL)
11844     return PerformSHLCombine(N, DAG);
11845
11846   // On X86 with SSE2 support, we can transform this to a vector shift if
11847   // all elements are shifted by the same amount.  We can't do this in legalize
11848   // because the a constant vector is typically transformed to a constant pool
11849   // so we have no knowledge of the shift amount.
11850   if (!Subtarget->hasSSE2())
11851     return SDValue();
11852
11853   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11854     return SDValue();
11855
11856   SDValue ShAmtOp = N->getOperand(1);
11857   EVT EltVT = VT.getVectorElementType();
11858   DebugLoc DL = N->getDebugLoc();
11859   SDValue BaseShAmt = SDValue();
11860   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11861     unsigned NumElts = VT.getVectorNumElements();
11862     unsigned i = 0;
11863     for (; i != NumElts; ++i) {
11864       SDValue Arg = ShAmtOp.getOperand(i);
11865       if (Arg.getOpcode() == ISD::UNDEF) continue;
11866       BaseShAmt = Arg;
11867       break;
11868     }
11869     for (; i != NumElts; ++i) {
11870       SDValue Arg = ShAmtOp.getOperand(i);
11871       if (Arg.getOpcode() == ISD::UNDEF) continue;
11872       if (Arg != BaseShAmt) {
11873         return SDValue();
11874       }
11875     }
11876   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11877              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11878     SDValue InVec = ShAmtOp.getOperand(0);
11879     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11880       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11881       unsigned i = 0;
11882       for (; i != NumElts; ++i) {
11883         SDValue Arg = InVec.getOperand(i);
11884         if (Arg.getOpcode() == ISD::UNDEF) continue;
11885         BaseShAmt = Arg;
11886         break;
11887       }
11888     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11889        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11890          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11891          if (C->getZExtValue() == SplatIdx)
11892            BaseShAmt = InVec.getOperand(1);
11893        }
11894     }
11895     if (BaseShAmt.getNode() == 0)
11896       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11897                               DAG.getIntPtrConstant(0));
11898   } else
11899     return SDValue();
11900
11901   // The shift amount is an i32.
11902   if (EltVT.bitsGT(MVT::i32))
11903     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11904   else if (EltVT.bitsLT(MVT::i32))
11905     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11906
11907   // The shift amount is identical so we can do a vector shift.
11908   SDValue  ValOp = N->getOperand(0);
11909   switch (N->getOpcode()) {
11910   default:
11911     llvm_unreachable("Unknown shift opcode!");
11912     break;
11913   case ISD::SHL:
11914     if (VT == MVT::v2i64)
11915       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11916                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11917                          ValOp, BaseShAmt);
11918     if (VT == MVT::v4i32)
11919       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11920                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11921                          ValOp, BaseShAmt);
11922     if (VT == MVT::v8i16)
11923       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11924                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11925                          ValOp, BaseShAmt);
11926     break;
11927   case ISD::SRA:
11928     if (VT == MVT::v4i32)
11929       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11930                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11931                          ValOp, BaseShAmt);
11932     if (VT == MVT::v8i16)
11933       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11934                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11935                          ValOp, BaseShAmt);
11936     break;
11937   case ISD::SRL:
11938     if (VT == MVT::v2i64)
11939       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11940                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11941                          ValOp, BaseShAmt);
11942     if (VT == MVT::v4i32)
11943       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11944                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11945                          ValOp, BaseShAmt);
11946     if (VT ==  MVT::v8i16)
11947       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11948                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11949                          ValOp, BaseShAmt);
11950     break;
11951   }
11952   return SDValue();
11953 }
11954
11955
11956 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11957 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11958 // and friends.  Likewise for OR -> CMPNEQSS.
11959 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11960                             TargetLowering::DAGCombinerInfo &DCI,
11961                             const X86Subtarget *Subtarget) {
11962   unsigned opcode;
11963
11964   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11965   // we're requiring SSE2 for both.
11966   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11967     SDValue N0 = N->getOperand(0);
11968     SDValue N1 = N->getOperand(1);
11969     SDValue CMP0 = N0->getOperand(1);
11970     SDValue CMP1 = N1->getOperand(1);
11971     DebugLoc DL = N->getDebugLoc();
11972
11973     // The SETCCs should both refer to the same CMP.
11974     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11975       return SDValue();
11976
11977     SDValue CMP00 = CMP0->getOperand(0);
11978     SDValue CMP01 = CMP0->getOperand(1);
11979     EVT     VT    = CMP00.getValueType();
11980
11981     if (VT == MVT::f32 || VT == MVT::f64) {
11982       bool ExpectingFlags = false;
11983       // Check for any users that want flags:
11984       for (SDNode::use_iterator UI = N->use_begin(),
11985              UE = N->use_end();
11986            !ExpectingFlags && UI != UE; ++UI)
11987         switch (UI->getOpcode()) {
11988         default:
11989         case ISD::BR_CC:
11990         case ISD::BRCOND:
11991         case ISD::SELECT:
11992           ExpectingFlags = true;
11993           break;
11994         case ISD::CopyToReg:
11995         case ISD::SIGN_EXTEND:
11996         case ISD::ZERO_EXTEND:
11997         case ISD::ANY_EXTEND:
11998           break;
11999         }
12000
12001       if (!ExpectingFlags) {
12002         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
12003         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
12004
12005         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
12006           X86::CondCode tmp = cc0;
12007           cc0 = cc1;
12008           cc1 = tmp;
12009         }
12010
12011         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
12012             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
12013           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
12014           X86ISD::NodeType NTOperator = is64BitFP ?
12015             X86ISD::FSETCCsd : X86ISD::FSETCCss;
12016           // FIXME: need symbolic constants for these magic numbers.
12017           // See X86ATTInstPrinter.cpp:printSSECC().
12018           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
12019           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
12020                                               DAG.getConstant(x86cc, MVT::i8));
12021           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
12022                                               OnesOrZeroesF);
12023           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
12024                                       DAG.getConstant(1, MVT::i32));
12025           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
12026           return OneBitOfTruth;
12027         }
12028       }
12029     }
12030   }
12031   return SDValue();
12032 }
12033
12034 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
12035 /// so it can be folded inside ANDNP.
12036 static bool CanFoldXORWithAllOnes(const SDNode *N) {
12037   EVT VT = N->getValueType(0);
12038
12039   // Match direct AllOnes for 128 and 256-bit vectors
12040   if (ISD::isBuildVectorAllOnes(N))
12041     return true;
12042
12043   // Look through a bit convert.
12044   if (N->getOpcode() == ISD::BITCAST)
12045     N = N->getOperand(0).getNode();
12046
12047   // Sometimes the operand may come from a insert_subvector building a 256-bit
12048   // allones vector
12049   SDValue V1 = N->getOperand(0);
12050   SDValue V2 = N->getOperand(1);
12051
12052   if (VT.getSizeInBits() == 256 &&
12053       N->getOpcode() == ISD::INSERT_SUBVECTOR &&
12054       V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
12055       V1.getOperand(0).getOpcode() == ISD::UNDEF &&
12056       ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
12057       ISD::isBuildVectorAllOnes(V2.getNode()))
12058     return true;
12059
12060   return false;
12061 }
12062
12063 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
12064                                  TargetLowering::DAGCombinerInfo &DCI,
12065                                  const X86Subtarget *Subtarget) {
12066   if (DCI.isBeforeLegalizeOps())
12067     return SDValue();
12068
12069   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12070   if (R.getNode())
12071     return R;
12072
12073   // Want to form ANDNP nodes:
12074   // 1) In the hopes of then easily combining them with OR and AND nodes
12075   //    to form PBLEND/PSIGN.
12076   // 2) To match ANDN packed intrinsics
12077   EVT VT = N->getValueType(0);
12078   if (VT != MVT::v2i64 && VT != MVT::v4i64)
12079     return SDValue();
12080
12081   SDValue N0 = N->getOperand(0);
12082   SDValue N1 = N->getOperand(1);
12083   DebugLoc DL = N->getDebugLoc();
12084
12085   // Check LHS for vnot
12086   if (N0.getOpcode() == ISD::XOR &&
12087       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12088       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
12089     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12090
12091   // Check RHS for vnot
12092   if (N1.getOpcode() == ISD::XOR &&
12093       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12094       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
12095     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12096
12097   return SDValue();
12098 }
12099
12100 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12101                                 TargetLowering::DAGCombinerInfo &DCI,
12102                                 const X86Subtarget *Subtarget) {
12103   if (DCI.isBeforeLegalizeOps())
12104     return SDValue();
12105
12106   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12107   if (R.getNode())
12108     return R;
12109
12110   EVT VT = N->getValueType(0);
12111   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12112     return SDValue();
12113
12114   SDValue N0 = N->getOperand(0);
12115   SDValue N1 = N->getOperand(1);
12116
12117   // look for psign/blend
12118   if (Subtarget->hasSSSE3()) {
12119     if (VT == MVT::v2i64) {
12120       // Canonicalize pandn to RHS
12121       if (N0.getOpcode() == X86ISD::ANDNP)
12122         std::swap(N0, N1);
12123       // or (and (m, x), (pandn m, y))
12124       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12125         SDValue Mask = N1.getOperand(0);
12126         SDValue X    = N1.getOperand(1);
12127         SDValue Y;
12128         if (N0.getOperand(0) == Mask)
12129           Y = N0.getOperand(1);
12130         if (N0.getOperand(1) == Mask)
12131           Y = N0.getOperand(0);
12132
12133         // Check to see if the mask appeared in both the AND and ANDNP and
12134         if (!Y.getNode())
12135           return SDValue();
12136
12137         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12138         if (Mask.getOpcode() != ISD::BITCAST ||
12139             X.getOpcode() != ISD::BITCAST ||
12140             Y.getOpcode() != ISD::BITCAST)
12141           return SDValue();
12142
12143         // Look through mask bitcast.
12144         Mask = Mask.getOperand(0);
12145         EVT MaskVT = Mask.getValueType();
12146
12147         // Validate that the Mask operand is a vector sra node.  The sra node
12148         // will be an intrinsic.
12149         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12150           return SDValue();
12151
12152         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12153         // there is no psrai.b
12154         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12155         case Intrinsic::x86_sse2_psrai_w:
12156         case Intrinsic::x86_sse2_psrai_d:
12157           break;
12158         default: return SDValue();
12159         }
12160
12161         // Check that the SRA is all signbits.
12162         SDValue SraC = Mask.getOperand(2);
12163         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
12164         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12165         if ((SraAmt + 1) != EltBits)
12166           return SDValue();
12167
12168         DebugLoc DL = N->getDebugLoc();
12169
12170         // Now we know we at least have a plendvb with the mask val.  See if
12171         // we can form a psignb/w/d.
12172         // psign = x.type == y.type == mask.type && y = sub(0, x);
12173         X = X.getOperand(0);
12174         Y = Y.getOperand(0);
12175         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12176             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12177             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12178           unsigned Opc = 0;
12179           switch (EltBits) {
12180           case 8: Opc = X86ISD::PSIGNB; break;
12181           case 16: Opc = X86ISD::PSIGNW; break;
12182           case 32: Opc = X86ISD::PSIGND; break;
12183           default: break;
12184           }
12185           if (Opc) {
12186             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12187             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12188           }
12189         }
12190         // PBLENDVB only available on SSE 4.1
12191         if (!Subtarget->hasSSE41())
12192           return SDValue();
12193
12194         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12195         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12196         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12197         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12198         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12199       }
12200     }
12201   }
12202
12203   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12204   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12205     std::swap(N0, N1);
12206   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12207     return SDValue();
12208   if (!N0.hasOneUse() || !N1.hasOneUse())
12209     return SDValue();
12210
12211   SDValue ShAmt0 = N0.getOperand(1);
12212   if (ShAmt0.getValueType() != MVT::i8)
12213     return SDValue();
12214   SDValue ShAmt1 = N1.getOperand(1);
12215   if (ShAmt1.getValueType() != MVT::i8)
12216     return SDValue();
12217   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12218     ShAmt0 = ShAmt0.getOperand(0);
12219   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12220     ShAmt1 = ShAmt1.getOperand(0);
12221
12222   DebugLoc DL = N->getDebugLoc();
12223   unsigned Opc = X86ISD::SHLD;
12224   SDValue Op0 = N0.getOperand(0);
12225   SDValue Op1 = N1.getOperand(0);
12226   if (ShAmt0.getOpcode() == ISD::SUB) {
12227     Opc = X86ISD::SHRD;
12228     std::swap(Op0, Op1);
12229     std::swap(ShAmt0, ShAmt1);
12230   }
12231
12232   unsigned Bits = VT.getSizeInBits();
12233   if (ShAmt1.getOpcode() == ISD::SUB) {
12234     SDValue Sum = ShAmt1.getOperand(0);
12235     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12236       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12237       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12238         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12239       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12240         return DAG.getNode(Opc, DL, VT,
12241                            Op0, Op1,
12242                            DAG.getNode(ISD::TRUNCATE, DL,
12243                                        MVT::i8, ShAmt0));
12244     }
12245   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12246     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12247     if (ShAmt0C &&
12248         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12249       return DAG.getNode(Opc, DL, VT,
12250                          N0.getOperand(0), N1.getOperand(0),
12251                          DAG.getNode(ISD::TRUNCATE, DL,
12252                                        MVT::i8, ShAmt0));
12253   }
12254
12255   return SDValue();
12256 }
12257
12258 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12259 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12260                                    const X86Subtarget *Subtarget) {
12261   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12262   // the FP state in cases where an emms may be missing.
12263   // A preferable solution to the general problem is to figure out the right
12264   // places to insert EMMS.  This qualifies as a quick hack.
12265
12266   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12267   StoreSDNode *St = cast<StoreSDNode>(N);
12268   EVT VT = St->getValue().getValueType();
12269   if (VT.getSizeInBits() != 64)
12270     return SDValue();
12271
12272   const Function *F = DAG.getMachineFunction().getFunction();
12273   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12274   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12275     && Subtarget->hasSSE2();
12276   if ((VT.isVector() ||
12277        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12278       isa<LoadSDNode>(St->getValue()) &&
12279       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12280       St->getChain().hasOneUse() && !St->isVolatile()) {
12281     SDNode* LdVal = St->getValue().getNode();
12282     LoadSDNode *Ld = 0;
12283     int TokenFactorIndex = -1;
12284     SmallVector<SDValue, 8> Ops;
12285     SDNode* ChainVal = St->getChain().getNode();
12286     // Must be a store of a load.  We currently handle two cases:  the load
12287     // is a direct child, and it's under an intervening TokenFactor.  It is
12288     // possible to dig deeper under nested TokenFactors.
12289     if (ChainVal == LdVal)
12290       Ld = cast<LoadSDNode>(St->getChain());
12291     else if (St->getValue().hasOneUse() &&
12292              ChainVal->getOpcode() == ISD::TokenFactor) {
12293       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12294         if (ChainVal->getOperand(i).getNode() == LdVal) {
12295           TokenFactorIndex = i;
12296           Ld = cast<LoadSDNode>(St->getValue());
12297         } else
12298           Ops.push_back(ChainVal->getOperand(i));
12299       }
12300     }
12301
12302     if (!Ld || !ISD::isNormalLoad(Ld))
12303       return SDValue();
12304
12305     // If this is not the MMX case, i.e. we are just turning i64 load/store
12306     // into f64 load/store, avoid the transformation if there are multiple
12307     // uses of the loaded value.
12308     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12309       return SDValue();
12310
12311     DebugLoc LdDL = Ld->getDebugLoc();
12312     DebugLoc StDL = N->getDebugLoc();
12313     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12314     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12315     // pair instead.
12316     if (Subtarget->is64Bit() || F64IsLegal) {
12317       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12318       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12319                                   Ld->getPointerInfo(), Ld->isVolatile(),
12320                                   Ld->isNonTemporal(), Ld->getAlignment());
12321       SDValue NewChain = NewLd.getValue(1);
12322       if (TokenFactorIndex != -1) {
12323         Ops.push_back(NewChain);
12324         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12325                                Ops.size());
12326       }
12327       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12328                           St->getPointerInfo(),
12329                           St->isVolatile(), St->isNonTemporal(),
12330                           St->getAlignment());
12331     }
12332
12333     // Otherwise, lower to two pairs of 32-bit loads / stores.
12334     SDValue LoAddr = Ld->getBasePtr();
12335     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12336                                  DAG.getConstant(4, MVT::i32));
12337
12338     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12339                                Ld->getPointerInfo(),
12340                                Ld->isVolatile(), Ld->isNonTemporal(),
12341                                Ld->getAlignment());
12342     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12343                                Ld->getPointerInfo().getWithOffset(4),
12344                                Ld->isVolatile(), Ld->isNonTemporal(),
12345                                MinAlign(Ld->getAlignment(), 4));
12346
12347     SDValue NewChain = LoLd.getValue(1);
12348     if (TokenFactorIndex != -1) {
12349       Ops.push_back(LoLd);
12350       Ops.push_back(HiLd);
12351       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12352                              Ops.size());
12353     }
12354
12355     LoAddr = St->getBasePtr();
12356     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12357                          DAG.getConstant(4, MVT::i32));
12358
12359     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12360                                 St->getPointerInfo(),
12361                                 St->isVolatile(), St->isNonTemporal(),
12362                                 St->getAlignment());
12363     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12364                                 St->getPointerInfo().getWithOffset(4),
12365                                 St->isVolatile(),
12366                                 St->isNonTemporal(),
12367                                 MinAlign(St->getAlignment(), 4));
12368     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12369   }
12370   return SDValue();
12371 }
12372
12373 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12374 /// X86ISD::FXOR nodes.
12375 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12376   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12377   // F[X]OR(0.0, x) -> x
12378   // F[X]OR(x, 0.0) -> x
12379   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12380     if (C->getValueAPF().isPosZero())
12381       return N->getOperand(1);
12382   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12383     if (C->getValueAPF().isPosZero())
12384       return N->getOperand(0);
12385   return SDValue();
12386 }
12387
12388 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12389 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12390   // FAND(0.0, x) -> 0.0
12391   // FAND(x, 0.0) -> 0.0
12392   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12393     if (C->getValueAPF().isPosZero())
12394       return N->getOperand(0);
12395   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12396     if (C->getValueAPF().isPosZero())
12397       return N->getOperand(1);
12398   return SDValue();
12399 }
12400
12401 static SDValue PerformBTCombine(SDNode *N,
12402                                 SelectionDAG &DAG,
12403                                 TargetLowering::DAGCombinerInfo &DCI) {
12404   // BT ignores high bits in the bit index operand.
12405   SDValue Op1 = N->getOperand(1);
12406   if (Op1.hasOneUse()) {
12407     unsigned BitWidth = Op1.getValueSizeInBits();
12408     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12409     APInt KnownZero, KnownOne;
12410     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12411                                           !DCI.isBeforeLegalizeOps());
12412     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12413     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12414         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12415       DCI.CommitTargetLoweringOpt(TLO);
12416   }
12417   return SDValue();
12418 }
12419
12420 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12421   SDValue Op = N->getOperand(0);
12422   if (Op.getOpcode() == ISD::BITCAST)
12423     Op = Op.getOperand(0);
12424   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12425   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12426       VT.getVectorElementType().getSizeInBits() ==
12427       OpVT.getVectorElementType().getSizeInBits()) {
12428     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12429   }
12430   return SDValue();
12431 }
12432
12433 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12434   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12435   //           (and (i32 x86isd::setcc_carry), 1)
12436   // This eliminates the zext. This transformation is necessary because
12437   // ISD::SETCC is always legalized to i8.
12438   DebugLoc dl = N->getDebugLoc();
12439   SDValue N0 = N->getOperand(0);
12440   EVT VT = N->getValueType(0);
12441   if (N0.getOpcode() == ISD::AND &&
12442       N0.hasOneUse() &&
12443       N0.getOperand(0).hasOneUse()) {
12444     SDValue N00 = N0.getOperand(0);
12445     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12446       return SDValue();
12447     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12448     if (!C || C->getZExtValue() != 1)
12449       return SDValue();
12450     return DAG.getNode(ISD::AND, dl, VT,
12451                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12452                                    N00.getOperand(0), N00.getOperand(1)),
12453                        DAG.getConstant(1, VT));
12454   }
12455
12456   return SDValue();
12457 }
12458
12459 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12460 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12461   unsigned X86CC = N->getConstantOperandVal(0);
12462   SDValue EFLAG = N->getOperand(1);
12463   DebugLoc DL = N->getDebugLoc();
12464
12465   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12466   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12467   // cases.
12468   if (X86CC == X86::COND_B)
12469     return DAG.getNode(ISD::AND, DL, MVT::i8,
12470                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12471                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12472                        DAG.getConstant(1, MVT::i8));
12473
12474   return SDValue();
12475 }
12476
12477 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12478                                         const X86TargetLowering *XTLI) {
12479   SDValue Op0 = N->getOperand(0);
12480   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12481   // a 32-bit target where SSE doesn't support i64->FP operations.
12482   if (Op0.getOpcode() == ISD::LOAD) {
12483     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12484     EVT VT = Ld->getValueType(0);
12485     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12486         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12487         !XTLI->getSubtarget()->is64Bit() &&
12488         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12489       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12490                                           Ld->getChain(), Op0, DAG);
12491       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12492       return FILDChain;
12493     }
12494   }
12495   return SDValue();
12496 }
12497
12498 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12499 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12500                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12501   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12502   // the result is either zero or one (depending on the input carry bit).
12503   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12504   if (X86::isZeroNode(N->getOperand(0)) &&
12505       X86::isZeroNode(N->getOperand(1)) &&
12506       // We don't have a good way to replace an EFLAGS use, so only do this when
12507       // dead right now.
12508       SDValue(N, 1).use_empty()) {
12509     DebugLoc DL = N->getDebugLoc();
12510     EVT VT = N->getValueType(0);
12511     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12512     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12513                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12514                                            DAG.getConstant(X86::COND_B,MVT::i8),
12515                                            N->getOperand(2)),
12516                                DAG.getConstant(1, VT));
12517     return DCI.CombineTo(N, Res1, CarryOut);
12518   }
12519
12520   return SDValue();
12521 }
12522
12523 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12524 //      (add Y, (setne X, 0)) -> sbb -1, Y
12525 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12526 //      (sub (setne X, 0), Y) -> adc -1, Y
12527 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12528   DebugLoc DL = N->getDebugLoc();
12529
12530   // Look through ZExts.
12531   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12532   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12533     return SDValue();
12534
12535   SDValue SetCC = Ext.getOperand(0);
12536   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12537     return SDValue();
12538
12539   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12540   if (CC != X86::COND_E && CC != X86::COND_NE)
12541     return SDValue();
12542
12543   SDValue Cmp = SetCC.getOperand(1);
12544   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12545       !X86::isZeroNode(Cmp.getOperand(1)) ||
12546       !Cmp.getOperand(0).getValueType().isInteger())
12547     return SDValue();
12548
12549   SDValue CmpOp0 = Cmp.getOperand(0);
12550   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12551                                DAG.getConstant(1, CmpOp0.getValueType()));
12552
12553   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12554   if (CC == X86::COND_NE)
12555     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12556                        DL, OtherVal.getValueType(), OtherVal,
12557                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12558   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12559                      DL, OtherVal.getValueType(), OtherVal,
12560                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12561 }
12562
12563 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12564                                              DAGCombinerInfo &DCI) const {
12565   SelectionDAG &DAG = DCI.DAG;
12566   switch (N->getOpcode()) {
12567   default: break;
12568   case ISD::EXTRACT_VECTOR_ELT:
12569     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12570   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12571   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12572   case ISD::ADD:
12573   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12574   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12575   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12576   case ISD::SHL:
12577   case ISD::SRA:
12578   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12579   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12580   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12581   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12582   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12583   case X86ISD::FXOR:
12584   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12585   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12586   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12587   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12588   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12589   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12590   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12591   case X86ISD::SHUFPD:
12592   case X86ISD::PALIGN:
12593   case X86ISD::PUNPCKHBW:
12594   case X86ISD::PUNPCKHWD:
12595   case X86ISD::PUNPCKHDQ:
12596   case X86ISD::PUNPCKHQDQ:
12597   case X86ISD::UNPCKHPS:
12598   case X86ISD::UNPCKHPD:
12599   case X86ISD::PUNPCKLBW:
12600   case X86ISD::PUNPCKLWD:
12601   case X86ISD::PUNPCKLDQ:
12602   case X86ISD::PUNPCKLQDQ:
12603   case X86ISD::UNPCKLPS:
12604   case X86ISD::UNPCKLPD:
12605   case X86ISD::VUNPCKLPSY:
12606   case X86ISD::VUNPCKLPDY:
12607   case X86ISD::MOVHLPS:
12608   case X86ISD::MOVLHPS:
12609   case X86ISD::PSHUFD:
12610   case X86ISD::PSHUFHW:
12611   case X86ISD::PSHUFLW:
12612   case X86ISD::MOVSS:
12613   case X86ISD::MOVSD:
12614   case X86ISD::VPERMIL:
12615   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12616   }
12617
12618   return SDValue();
12619 }
12620
12621 /// isTypeDesirableForOp - Return true if the target has native support for
12622 /// the specified value type and it is 'desirable' to use the type for the
12623 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12624 /// instruction encodings are longer and some i16 instructions are slow.
12625 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12626   if (!isTypeLegal(VT))
12627     return false;
12628   if (VT != MVT::i16)
12629     return true;
12630
12631   switch (Opc) {
12632   default:
12633     return true;
12634   case ISD::LOAD:
12635   case ISD::SIGN_EXTEND:
12636   case ISD::ZERO_EXTEND:
12637   case ISD::ANY_EXTEND:
12638   case ISD::SHL:
12639   case ISD::SRL:
12640   case ISD::SUB:
12641   case ISD::ADD:
12642   case ISD::MUL:
12643   case ISD::AND:
12644   case ISD::OR:
12645   case ISD::XOR:
12646     return false;
12647   }
12648 }
12649
12650 /// IsDesirableToPromoteOp - This method query the target whether it is
12651 /// beneficial for dag combiner to promote the specified node. If true, it
12652 /// should return the desired promotion type by reference.
12653 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12654   EVT VT = Op.getValueType();
12655   if (VT != MVT::i16)
12656     return false;
12657
12658   bool Promote = false;
12659   bool Commute = false;
12660   switch (Op.getOpcode()) {
12661   default: break;
12662   case ISD::LOAD: {
12663     LoadSDNode *LD = cast<LoadSDNode>(Op);
12664     // If the non-extending load has a single use and it's not live out, then it
12665     // might be folded.
12666     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12667                                                      Op.hasOneUse()*/) {
12668       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12669              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12670         // The only case where we'd want to promote LOAD (rather then it being
12671         // promoted as an operand is when it's only use is liveout.
12672         if (UI->getOpcode() != ISD::CopyToReg)
12673           return false;
12674       }
12675     }
12676     Promote = true;
12677     break;
12678   }
12679   case ISD::SIGN_EXTEND:
12680   case ISD::ZERO_EXTEND:
12681   case ISD::ANY_EXTEND:
12682     Promote = true;
12683     break;
12684   case ISD::SHL:
12685   case ISD::SRL: {
12686     SDValue N0 = Op.getOperand(0);
12687     // Look out for (store (shl (load), x)).
12688     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12689       return false;
12690     Promote = true;
12691     break;
12692   }
12693   case ISD::ADD:
12694   case ISD::MUL:
12695   case ISD::AND:
12696   case ISD::OR:
12697   case ISD::XOR:
12698     Commute = true;
12699     // fallthrough
12700   case ISD::SUB: {
12701     SDValue N0 = Op.getOperand(0);
12702     SDValue N1 = Op.getOperand(1);
12703     if (!Commute && MayFoldLoad(N1))
12704       return false;
12705     // Avoid disabling potential load folding opportunities.
12706     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12707       return false;
12708     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12709       return false;
12710     Promote = true;
12711   }
12712   }
12713
12714   PVT = MVT::i32;
12715   return Promote;
12716 }
12717
12718 //===----------------------------------------------------------------------===//
12719 //                           X86 Inline Assembly Support
12720 //===----------------------------------------------------------------------===//
12721
12722 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12723   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12724
12725   std::string AsmStr = IA->getAsmString();
12726
12727   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12728   SmallVector<StringRef, 4> AsmPieces;
12729   SplitString(AsmStr, AsmPieces, ";\n");
12730
12731   switch (AsmPieces.size()) {
12732   default: return false;
12733   case 1:
12734     AsmStr = AsmPieces[0];
12735     AsmPieces.clear();
12736     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12737
12738     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12739     // we will turn this bswap into something that will be lowered to logical ops
12740     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12741     // so don't worry about this.
12742     // bswap $0
12743     if (AsmPieces.size() == 2 &&
12744         (AsmPieces[0] == "bswap" ||
12745          AsmPieces[0] == "bswapq" ||
12746          AsmPieces[0] == "bswapl") &&
12747         (AsmPieces[1] == "$0" ||
12748          AsmPieces[1] == "${0:q}")) {
12749       // No need to check constraints, nothing other than the equivalent of
12750       // "=r,0" would be valid here.
12751       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12752       if (!Ty || Ty->getBitWidth() % 16 != 0)
12753         return false;
12754       return IntrinsicLowering::LowerToByteSwap(CI);
12755     }
12756     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12757     if (CI->getType()->isIntegerTy(16) &&
12758         AsmPieces.size() == 3 &&
12759         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12760         AsmPieces[1] == "$$8," &&
12761         AsmPieces[2] == "${0:w}" &&
12762         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12763       AsmPieces.clear();
12764       const std::string &ConstraintsStr = IA->getConstraintString();
12765       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12766       std::sort(AsmPieces.begin(), AsmPieces.end());
12767       if (AsmPieces.size() == 4 &&
12768           AsmPieces[0] == "~{cc}" &&
12769           AsmPieces[1] == "~{dirflag}" &&
12770           AsmPieces[2] == "~{flags}" &&
12771           AsmPieces[3] == "~{fpsr}") {
12772         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12773         if (!Ty || Ty->getBitWidth() % 16 != 0)
12774           return false;
12775         return IntrinsicLowering::LowerToByteSwap(CI);
12776       }
12777     }
12778     break;
12779   case 3:
12780     if (CI->getType()->isIntegerTy(32) &&
12781         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12782       SmallVector<StringRef, 4> Words;
12783       SplitString(AsmPieces[0], Words, " \t,");
12784       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12785           Words[2] == "${0:w}") {
12786         Words.clear();
12787         SplitString(AsmPieces[1], Words, " \t,");
12788         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12789             Words[2] == "$0") {
12790           Words.clear();
12791           SplitString(AsmPieces[2], Words, " \t,");
12792           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12793               Words[2] == "${0:w}") {
12794             AsmPieces.clear();
12795             const std::string &ConstraintsStr = IA->getConstraintString();
12796             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12797             std::sort(AsmPieces.begin(), AsmPieces.end());
12798             if (AsmPieces.size() == 4 &&
12799                 AsmPieces[0] == "~{cc}" &&
12800                 AsmPieces[1] == "~{dirflag}" &&
12801                 AsmPieces[2] == "~{flags}" &&
12802                 AsmPieces[3] == "~{fpsr}") {
12803               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12804               if (!Ty || Ty->getBitWidth() % 16 != 0)
12805                 return false;
12806               return IntrinsicLowering::LowerToByteSwap(CI);
12807             }
12808           }
12809         }
12810       }
12811     }
12812
12813     if (CI->getType()->isIntegerTy(64)) {
12814       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12815       if (Constraints.size() >= 2 &&
12816           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12817           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12818         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12819         SmallVector<StringRef, 4> Words;
12820         SplitString(AsmPieces[0], Words, " \t");
12821         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12822           Words.clear();
12823           SplitString(AsmPieces[1], Words, " \t");
12824           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12825             Words.clear();
12826             SplitString(AsmPieces[2], Words, " \t,");
12827             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12828                 Words[2] == "%edx") {
12829               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12830               if (!Ty || Ty->getBitWidth() % 16 != 0)
12831                 return false;
12832               return IntrinsicLowering::LowerToByteSwap(CI);
12833             }
12834           }
12835         }
12836       }
12837     }
12838     break;
12839   }
12840   return false;
12841 }
12842
12843
12844
12845 /// getConstraintType - Given a constraint letter, return the type of
12846 /// constraint it is for this target.
12847 X86TargetLowering::ConstraintType
12848 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12849   if (Constraint.size() == 1) {
12850     switch (Constraint[0]) {
12851     case 'R':
12852     case 'q':
12853     case 'Q':
12854     case 'f':
12855     case 't':
12856     case 'u':
12857     case 'y':
12858     case 'x':
12859     case 'Y':
12860     case 'l':
12861       return C_RegisterClass;
12862     case 'a':
12863     case 'b':
12864     case 'c':
12865     case 'd':
12866     case 'S':
12867     case 'D':
12868     case 'A':
12869       return C_Register;
12870     case 'I':
12871     case 'J':
12872     case 'K':
12873     case 'L':
12874     case 'M':
12875     case 'N':
12876     case 'G':
12877     case 'C':
12878     case 'e':
12879     case 'Z':
12880       return C_Other;
12881     default:
12882       break;
12883     }
12884   }
12885   return TargetLowering::getConstraintType(Constraint);
12886 }
12887
12888 /// Examine constraint type and operand type and determine a weight value.
12889 /// This object must already have been set up with the operand type
12890 /// and the current alternative constraint selected.
12891 TargetLowering::ConstraintWeight
12892   X86TargetLowering::getSingleConstraintMatchWeight(
12893     AsmOperandInfo &info, const char *constraint) const {
12894   ConstraintWeight weight = CW_Invalid;
12895   Value *CallOperandVal = info.CallOperandVal;
12896     // If we don't have a value, we can't do a match,
12897     // but allow it at the lowest weight.
12898   if (CallOperandVal == NULL)
12899     return CW_Default;
12900   Type *type = CallOperandVal->getType();
12901   // Look at the constraint type.
12902   switch (*constraint) {
12903   default:
12904     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12905   case 'R':
12906   case 'q':
12907   case 'Q':
12908   case 'a':
12909   case 'b':
12910   case 'c':
12911   case 'd':
12912   case 'S':
12913   case 'D':
12914   case 'A':
12915     if (CallOperandVal->getType()->isIntegerTy())
12916       weight = CW_SpecificReg;
12917     break;
12918   case 'f':
12919   case 't':
12920   case 'u':
12921       if (type->isFloatingPointTy())
12922         weight = CW_SpecificReg;
12923       break;
12924   case 'y':
12925       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12926         weight = CW_SpecificReg;
12927       break;
12928   case 'x':
12929   case 'Y':
12930     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12931       weight = CW_Register;
12932     break;
12933   case 'I':
12934     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12935       if (C->getZExtValue() <= 31)
12936         weight = CW_Constant;
12937     }
12938     break;
12939   case 'J':
12940     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12941       if (C->getZExtValue() <= 63)
12942         weight = CW_Constant;
12943     }
12944     break;
12945   case 'K':
12946     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12947       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12948         weight = CW_Constant;
12949     }
12950     break;
12951   case 'L':
12952     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12953       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12954         weight = CW_Constant;
12955     }
12956     break;
12957   case 'M':
12958     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12959       if (C->getZExtValue() <= 3)
12960         weight = CW_Constant;
12961     }
12962     break;
12963   case 'N':
12964     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12965       if (C->getZExtValue() <= 0xff)
12966         weight = CW_Constant;
12967     }
12968     break;
12969   case 'G':
12970   case 'C':
12971     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12972       weight = CW_Constant;
12973     }
12974     break;
12975   case 'e':
12976     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12977       if ((C->getSExtValue() >= -0x80000000LL) &&
12978           (C->getSExtValue() <= 0x7fffffffLL))
12979         weight = CW_Constant;
12980     }
12981     break;
12982   case 'Z':
12983     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12984       if (C->getZExtValue() <= 0xffffffff)
12985         weight = CW_Constant;
12986     }
12987     break;
12988   }
12989   return weight;
12990 }
12991
12992 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12993 /// with another that has more specific requirements based on the type of the
12994 /// corresponding operand.
12995 const char *X86TargetLowering::
12996 LowerXConstraint(EVT ConstraintVT) const {
12997   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12998   // 'f' like normal targets.
12999   if (ConstraintVT.isFloatingPoint()) {
13000     if (Subtarget->hasXMMInt())
13001       return "Y";
13002     if (Subtarget->hasXMM())
13003       return "x";
13004   }
13005
13006   return TargetLowering::LowerXConstraint(ConstraintVT);
13007 }
13008
13009 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13010 /// vector.  If it is invalid, don't add anything to Ops.
13011 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13012                                                      std::string &Constraint,
13013                                                      std::vector<SDValue>&Ops,
13014                                                      SelectionDAG &DAG) const {
13015   SDValue Result(0, 0);
13016
13017   // Only support length 1 constraints for now.
13018   if (Constraint.length() > 1) return;
13019
13020   char ConstraintLetter = Constraint[0];
13021   switch (ConstraintLetter) {
13022   default: break;
13023   case 'I':
13024     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13025       if (C->getZExtValue() <= 31) {
13026         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13027         break;
13028       }
13029     }
13030     return;
13031   case 'J':
13032     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13033       if (C->getZExtValue() <= 63) {
13034         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13035         break;
13036       }
13037     }
13038     return;
13039   case 'K':
13040     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13041       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
13042         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13043         break;
13044       }
13045     }
13046     return;
13047   case 'N':
13048     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13049       if (C->getZExtValue() <= 255) {
13050         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13051         break;
13052       }
13053     }
13054     return;
13055   case 'e': {
13056     // 32-bit signed value
13057     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13058       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13059                                            C->getSExtValue())) {
13060         // Widen to 64 bits here to get it sign extended.
13061         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
13062         break;
13063       }
13064     // FIXME gcc accepts some relocatable values here too, but only in certain
13065     // memory models; it's complicated.
13066     }
13067     return;
13068   }
13069   case 'Z': {
13070     // 32-bit unsigned value
13071     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13072       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13073                                            C->getZExtValue())) {
13074         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13075         break;
13076       }
13077     }
13078     // FIXME gcc accepts some relocatable values here too, but only in certain
13079     // memory models; it's complicated.
13080     return;
13081   }
13082   case 'i': {
13083     // Literal immediates are always ok.
13084     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13085       // Widen to 64 bits here to get it sign extended.
13086       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13087       break;
13088     }
13089
13090     // In any sort of PIC mode addresses need to be computed at runtime by
13091     // adding in a register or some sort of table lookup.  These can't
13092     // be used as immediates.
13093     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13094       return;
13095
13096     // If we are in non-pic codegen mode, we allow the address of a global (with
13097     // an optional displacement) to be used with 'i'.
13098     GlobalAddressSDNode *GA = 0;
13099     int64_t Offset = 0;
13100
13101     // Match either (GA), (GA+C), (GA+C1+C2), etc.
13102     while (1) {
13103       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13104         Offset += GA->getOffset();
13105         break;
13106       } else if (Op.getOpcode() == ISD::ADD) {
13107         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13108           Offset += C->getZExtValue();
13109           Op = Op.getOperand(0);
13110           continue;
13111         }
13112       } else if (Op.getOpcode() == ISD::SUB) {
13113         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13114           Offset += -C->getZExtValue();
13115           Op = Op.getOperand(0);
13116           continue;
13117         }
13118       }
13119
13120       // Otherwise, this isn't something we can handle, reject it.
13121       return;
13122     }
13123
13124     const GlobalValue *GV = GA->getGlobal();
13125     // If we require an extra load to get this address, as in PIC mode, we
13126     // can't accept it.
13127     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
13128                                                         getTargetMachine())))
13129       return;
13130
13131     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
13132                                         GA->getValueType(0), Offset);
13133     break;
13134   }
13135   }
13136
13137   if (Result.getNode()) {
13138     Ops.push_back(Result);
13139     return;
13140   }
13141   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13142 }
13143
13144 std::pair<unsigned, const TargetRegisterClass*>
13145 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
13146                                                 EVT VT) const {
13147   // First, see if this is a constraint that directly corresponds to an LLVM
13148   // register class.
13149   if (Constraint.size() == 1) {
13150     // GCC Constraint Letters
13151     switch (Constraint[0]) {
13152     default: break;
13153       // TODO: Slight differences here in allocation order and leaving
13154       // RIP in the class. Do they matter any more here than they do
13155       // in the normal allocation?
13156     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13157       if (Subtarget->is64Bit()) {
13158         if (VT == MVT::i32 || VT == MVT::f32)
13159           return std::make_pair(0U, X86::GR32RegisterClass);
13160         else if (VT == MVT::i16)
13161           return std::make_pair(0U, X86::GR16RegisterClass);
13162         else if (VT == MVT::i8 || VT == MVT::i1)
13163           return std::make_pair(0U, X86::GR8RegisterClass);
13164         else if (VT == MVT::i64 || VT == MVT::f64)
13165           return std::make_pair(0U, X86::GR64RegisterClass);
13166         break;
13167       }
13168       // 32-bit fallthrough
13169     case 'Q':   // Q_REGS
13170       if (VT == MVT::i32 || VT == MVT::f32)
13171         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
13172       else if (VT == MVT::i16)
13173         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
13174       else if (VT == MVT::i8 || VT == MVT::i1)
13175         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
13176       else if (VT == MVT::i64)
13177         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
13178       break;
13179     case 'r':   // GENERAL_REGS
13180     case 'l':   // INDEX_REGS
13181       if (VT == MVT::i8 || VT == MVT::i1)
13182         return std::make_pair(0U, X86::GR8RegisterClass);
13183       if (VT == MVT::i16)
13184         return std::make_pair(0U, X86::GR16RegisterClass);
13185       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
13186         return std::make_pair(0U, X86::GR32RegisterClass);
13187       return std::make_pair(0U, X86::GR64RegisterClass);
13188     case 'R':   // LEGACY_REGS
13189       if (VT == MVT::i8 || VT == MVT::i1)
13190         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13191       if (VT == MVT::i16)
13192         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13193       if (VT == MVT::i32 || !Subtarget->is64Bit())
13194         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13195       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13196     case 'f':  // FP Stack registers.
13197       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13198       // value to the correct fpstack register class.
13199       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13200         return std::make_pair(0U, X86::RFP32RegisterClass);
13201       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13202         return std::make_pair(0U, X86::RFP64RegisterClass);
13203       return std::make_pair(0U, X86::RFP80RegisterClass);
13204     case 'y':   // MMX_REGS if MMX allowed.
13205       if (!Subtarget->hasMMX()) break;
13206       return std::make_pair(0U, X86::VR64RegisterClass);
13207     case 'Y':   // SSE_REGS if SSE2 allowed
13208       if (!Subtarget->hasXMMInt()) break;
13209       // FALL THROUGH.
13210     case 'x':   // SSE_REGS if SSE1 allowed
13211       if (!Subtarget->hasXMM()) break;
13212
13213       switch (VT.getSimpleVT().SimpleTy) {
13214       default: break;
13215       // Scalar SSE types.
13216       case MVT::f32:
13217       case MVT::i32:
13218         return std::make_pair(0U, X86::FR32RegisterClass);
13219       case MVT::f64:
13220       case MVT::i64:
13221         return std::make_pair(0U, X86::FR64RegisterClass);
13222       // Vector types.
13223       case MVT::v16i8:
13224       case MVT::v8i16:
13225       case MVT::v4i32:
13226       case MVT::v2i64:
13227       case MVT::v4f32:
13228       case MVT::v2f64:
13229         return std::make_pair(0U, X86::VR128RegisterClass);
13230       }
13231       break;
13232     }
13233   }
13234
13235   // Use the default implementation in TargetLowering to convert the register
13236   // constraint into a member of a register class.
13237   std::pair<unsigned, const TargetRegisterClass*> Res;
13238   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13239
13240   // Not found as a standard register?
13241   if (Res.second == 0) {
13242     // Map st(0) -> st(7) -> ST0
13243     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13244         tolower(Constraint[1]) == 's' &&
13245         tolower(Constraint[2]) == 't' &&
13246         Constraint[3] == '(' &&
13247         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13248         Constraint[5] == ')' &&
13249         Constraint[6] == '}') {
13250
13251       Res.first = X86::ST0+Constraint[4]-'0';
13252       Res.second = X86::RFP80RegisterClass;
13253       return Res;
13254     }
13255
13256     // GCC allows "st(0)" to be called just plain "st".
13257     if (StringRef("{st}").equals_lower(Constraint)) {
13258       Res.first = X86::ST0;
13259       Res.second = X86::RFP80RegisterClass;
13260       return Res;
13261     }
13262
13263     // flags -> EFLAGS
13264     if (StringRef("{flags}").equals_lower(Constraint)) {
13265       Res.first = X86::EFLAGS;
13266       Res.second = X86::CCRRegisterClass;
13267       return Res;
13268     }
13269
13270     // 'A' means EAX + EDX.
13271     if (Constraint == "A") {
13272       Res.first = X86::EAX;
13273       Res.second = X86::GR32_ADRegisterClass;
13274       return Res;
13275     }
13276     return Res;
13277   }
13278
13279   // Otherwise, check to see if this is a register class of the wrong value
13280   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13281   // turn into {ax},{dx}.
13282   if (Res.second->hasType(VT))
13283     return Res;   // Correct type already, nothing to do.
13284
13285   // All of the single-register GCC register classes map their values onto
13286   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13287   // really want an 8-bit or 32-bit register, map to the appropriate register
13288   // class and return the appropriate register.
13289   if (Res.second == X86::GR16RegisterClass) {
13290     if (VT == MVT::i8) {
13291       unsigned DestReg = 0;
13292       switch (Res.first) {
13293       default: break;
13294       case X86::AX: DestReg = X86::AL; break;
13295       case X86::DX: DestReg = X86::DL; break;
13296       case X86::CX: DestReg = X86::CL; break;
13297       case X86::BX: DestReg = X86::BL; break;
13298       }
13299       if (DestReg) {
13300         Res.first = DestReg;
13301         Res.second = X86::GR8RegisterClass;
13302       }
13303     } else if (VT == MVT::i32) {
13304       unsigned DestReg = 0;
13305       switch (Res.first) {
13306       default: break;
13307       case X86::AX: DestReg = X86::EAX; break;
13308       case X86::DX: DestReg = X86::EDX; break;
13309       case X86::CX: DestReg = X86::ECX; break;
13310       case X86::BX: DestReg = X86::EBX; break;
13311       case X86::SI: DestReg = X86::ESI; break;
13312       case X86::DI: DestReg = X86::EDI; break;
13313       case X86::BP: DestReg = X86::EBP; break;
13314       case X86::SP: DestReg = X86::ESP; break;
13315       }
13316       if (DestReg) {
13317         Res.first = DestReg;
13318         Res.second = X86::GR32RegisterClass;
13319       }
13320     } else if (VT == MVT::i64) {
13321       unsigned DestReg = 0;
13322       switch (Res.first) {
13323       default: break;
13324       case X86::AX: DestReg = X86::RAX; break;
13325       case X86::DX: DestReg = X86::RDX; break;
13326       case X86::CX: DestReg = X86::RCX; break;
13327       case X86::BX: DestReg = X86::RBX; break;
13328       case X86::SI: DestReg = X86::RSI; break;
13329       case X86::DI: DestReg = X86::RDI; break;
13330       case X86::BP: DestReg = X86::RBP; break;
13331       case X86::SP: DestReg = X86::RSP; break;
13332       }
13333       if (DestReg) {
13334         Res.first = DestReg;
13335         Res.second = X86::GR64RegisterClass;
13336       }
13337     }
13338   } else if (Res.second == X86::FR32RegisterClass ||
13339              Res.second == X86::FR64RegisterClass ||
13340              Res.second == X86::VR128RegisterClass) {
13341     // Handle references to XMM physical registers that got mapped into the
13342     // wrong class.  This can happen with constraints like {xmm0} where the
13343     // target independent register mapper will just pick the first match it can
13344     // find, ignoring the required type.
13345     if (VT == MVT::f32)
13346       Res.second = X86::FR32RegisterClass;
13347     else if (VT == MVT::f64)
13348       Res.second = X86::FR64RegisterClass;
13349     else if (X86::VR128RegisterClass->hasType(VT))
13350       Res.second = X86::VR128RegisterClass;
13351   }
13352
13353   return Res;
13354 }