]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/lib/Target/X86/X86ISelLowering.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / 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 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89   EVT ElVT = VT.getVectorElementType();
90
91   int Factor = VT.getSizeInBits() / 128;
92
93   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                   ElVT,
95                                   VT.getVectorNumElements() / Factor);
96
97   // Extract from UNDEF is UNDEF.
98   if (Vec.getOpcode() == ISD::UNDEF)
99     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101   if (isa<ConstantSDNode>(Idx)) {
102     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105     // we can match to VEXTRACTF128.
106     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108     // This is the index of the first element of the 128-bit chunk
109     // we want.
110     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                  * ElemsPerChunk);
112
113     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                  VecIdx);
117
118     return Result;
119   }
120
121   return SDValue();
122 }
123
124 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference.  Idx is an index in the 128 bits
127 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setBooleanContents(ZeroOrOneBooleanContent);
225
226   // For 64-bit since we have so many registers use the ILP scheduler, for
227   // 32-bit code use the register pressure specific scheduling.
228   if (Subtarget->is64Bit())
229     setSchedulingPreference(Sched::ILP);
230   else
231     setSchedulingPreference(Sched::RegPressure);
232   setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235     // Setup Windows compiler runtime calls.
236     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238     setLibcallName(RTLIB::SREM_I64, "_allrem");
239     setLibcallName(RTLIB::UREM_I64, "_aullrem");
240     setLibcallName(RTLIB::MUL_I64, "_allmul");
241     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
242     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
243     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
244     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
245     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
246     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
247     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
248     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
249     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
250   }
251
252   if (Subtarget->isTargetDarwin()) {
253     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
254     setUseUnderscoreSetJmp(false);
255     setUseUnderscoreLongJmp(false);
256   } else if (Subtarget->isTargetMingw()) {
257     // MS runtime is weird: it exports _setjmp, but longjmp!
258     setUseUnderscoreSetJmp(true);
259     setUseUnderscoreLongJmp(false);
260   } else {
261     setUseUnderscoreSetJmp(true);
262     setUseUnderscoreLongJmp(true);
263   }
264
265   // Set up the register classes.
266   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
267   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
268   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
269   if (Subtarget->is64Bit())
270     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
271
272   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
273
274   // We don't accept any truncstore of integer registers.
275   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
276   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
277   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
278   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
279   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
280   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
281
282   // SETOEQ and SETUNE require checking two conditions.
283   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
284   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
285   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
286   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
287   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
288   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
289
290   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
291   // operation.
292   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
293   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
294   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
295
296   if (Subtarget->is64Bit()) {
297     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
298     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
299   } else if (!UseSoftFloat) {
300     // We have an algorithm for SSE2->double, and we turn this into a
301     // 64-bit FILD followed by conditional FADD for other targets.
302     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
303     // We have an algorithm for SSE2, and we turn this into a 64-bit
304     // FILD for other targets.
305     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
306   }
307
308   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
309   // this operation.
310   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
311   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
312
313   if (!UseSoftFloat) {
314     // SSE has no i16 to fp conversion, only i32
315     if (X86ScalarSSEf32) {
316       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
317       // f32 and f64 cases are Legal, f80 case is not
318       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
319     } else {
320       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
321       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
322     }
323   } else {
324     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
325     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
326   }
327
328   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
329   // are Legal, f80 is custom lowered.
330   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
331   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
332
333   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
336   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
337
338   if (X86ScalarSSEf32) {
339     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
340     // f32 and f64 cases are Legal, f80 case is not
341     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
342   } else {
343     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
344     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
345   }
346
347   // Handle FP_TO_UINT by promoting the destination to a larger signed
348   // conversion.
349   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
350   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
351   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
352
353   if (Subtarget->is64Bit()) {
354     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
355     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
356   } else if (!UseSoftFloat) {
357     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
358       // Expand FP_TO_UINT into a select.
359       // FIXME: We would like to use a Custom expander here eventually to do
360       // the optimal thing for SSE vs. the default expansion in the legalizer.
361       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
362     else
363       // With SSE3 we can use fisttpll to convert to a signed i64; without
364       // SSE, we're stuck with a fistpll.
365       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
366   }
367
368   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
369   if (!X86ScalarSSEf64) {
370     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
371     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
372     if (Subtarget->is64Bit()) {
373       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
374       // Without SSE, i64->f64 goes through memory.
375       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
376     }
377   }
378
379   // Scalar integer divide and remainder are lowered to use operations that
380   // produce two results, to match the available instructions. This exposes
381   // the two-result form to trivial CSE, which is able to combine x/y and x%y
382   // into a single instruction.
383   //
384   // Scalar integer multiply-high is also lowered to use two-result
385   // operations, to match the available instructions. However, plain multiply
386   // (low) operations are left as Legal, as there are single-result
387   // instructions for this in x86. Using the two-result multiply instructions
388   // when both high and low results are needed must be arranged by dagcombine.
389   for (unsigned i = 0, e = 4; i != e; ++i) {
390     MVT VT = IntVTs[i];
391     setOperationAction(ISD::MULHS, VT, Expand);
392     setOperationAction(ISD::MULHU, VT, Expand);
393     setOperationAction(ISD::SDIV, VT, Expand);
394     setOperationAction(ISD::UDIV, VT, Expand);
395     setOperationAction(ISD::SREM, VT, Expand);
396     setOperationAction(ISD::UREM, VT, Expand);
397
398     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
399     setOperationAction(ISD::ADDC, VT, Custom);
400     setOperationAction(ISD::ADDE, VT, Custom);
401     setOperationAction(ISD::SUBC, VT, Custom);
402     setOperationAction(ISD::SUBE, VT, Custom);
403   }
404
405   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
406   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
407   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
408   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
409   if (Subtarget->is64Bit())
410     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
411   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
412   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
413   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
414   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
415   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
416   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
417   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
418   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
419
420   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
421   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
422   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
423   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
424   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
425   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
426   if (Subtarget->is64Bit()) {
427     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
428     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
429   }
430
431   if (Subtarget->hasPOPCNT()) {
432     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
433   } else {
434     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
435     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
436     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
437     if (Subtarget->is64Bit())
438       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
439   }
440
441   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
442   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
443
444   // These should be promoted to a larger select which is supported.
445   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
446   // X86 wants to expand cmov itself.
447   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
448   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
449   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
450   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
451   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
452   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
454   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
455   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
456   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
457   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
458   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
459   if (Subtarget->is64Bit()) {
460     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
461     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
462   }
463   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
464
465   // Darwin ABI issue.
466   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
467   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
468   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
469   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
470   if (Subtarget->is64Bit())
471     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
472   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
473   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
474   if (Subtarget->is64Bit()) {
475     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
476     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
477     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
478     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
479     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
480   }
481   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
482   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
483   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
484   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
485   if (Subtarget->is64Bit()) {
486     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
487     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
488     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
489   }
490
491   if (Subtarget->hasXMM())
492     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
493
494   // We may not have a libcall for MEMBARRIER so we should lower this.
495   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
496
497   // On X86 and X86-64, atomic operations are lowered to locked instructions.
498   // Locked instructions, in turn, have implicit fence semantics (all memory
499   // operations are flushed before issuing the locked instruction, and they
500   // are not buffered), so we can fold away the common pattern of
501   // fence-atomic-fence.
502   setShouldFoldAtomicFences(true);
503
504   // Expand certain atomics
505   for (unsigned i = 0, e = 4; i != e; ++i) {
506     MVT VT = IntVTs[i];
507     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
509   }
510
511   if (!Subtarget->is64Bit()) {
512     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
513     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
514     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
515     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
516     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
519   }
520
521   // FIXME - use subtarget debug flags
522   if (!Subtarget->isTargetDarwin() &&
523       !Subtarget->isTargetELF() &&
524       !Subtarget->isTargetCygMing()) {
525     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
526   }
527
528   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
529   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
530   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
531   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
532   if (Subtarget->is64Bit()) {
533     setExceptionPointerRegister(X86::RAX);
534     setExceptionSelectorRegister(X86::RDX);
535   } else {
536     setExceptionPointerRegister(X86::EAX);
537     setExceptionSelectorRegister(X86::EDX);
538   }
539   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
540   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
541
542   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
543
544   setOperationAction(ISD::TRAP, MVT::Other, Legal);
545
546   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
547   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
548   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
549   if (Subtarget->is64Bit()) {
550     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
551     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
552   } else {
553     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
554     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
555   }
556
557   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
558   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
559   setOperationAction(ISD::DYNAMIC_STACKALLOC,
560                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
561                      (Subtarget->isTargetCOFF()
562                       && !Subtarget->isTargetEnvMacho()
563                       ? Custom : Expand));
564
565   if (!UseSoftFloat && X86ScalarSSEf64) {
566     // f32 and f64 use SSE.
567     // Set up the FP register classes.
568     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
569     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
570
571     // Use ANDPD to simulate FABS.
572     setOperationAction(ISD::FABS , MVT::f64, Custom);
573     setOperationAction(ISD::FABS , MVT::f32, Custom);
574
575     // Use XORP to simulate FNEG.
576     setOperationAction(ISD::FNEG , MVT::f64, Custom);
577     setOperationAction(ISD::FNEG , MVT::f32, Custom);
578
579     // Use ANDPD and ORPD to simulate FCOPYSIGN.
580     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
581     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
582
583     // Lower this to FGETSIGNx86 plus an AND.
584     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
585     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
586
587     // We don't support sin/cos/fmod
588     setOperationAction(ISD::FSIN , MVT::f64, Expand);
589     setOperationAction(ISD::FCOS , MVT::f64, Expand);
590     setOperationAction(ISD::FSIN , MVT::f32, Expand);
591     setOperationAction(ISD::FCOS , MVT::f32, Expand);
592
593     // Expand FP immediates into loads from the stack, except for the special
594     // cases we handle.
595     addLegalFPImmediate(APFloat(+0.0)); // xorpd
596     addLegalFPImmediate(APFloat(+0.0f)); // xorps
597   } else if (!UseSoftFloat && X86ScalarSSEf32) {
598     // Use SSE for f32, x87 for f64.
599     // Set up the FP register classes.
600     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
601     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
602
603     // Use ANDPS to simulate FABS.
604     setOperationAction(ISD::FABS , MVT::f32, Custom);
605
606     // Use XORP to simulate FNEG.
607     setOperationAction(ISD::FNEG , MVT::f32, Custom);
608
609     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
610
611     // Use ANDPS and ORPS to simulate FCOPYSIGN.
612     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
613     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
614
615     // We don't support sin/cos/fmod
616     setOperationAction(ISD::FSIN , MVT::f32, Expand);
617     setOperationAction(ISD::FCOS , MVT::f32, Expand);
618
619     // Special cases we handle for FP constants.
620     addLegalFPImmediate(APFloat(+0.0f)); // xorps
621     addLegalFPImmediate(APFloat(+0.0)); // FLD0
622     addLegalFPImmediate(APFloat(+1.0)); // FLD1
623     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
624     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
625
626     if (!UnsafeFPMath) {
627       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
628       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
629     }
630   } else if (!UseSoftFloat) {
631     // f32 and f64 in x87.
632     // Set up the FP register classes.
633     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
634     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
635
636     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
637     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
638     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
639     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
640
641     if (!UnsafeFPMath) {
642       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
643       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
644     }
645     addLegalFPImmediate(APFloat(+0.0)); // FLD0
646     addLegalFPImmediate(APFloat(+1.0)); // FLD1
647     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
648     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
649     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
653   }
654
655   // We don't support FMA.
656   setOperationAction(ISD::FMA, MVT::f64, Expand);
657   setOperationAction(ISD::FMA, MVT::f32, Expand);
658
659   // Long double always uses X87.
660   if (!UseSoftFloat) {
661     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
662     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
663     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
664     {
665       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
666       addLegalFPImmediate(TmpFlt);  // FLD0
667       TmpFlt.changeSign();
668       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
669
670       bool ignored;
671       APFloat TmpFlt2(+1.0);
672       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
673                       &ignored);
674       addLegalFPImmediate(TmpFlt2);  // FLD1
675       TmpFlt2.changeSign();
676       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
677     }
678
679     if (!UnsafeFPMath) {
680       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
681       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
682     }
683
684     setOperationAction(ISD::FMA, MVT::f80, Expand);
685   }
686
687   // Always use a library call for pow.
688   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
689   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
690   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
691
692   setOperationAction(ISD::FLOG, MVT::f80, Expand);
693   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
694   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
695   setOperationAction(ISD::FEXP, MVT::f80, Expand);
696   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
697
698   // First set operation action for all vector types to either promote
699   // (for widening) or expand (for scalarization). Then we will selectively
700   // turn on ones that can be effectively codegen'd.
701   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
702        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
703     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
718     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
720     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
721     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
753     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
757     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
758          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
759       setTruncStoreAction((MVT::SimpleValueType)VT,
760                           (MVT::SimpleValueType)InnerVT, Expand);
761     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
762     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
763     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
764   }
765
766   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
767   // with -msoft-float, disable use of MMX as well.
768   if (!UseSoftFloat && Subtarget->hasMMX()) {
769     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
770     // No operations on x86mmx supported, everything uses intrinsics.
771   }
772
773   // MMX-sized vectors (other than x86mmx) are expected to be expanded
774   // into smaller operations.
775   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
776   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
777   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
778   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
779   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
780   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
781   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
782   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
783   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
784   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
785   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
786   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
787   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
788   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
789   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
790   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
791   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
792   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
793   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
794   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
795   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
796   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
797   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
798   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
799   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
800   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
801   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
802   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
803   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
804
805   if (!UseSoftFloat && Subtarget->hasXMM()) {
806     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
807
808     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
809     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
810     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
811     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
812     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
813     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
814     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
815     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
816     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
817     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
818     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
819     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
820   }
821
822   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
823     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
824
825     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
826     // registers cannot be used even for integer operations.
827     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
828     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
829     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
830     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
831
832     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
833     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
834     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
835     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
836     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
837     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
838     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
839     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
840     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
841     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
842     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
844     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
845     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
846     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
847     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
848
849     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
850     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
851     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
852     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
853
854     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
855     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
856     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
857     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
858     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
859
860     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
861     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
862     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
863     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
864     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
865
866     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
867     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
868       EVT VT = (MVT::SimpleValueType)i;
869       // Do not attempt to custom lower non-power-of-2 vectors
870       if (!isPowerOf2_32(VT.getVectorNumElements()))
871         continue;
872       // Do not attempt to custom lower non-128-bit vectors
873       if (!VT.is128BitVector())
874         continue;
875       setOperationAction(ISD::BUILD_VECTOR,
876                          VT.getSimpleVT().SimpleTy, Custom);
877       setOperationAction(ISD::VECTOR_SHUFFLE,
878                          VT.getSimpleVT().SimpleTy, Custom);
879       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
880                          VT.getSimpleVT().SimpleTy, Custom);
881     }
882
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
889
890     if (Subtarget->is64Bit()) {
891       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
892       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
893     }
894
895     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
896     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
897       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
898       EVT VT = SVT;
899
900       // Do not attempt to promote non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903
904       setOperationAction(ISD::AND,    SVT, Promote);
905       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
906       setOperationAction(ISD::OR,     SVT, Promote);
907       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    SVT, Promote);
909       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   SVT, Promote);
911       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, SVT, Promote);
913       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
914     }
915
916     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926   }
927
928   if (Subtarget->hasSSE41()) {
929     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
930     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
931     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
932     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
933     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
934     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
935     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
936     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
937     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
938     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
939
940     // FIXME: Do we need to handle scalar-to-vector here?
941     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
942
943     // Can turn SHL into an integer multiply.
944     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
945     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
946
947     // i8 and i16 vectors are custom , because the source register and source
948     // source memory operand types are not the same width.  f32 vectors are
949     // custom since the immediate controlling the insert encodes additional
950     // information.
951     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
952     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
953     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
954     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
955
956     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
957     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
958     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
959     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
960
961     if (Subtarget->is64Bit()) {
962       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
963       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
964     }
965   }
966
967   if (Subtarget->hasSSE2()) {
968     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
969     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
970     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
971
972     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
973     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
974     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
975
976     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
977     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
978   }
979
980   if (Subtarget->hasSSE42())
981     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
982
983   if (!UseSoftFloat && Subtarget->hasAVX()) {
984     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
985     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
986     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
987     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
988     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
989
990     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
991     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
992     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
993
994     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
995     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
996     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
997     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
998     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
999     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1000
1001     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1002     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1003     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1004     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1005     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1006     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1007
1008     // Custom lower several nodes for 256-bit types.
1009     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1010                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1011       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1012       EVT VT = SVT;
1013
1014       // Extract subvector is special because the value type
1015       // (result) is 128-bit but the source is 256-bit wide.
1016       if (VT.is128BitVector())
1017         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1018
1019       // Do not attempt to custom lower other non-256-bit vectors
1020       if (!VT.is256BitVector())
1021         continue;
1022
1023       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1024       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1025       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1026       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1027       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1028       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1029     }
1030
1031     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1032     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1033       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1034       EVT VT = SVT;
1035
1036       // Do not attempt to promote non-256-bit vectors
1037       if (!VT.is256BitVector())
1038         continue;
1039
1040       setOperationAction(ISD::AND,    SVT, Promote);
1041       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1042       setOperationAction(ISD::OR,     SVT, Promote);
1043       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1044       setOperationAction(ISD::XOR,    SVT, Promote);
1045       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1046       setOperationAction(ISD::LOAD,   SVT, Promote);
1047       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1048       setOperationAction(ISD::SELECT, SVT, Promote);
1049       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1050     }
1051   }
1052
1053   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1054   // of this type with custom code.
1055   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1056          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1057     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1058   }
1059
1060   // We want to custom lower some of our intrinsics.
1061   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1062
1063
1064   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1065   // handle type legalization for these operations here.
1066   //
1067   // FIXME: We really should do custom legalization for addition and
1068   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1069   // than generic legalization for 64-bit multiplication-with-overflow, though.
1070   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1071     // Add/Sub/Mul with overflow operations are custom lowered.
1072     MVT VT = IntVTs[i];
1073     setOperationAction(ISD::SADDO, VT, Custom);
1074     setOperationAction(ISD::UADDO, VT, Custom);
1075     setOperationAction(ISD::SSUBO, VT, Custom);
1076     setOperationAction(ISD::USUBO, VT, Custom);
1077     setOperationAction(ISD::SMULO, VT, Custom);
1078     setOperationAction(ISD::UMULO, VT, Custom);
1079   }
1080
1081   // There are no 8-bit 3-address imul/mul instructions
1082   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1083   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1084
1085   if (!Subtarget->is64Bit()) {
1086     // These libcalls are not available in 32-bit.
1087     setLibcallName(RTLIB::SHL_I128, 0);
1088     setLibcallName(RTLIB::SRL_I128, 0);
1089     setLibcallName(RTLIB::SRA_I128, 0);
1090   }
1091
1092   // We have target-specific dag combine patterns for the following nodes:
1093   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1094   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1095   setTargetDAGCombine(ISD::BUILD_VECTOR);
1096   setTargetDAGCombine(ISD::SELECT);
1097   setTargetDAGCombine(ISD::SHL);
1098   setTargetDAGCombine(ISD::SRA);
1099   setTargetDAGCombine(ISD::SRL);
1100   setTargetDAGCombine(ISD::OR);
1101   setTargetDAGCombine(ISD::AND);
1102   setTargetDAGCombine(ISD::ADD);
1103   setTargetDAGCombine(ISD::SUB);
1104   setTargetDAGCombine(ISD::STORE);
1105   setTargetDAGCombine(ISD::ZERO_EXTEND);
1106   setTargetDAGCombine(ISD::SINT_TO_FP);
1107   if (Subtarget->is64Bit())
1108     setTargetDAGCombine(ISD::MUL);
1109
1110   computeRegisterProperties();
1111
1112   // On Darwin, -Os means optimize for size without hurting performance,
1113   // do not reduce the limit.
1114   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1115   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1116   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1117   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1118   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1119   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1120   setPrefLoopAlignment(16);
1121   benefitFromCodePlacementOpt = true;
1122
1123   setPrefFunctionAlignment(4);
1124 }
1125
1126
1127 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1128   return MVT::i8;
1129 }
1130
1131
1132 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1133 /// the desired ByVal argument alignment.
1134 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1135   if (MaxAlign == 16)
1136     return;
1137   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1138     if (VTy->getBitWidth() == 128)
1139       MaxAlign = 16;
1140   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1141     unsigned EltAlign = 0;
1142     getMaxByValAlign(ATy->getElementType(), EltAlign);
1143     if (EltAlign > MaxAlign)
1144       MaxAlign = EltAlign;
1145   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1146     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1147       unsigned EltAlign = 0;
1148       getMaxByValAlign(STy->getElementType(i), EltAlign);
1149       if (EltAlign > MaxAlign)
1150         MaxAlign = EltAlign;
1151       if (MaxAlign == 16)
1152         break;
1153     }
1154   }
1155   return;
1156 }
1157
1158 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1159 /// function arguments in the caller parameter area. For X86, aggregates
1160 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1161 /// are at 4-byte boundaries.
1162 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1163   if (Subtarget->is64Bit()) {
1164     // Max of 8 and alignment of type.
1165     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1166     if (TyAlign > 8)
1167       return TyAlign;
1168     return 8;
1169   }
1170
1171   unsigned Align = 4;
1172   if (Subtarget->hasXMM())
1173     getMaxByValAlign(Ty, Align);
1174   return Align;
1175 }
1176
1177 /// getOptimalMemOpType - Returns the target specific optimal type for load
1178 /// and store operations as a result of memset, memcpy, and memmove
1179 /// lowering. If DstAlign is zero that means it's safe to destination
1180 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1181 /// means there isn't a need to check it against alignment requirement,
1182 /// probably because the source does not need to be loaded. If
1183 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1184 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1185 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1186 /// constant so it does not need to be loaded.
1187 /// It returns EVT::Other if the type should be determined using generic
1188 /// target-independent logic.
1189 EVT
1190 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1191                                        unsigned DstAlign, unsigned SrcAlign,
1192                                        bool NonScalarIntSafe,
1193                                        bool MemcpyStrSrc,
1194                                        MachineFunction &MF) const {
1195   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1196   // linux.  This is because the stack realignment code can't handle certain
1197   // cases like PR2962.  This should be removed when PR2962 is fixed.
1198   const Function *F = MF.getFunction();
1199   if (NonScalarIntSafe &&
1200       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1201     if (Size >= 16 &&
1202         (Subtarget->isUnalignedMemAccessFast() ||
1203          ((DstAlign == 0 || DstAlign >= 16) &&
1204           (SrcAlign == 0 || SrcAlign >= 16))) &&
1205         Subtarget->getStackAlignment() >= 16) {
1206       if (Subtarget->hasSSE2())
1207         return MVT::v4i32;
1208       if (Subtarget->hasSSE1())
1209         return MVT::v4f32;
1210     } else if (!MemcpyStrSrc && Size >= 8 &&
1211                !Subtarget->is64Bit() &&
1212                Subtarget->getStackAlignment() >= 8 &&
1213                Subtarget->hasXMMInt()) {
1214       // Do not use f64 to lower memcpy if source is string constant. It's
1215       // better to use i32 to avoid the loads.
1216       return MVT::f64;
1217     }
1218   }
1219   if (Subtarget->is64Bit() && Size >= 8)
1220     return MVT::i64;
1221   return MVT::i32;
1222 }
1223
1224 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1225 /// current function.  The returned value is a member of the
1226 /// MachineJumpTableInfo::JTEntryKind enum.
1227 unsigned X86TargetLowering::getJumpTableEncoding() const {
1228   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1229   // symbol.
1230   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1231       Subtarget->isPICStyleGOT())
1232     return MachineJumpTableInfo::EK_Custom32;
1233
1234   // Otherwise, use the normal jump table encoding heuristics.
1235   return TargetLowering::getJumpTableEncoding();
1236 }
1237
1238 const MCExpr *
1239 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1240                                              const MachineBasicBlock *MBB,
1241                                              unsigned uid,MCContext &Ctx) const{
1242   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1243          Subtarget->isPICStyleGOT());
1244   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1245   // entries.
1246   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1247                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1248 }
1249
1250 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1251 /// jumptable.
1252 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1253                                                     SelectionDAG &DAG) const {
1254   if (!Subtarget->is64Bit())
1255     // This doesn't have DebugLoc associated with it, but is not really the
1256     // same as a Register.
1257     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1258   return Table;
1259 }
1260
1261 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1262 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1263 /// MCExpr.
1264 const MCExpr *X86TargetLowering::
1265 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1266                              MCContext &Ctx) const {
1267   // X86-64 uses RIP relative addressing based on the jump table label.
1268   if (Subtarget->isPICStyleRIPRel())
1269     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1270
1271   // Otherwise, the reference is relative to the PIC base.
1272   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1273 }
1274
1275 // FIXME: Why this routine is here? Move to RegInfo!
1276 std::pair<const TargetRegisterClass*, uint8_t>
1277 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1278   const TargetRegisterClass *RRC = 0;
1279   uint8_t Cost = 1;
1280   switch (VT.getSimpleVT().SimpleTy) {
1281   default:
1282     return TargetLowering::findRepresentativeClass(VT);
1283   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1284     RRC = (Subtarget->is64Bit()
1285            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1286     break;
1287   case MVT::x86mmx:
1288     RRC = X86::VR64RegisterClass;
1289     break;
1290   case MVT::f32: case MVT::f64:
1291   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1292   case MVT::v4f32: case MVT::v2f64:
1293   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1294   case MVT::v4f64:
1295     RRC = X86::VR128RegisterClass;
1296     break;
1297   }
1298   return std::make_pair(RRC, Cost);
1299 }
1300
1301 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1302                                                unsigned &Offset) const {
1303   if (!Subtarget->isTargetLinux())
1304     return false;
1305
1306   if (Subtarget->is64Bit()) {
1307     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1308     Offset = 0x28;
1309     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1310       AddressSpace = 256;
1311     else
1312       AddressSpace = 257;
1313   } else {
1314     // %gs:0x14 on i386
1315     Offset = 0x14;
1316     AddressSpace = 256;
1317   }
1318   return true;
1319 }
1320
1321
1322 //===----------------------------------------------------------------------===//
1323 //               Return Value Calling Convention Implementation
1324 //===----------------------------------------------------------------------===//
1325
1326 #include "X86GenCallingConv.inc"
1327
1328 bool
1329 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1330                                   MachineFunction &MF, bool isVarArg,
1331                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1332                         LLVMContext &Context) const {
1333   SmallVector<CCValAssign, 16> RVLocs;
1334   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1335                  RVLocs, Context);
1336   return CCInfo.CheckReturn(Outs, RetCC_X86);
1337 }
1338
1339 SDValue
1340 X86TargetLowering::LowerReturn(SDValue Chain,
1341                                CallingConv::ID CallConv, bool isVarArg,
1342                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1343                                const SmallVectorImpl<SDValue> &OutVals,
1344                                DebugLoc dl, SelectionDAG &DAG) const {
1345   MachineFunction &MF = DAG.getMachineFunction();
1346   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1347
1348   SmallVector<CCValAssign, 16> RVLocs;
1349   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1350                  RVLocs, *DAG.getContext());
1351   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1352
1353   // Add the regs to the liveout set for the function.
1354   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1355   for (unsigned i = 0; i != RVLocs.size(); ++i)
1356     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1357       MRI.addLiveOut(RVLocs[i].getLocReg());
1358
1359   SDValue Flag;
1360
1361   SmallVector<SDValue, 6> RetOps;
1362   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1363   // Operand #1 = Bytes To Pop
1364   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1365                    MVT::i16));
1366
1367   // Copy the result values into the output registers.
1368   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1369     CCValAssign &VA = RVLocs[i];
1370     assert(VA.isRegLoc() && "Can only return in registers!");
1371     SDValue ValToCopy = OutVals[i];
1372     EVT ValVT = ValToCopy.getValueType();
1373
1374     // If this is x86-64, and we disabled SSE, we can't return FP values,
1375     // or SSE or MMX vectors.
1376     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1377          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1378           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1379       report_fatal_error("SSE register return with SSE disabled");
1380     }
1381     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1382     // llvm-gcc has never done it right and no one has noticed, so this
1383     // should be OK for now.
1384     if (ValVT == MVT::f64 &&
1385         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1386       report_fatal_error("SSE2 register return with SSE2 disabled");
1387
1388     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1389     // the RET instruction and handled by the FP Stackifier.
1390     if (VA.getLocReg() == X86::ST0 ||
1391         VA.getLocReg() == X86::ST1) {
1392       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1393       // change the value to the FP stack register class.
1394       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1395         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1396       RetOps.push_back(ValToCopy);
1397       // Don't emit a copytoreg.
1398       continue;
1399     }
1400
1401     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1402     // which is returned in RAX / RDX.
1403     if (Subtarget->is64Bit()) {
1404       if (ValVT == MVT::x86mmx) {
1405         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1406           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1407           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1408                                   ValToCopy);
1409           // If we don't have SSE2 available, convert to v4f32 so the generated
1410           // register is legal.
1411           if (!Subtarget->hasSSE2())
1412             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1413         }
1414       }
1415     }
1416
1417     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1418     Flag = Chain.getValue(1);
1419   }
1420
1421   // The x86-64 ABI for returning structs by value requires that we copy
1422   // the sret argument into %rax for the return. We saved the argument into
1423   // a virtual register in the entry block, so now we copy the value out
1424   // and into %rax.
1425   if (Subtarget->is64Bit() &&
1426       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1427     MachineFunction &MF = DAG.getMachineFunction();
1428     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1429     unsigned Reg = FuncInfo->getSRetReturnReg();
1430     assert(Reg &&
1431            "SRetReturnReg should have been set in LowerFormalArguments().");
1432     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1433
1434     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1435     Flag = Chain.getValue(1);
1436
1437     // RAX now acts like a return value.
1438     MRI.addLiveOut(X86::RAX);
1439   }
1440
1441   RetOps[0] = Chain;  // Update chain.
1442
1443   // Add the flag if we have it.
1444   if (Flag.getNode())
1445     RetOps.push_back(Flag);
1446
1447   return DAG.getNode(X86ISD::RET_FLAG, dl,
1448                      MVT::Other, &RetOps[0], RetOps.size());
1449 }
1450
1451 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1452   if (N->getNumValues() != 1)
1453     return false;
1454   if (!N->hasNUsesOfValue(1, 0))
1455     return false;
1456
1457   SDNode *Copy = *N->use_begin();
1458   if (Copy->getOpcode() != ISD::CopyToReg &&
1459       Copy->getOpcode() != ISD::FP_EXTEND)
1460     return false;
1461
1462   bool HasRet = false;
1463   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1464        UI != UE; ++UI) {
1465     if (UI->getOpcode() != X86ISD::RET_FLAG)
1466       return false;
1467     HasRet = true;
1468   }
1469
1470   return HasRet;
1471 }
1472
1473 EVT
1474 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1475                                             ISD::NodeType ExtendKind) const {
1476   MVT ReturnMVT;
1477   // TODO: Is this also valid on 32-bit?
1478   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1479     ReturnMVT = MVT::i8;
1480   else
1481     ReturnMVT = MVT::i32;
1482
1483   EVT MinVT = getRegisterType(Context, ReturnMVT);
1484   return VT.bitsLT(MinVT) ? MinVT : VT;
1485 }
1486
1487 /// LowerCallResult - Lower the result values of a call into the
1488 /// appropriate copies out of appropriate physical registers.
1489 ///
1490 SDValue
1491 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1492                                    CallingConv::ID CallConv, bool isVarArg,
1493                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1494                                    DebugLoc dl, SelectionDAG &DAG,
1495                                    SmallVectorImpl<SDValue> &InVals) const {
1496
1497   // Assign locations to each value returned by this call.
1498   SmallVector<CCValAssign, 16> RVLocs;
1499   bool Is64Bit = Subtarget->is64Bit();
1500   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1501                  getTargetMachine(), RVLocs, *DAG.getContext());
1502   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1503
1504   // Copy all of the result registers out of their specified physreg.
1505   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506     CCValAssign &VA = RVLocs[i];
1507     EVT CopyVT = VA.getValVT();
1508
1509     // If this is x86-64, and we disabled SSE, we can't return FP values
1510     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1511         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1512       report_fatal_error("SSE register return with SSE disabled");
1513     }
1514
1515     SDValue Val;
1516
1517     // If this is a call to a function that returns an fp value on the floating
1518     // point stack, we must guarantee the the value is popped from the stack, so
1519     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1520     // if the return value is not used. We use the FpPOP_RETVAL instruction
1521     // instead.
1522     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1523       // If we prefer to use the value in xmm registers, copy it out as f80 and
1524       // use a truncate to move it from fp stack reg to xmm reg.
1525       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1526       SDValue Ops[] = { Chain, InFlag };
1527       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1528                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1529       Val = Chain.getValue(0);
1530
1531       // Round the f80 to the right size, which also moves it to the appropriate
1532       // xmm register.
1533       if (CopyVT != VA.getValVT())
1534         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1535                           // This truncation won't change the value.
1536                           DAG.getIntPtrConstant(1));
1537     } else {
1538       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1539                                  CopyVT, InFlag).getValue(1);
1540       Val = Chain.getValue(0);
1541     }
1542     InFlag = Chain.getValue(2);
1543     InVals.push_back(Val);
1544   }
1545
1546   return Chain;
1547 }
1548
1549
1550 //===----------------------------------------------------------------------===//
1551 //                C & StdCall & Fast Calling Convention implementation
1552 //===----------------------------------------------------------------------===//
1553 //  StdCall calling convention seems to be standard for many Windows' API
1554 //  routines and around. It differs from C calling convention just a little:
1555 //  callee should clean up the stack, not caller. Symbols should be also
1556 //  decorated in some fancy way :) It doesn't support any vector arguments.
1557 //  For info on fast calling convention see Fast Calling Convention (tail call)
1558 //  implementation LowerX86_32FastCCCallTo.
1559
1560 /// CallIsStructReturn - Determines whether a call uses struct return
1561 /// semantics.
1562 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1563   if (Outs.empty())
1564     return false;
1565
1566   return Outs[0].Flags.isSRet();
1567 }
1568
1569 /// ArgsAreStructReturn - Determines whether a function uses struct
1570 /// return semantics.
1571 static bool
1572 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1573   if (Ins.empty())
1574     return false;
1575
1576   return Ins[0].Flags.isSRet();
1577 }
1578
1579 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1580 /// by "Src" to address "Dst" with size and alignment information specified by
1581 /// the specific parameter attribute. The copy will be passed as a byval
1582 /// function parameter.
1583 static SDValue
1584 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1585                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1586                           DebugLoc dl) {
1587   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1588
1589   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1590                        /*isVolatile*/false, /*AlwaysInline=*/true,
1591                        MachinePointerInfo(), MachinePointerInfo());
1592 }
1593
1594 /// IsTailCallConvention - Return true if the calling convention is one that
1595 /// supports tail call optimization.
1596 static bool IsTailCallConvention(CallingConv::ID CC) {
1597   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1598 }
1599
1600 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1601   if (!CI->isTailCall())
1602     return false;
1603
1604   CallSite CS(CI);
1605   CallingConv::ID CalleeCC = CS.getCallingConv();
1606   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1607     return false;
1608
1609   return true;
1610 }
1611
1612 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1613 /// a tailcall target by changing its ABI.
1614 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1615   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1616 }
1617
1618 SDValue
1619 X86TargetLowering::LowerMemArgument(SDValue Chain,
1620                                     CallingConv::ID CallConv,
1621                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1622                                     DebugLoc dl, SelectionDAG &DAG,
1623                                     const CCValAssign &VA,
1624                                     MachineFrameInfo *MFI,
1625                                     unsigned i) const {
1626   // Create the nodes corresponding to a load from this parameter slot.
1627   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1628   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1629   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1630   EVT ValVT;
1631
1632   // If value is passed by pointer we have address passed instead of the value
1633   // itself.
1634   if (VA.getLocInfo() == CCValAssign::Indirect)
1635     ValVT = VA.getLocVT();
1636   else
1637     ValVT = VA.getValVT();
1638
1639   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1640   // changed with more analysis.
1641   // In case of tail call optimization mark all arguments mutable. Since they
1642   // could be overwritten by lowering of arguments in case of a tail call.
1643   if (Flags.isByVal()) {
1644     unsigned Bytes = Flags.getByValSize();
1645     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1646     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1647     return DAG.getFrameIndex(FI, getPointerTy());
1648   } else {
1649     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1650                                     VA.getLocMemOffset(), isImmutable);
1651     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1652     return DAG.getLoad(ValVT, dl, Chain, FIN,
1653                        MachinePointerInfo::getFixedStack(FI),
1654                        false, false, 0);
1655   }
1656 }
1657
1658 SDValue
1659 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1660                                         CallingConv::ID CallConv,
1661                                         bool isVarArg,
1662                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1663                                         DebugLoc dl,
1664                                         SelectionDAG &DAG,
1665                                         SmallVectorImpl<SDValue> &InVals)
1666                                           const {
1667   MachineFunction &MF = DAG.getMachineFunction();
1668   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1669
1670   const Function* Fn = MF.getFunction();
1671   if (Fn->hasExternalLinkage() &&
1672       Subtarget->isTargetCygMing() &&
1673       Fn->getName() == "main")
1674     FuncInfo->setForceFramePointer(true);
1675
1676   MachineFrameInfo *MFI = MF.getFrameInfo();
1677   bool Is64Bit = Subtarget->is64Bit();
1678   bool IsWin64 = Subtarget->isTargetWin64();
1679
1680   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1681          "Var args not supported with calling convention fastcc or ghc");
1682
1683   // Assign locations to all of the incoming arguments.
1684   SmallVector<CCValAssign, 16> ArgLocs;
1685   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1686                  ArgLocs, *DAG.getContext());
1687
1688   // Allocate shadow area for Win64
1689   if (IsWin64) {
1690     CCInfo.AllocateStack(32, 8);
1691   }
1692
1693   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1694
1695   unsigned LastVal = ~0U;
1696   SDValue ArgValue;
1697   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1698     CCValAssign &VA = ArgLocs[i];
1699     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1700     // places.
1701     assert(VA.getValNo() != LastVal &&
1702            "Don't support value assigned to multiple locs yet");
1703     LastVal = VA.getValNo();
1704
1705     if (VA.isRegLoc()) {
1706       EVT RegVT = VA.getLocVT();
1707       TargetRegisterClass *RC = NULL;
1708       if (RegVT == MVT::i32)
1709         RC = X86::GR32RegisterClass;
1710       else if (Is64Bit && RegVT == MVT::i64)
1711         RC = X86::GR64RegisterClass;
1712       else if (RegVT == MVT::f32)
1713         RC = X86::FR32RegisterClass;
1714       else if (RegVT == MVT::f64)
1715         RC = X86::FR64RegisterClass;
1716       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1717         RC = X86::VR256RegisterClass;
1718       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1719         RC = X86::VR128RegisterClass;
1720       else if (RegVT == MVT::x86mmx)
1721         RC = X86::VR64RegisterClass;
1722       else
1723         llvm_unreachable("Unknown argument type!");
1724
1725       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1726       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1727
1728       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1729       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1730       // right size.
1731       if (VA.getLocInfo() == CCValAssign::SExt)
1732         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1733                                DAG.getValueType(VA.getValVT()));
1734       else if (VA.getLocInfo() == CCValAssign::ZExt)
1735         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1736                                DAG.getValueType(VA.getValVT()));
1737       else if (VA.getLocInfo() == CCValAssign::BCvt)
1738         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1739
1740       if (VA.isExtInLoc()) {
1741         // Handle MMX values passed in XMM regs.
1742         if (RegVT.isVector()) {
1743           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1744                                  ArgValue);
1745         } else
1746           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1747       }
1748     } else {
1749       assert(VA.isMemLoc());
1750       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1751     }
1752
1753     // If value is passed via pointer - do a load.
1754     if (VA.getLocInfo() == CCValAssign::Indirect)
1755       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1756                              MachinePointerInfo(), false, false, 0);
1757
1758     InVals.push_back(ArgValue);
1759   }
1760
1761   // The x86-64 ABI for returning structs by value requires that we copy
1762   // the sret argument into %rax for the return. Save the argument into
1763   // a virtual register so that we can access it from the return points.
1764   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1765     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1766     unsigned Reg = FuncInfo->getSRetReturnReg();
1767     if (!Reg) {
1768       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1769       FuncInfo->setSRetReturnReg(Reg);
1770     }
1771     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1772     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1773   }
1774
1775   unsigned StackSize = CCInfo.getNextStackOffset();
1776   // Align stack specially for tail calls.
1777   if (FuncIsMadeTailCallSafe(CallConv))
1778     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1779
1780   // If the function takes variable number of arguments, make a frame index for
1781   // the start of the first vararg value... for expansion of llvm.va_start.
1782   if (isVarArg) {
1783     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1784                     CallConv != CallingConv::X86_ThisCall)) {
1785       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1786     }
1787     if (Is64Bit) {
1788       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1789
1790       // FIXME: We should really autogenerate these arrays
1791       static const unsigned GPR64ArgRegsWin64[] = {
1792         X86::RCX, X86::RDX, X86::R8,  X86::R9
1793       };
1794       static const unsigned GPR64ArgRegs64Bit[] = {
1795         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1796       };
1797       static const unsigned XMMArgRegs64Bit[] = {
1798         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1799         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1800       };
1801       const unsigned *GPR64ArgRegs;
1802       unsigned NumXMMRegs = 0;
1803
1804       if (IsWin64) {
1805         // The XMM registers which might contain var arg parameters are shadowed
1806         // in their paired GPR.  So we only need to save the GPR to their home
1807         // slots.
1808         TotalNumIntRegs = 4;
1809         GPR64ArgRegs = GPR64ArgRegsWin64;
1810       } else {
1811         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1812         GPR64ArgRegs = GPR64ArgRegs64Bit;
1813
1814         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1815       }
1816       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1817                                                        TotalNumIntRegs);
1818
1819       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1820       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1821              "SSE register cannot be used when SSE is disabled!");
1822       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1823              "SSE register cannot be used when SSE is disabled!");
1824       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1825         // Kernel mode asks for SSE to be disabled, so don't push them
1826         // on the stack.
1827         TotalNumXMMRegs = 0;
1828
1829       if (IsWin64) {
1830         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1831         // Get to the caller-allocated home save location.  Add 8 to account
1832         // for the return address.
1833         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1834         FuncInfo->setRegSaveFrameIndex(
1835           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1836         // Fixup to set vararg frame on shadow area (4 x i64).
1837         if (NumIntRegs < 4)
1838           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1839       } else {
1840         // For X86-64, if there are vararg parameters that are passed via
1841         // registers, then we must store them to their spots on the stack so they
1842         // may be loaded by deferencing the result of va_next.
1843         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1844         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1845         FuncInfo->setRegSaveFrameIndex(
1846           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1847                                false));
1848       }
1849
1850       // Store the integer parameter registers.
1851       SmallVector<SDValue, 8> MemOps;
1852       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1853                                         getPointerTy());
1854       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1855       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1856         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1857                                   DAG.getIntPtrConstant(Offset));
1858         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1859                                      X86::GR64RegisterClass);
1860         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1861         SDValue Store =
1862           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1863                        MachinePointerInfo::getFixedStack(
1864                          FuncInfo->getRegSaveFrameIndex(), Offset),
1865                        false, false, 0);
1866         MemOps.push_back(Store);
1867         Offset += 8;
1868       }
1869
1870       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1871         // Now store the XMM (fp + vector) parameter registers.
1872         SmallVector<SDValue, 11> SaveXMMOps;
1873         SaveXMMOps.push_back(Chain);
1874
1875         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1876         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1877         SaveXMMOps.push_back(ALVal);
1878
1879         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1880                                FuncInfo->getRegSaveFrameIndex()));
1881         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1882                                FuncInfo->getVarArgsFPOffset()));
1883
1884         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1885           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1886                                        X86::VR128RegisterClass);
1887           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1888           SaveXMMOps.push_back(Val);
1889         }
1890         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1891                                      MVT::Other,
1892                                      &SaveXMMOps[0], SaveXMMOps.size()));
1893       }
1894
1895       if (!MemOps.empty())
1896         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1897                             &MemOps[0], MemOps.size());
1898     }
1899   }
1900
1901   // Some CCs need callee pop.
1902   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1903     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1904   } else {
1905     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1906     // If this is an sret function, the return should pop the hidden pointer.
1907     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1908       FuncInfo->setBytesToPopOnReturn(4);
1909   }
1910
1911   if (!Is64Bit) {
1912     // RegSaveFrameIndex is X86-64 only.
1913     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1914     if (CallConv == CallingConv::X86_FastCall ||
1915         CallConv == CallingConv::X86_ThisCall)
1916       // fastcc functions can't have varargs.
1917       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1918   }
1919
1920   return Chain;
1921 }
1922
1923 SDValue
1924 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1925                                     SDValue StackPtr, SDValue Arg,
1926                                     DebugLoc dl, SelectionDAG &DAG,
1927                                     const CCValAssign &VA,
1928                                     ISD::ArgFlagsTy Flags) const {
1929   unsigned LocMemOffset = VA.getLocMemOffset();
1930   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1931   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1932   if (Flags.isByVal())
1933     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1934
1935   return DAG.getStore(Chain, dl, Arg, PtrOff,
1936                       MachinePointerInfo::getStack(LocMemOffset),
1937                       false, false, 0);
1938 }
1939
1940 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1941 /// optimization is performed and it is required.
1942 SDValue
1943 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1944                                            SDValue &OutRetAddr, SDValue Chain,
1945                                            bool IsTailCall, bool Is64Bit,
1946                                            int FPDiff, DebugLoc dl) const {
1947   // Adjust the Return address stack slot.
1948   EVT VT = getPointerTy();
1949   OutRetAddr = getReturnAddressFrameIndex(DAG);
1950
1951   // Load the "old" Return address.
1952   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1953                            false, false, 0);
1954   return SDValue(OutRetAddr.getNode(), 1);
1955 }
1956
1957 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1958 /// optimization is performed and it is required (FPDiff!=0).
1959 static SDValue
1960 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1961                          SDValue Chain, SDValue RetAddrFrIdx,
1962                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1963   // Store the return address to the appropriate stack slot.
1964   if (!FPDiff) return Chain;
1965   // Calculate the new stack slot for the return address.
1966   int SlotSize = Is64Bit ? 8 : 4;
1967   int NewReturnAddrFI =
1968     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1969   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1970   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1971   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1972                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1973                        false, false, 0);
1974   return Chain;
1975 }
1976
1977 SDValue
1978 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1979                              CallingConv::ID CallConv, bool isVarArg,
1980                              bool &isTailCall,
1981                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1982                              const SmallVectorImpl<SDValue> &OutVals,
1983                              const SmallVectorImpl<ISD::InputArg> &Ins,
1984                              DebugLoc dl, SelectionDAG &DAG,
1985                              SmallVectorImpl<SDValue> &InVals) const {
1986   MachineFunction &MF = DAG.getMachineFunction();
1987   bool Is64Bit        = Subtarget->is64Bit();
1988   bool IsWin64        = Subtarget->isTargetWin64();
1989   bool IsStructRet    = CallIsStructReturn(Outs);
1990   bool IsSibcall      = false;
1991
1992   if (isTailCall) {
1993     // Check if it's really possible to do a tail call.
1994     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1995                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1996                                                    Outs, OutVals, Ins, DAG);
1997
1998     // Sibcalls are automatically detected tailcalls which do not require
1999     // ABI changes.
2000     if (!GuaranteedTailCallOpt && isTailCall)
2001       IsSibcall = true;
2002
2003     if (isTailCall)
2004       ++NumTailCalls;
2005   }
2006
2007   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2008          "Var args not supported with calling convention fastcc or ghc");
2009
2010   // Analyze operands of the call, assigning locations to each operand.
2011   SmallVector<CCValAssign, 16> ArgLocs;
2012   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2013                  ArgLocs, *DAG.getContext());
2014
2015   // Allocate shadow area for Win64
2016   if (IsWin64) {
2017     CCInfo.AllocateStack(32, 8);
2018   }
2019
2020   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2021
2022   // Get a count of how many bytes are to be pushed on the stack.
2023   unsigned NumBytes = CCInfo.getNextStackOffset();
2024   if (IsSibcall)
2025     // This is a sibcall. The memory operands are available in caller's
2026     // own caller's stack.
2027     NumBytes = 0;
2028   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2029     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2030
2031   int FPDiff = 0;
2032   if (isTailCall && !IsSibcall) {
2033     // Lower arguments at fp - stackoffset + fpdiff.
2034     unsigned NumBytesCallerPushed =
2035       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2036     FPDiff = NumBytesCallerPushed - NumBytes;
2037
2038     // Set the delta of movement of the returnaddr stackslot.
2039     // But only set if delta is greater than previous delta.
2040     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2041       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2042   }
2043
2044   if (!IsSibcall)
2045     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2046
2047   SDValue RetAddrFrIdx;
2048   // Load return address for tail calls.
2049   if (isTailCall && FPDiff)
2050     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2051                                     Is64Bit, FPDiff, dl);
2052
2053   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2054   SmallVector<SDValue, 8> MemOpChains;
2055   SDValue StackPtr;
2056
2057   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2058   // of tail call optimization arguments are handle later.
2059   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2060     CCValAssign &VA = ArgLocs[i];
2061     EVT RegVT = VA.getLocVT();
2062     SDValue Arg = OutVals[i];
2063     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2064     bool isByVal = Flags.isByVal();
2065
2066     // Promote the value if needed.
2067     switch (VA.getLocInfo()) {
2068     default: llvm_unreachable("Unknown loc info!");
2069     case CCValAssign::Full: break;
2070     case CCValAssign::SExt:
2071       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2072       break;
2073     case CCValAssign::ZExt:
2074       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2075       break;
2076     case CCValAssign::AExt:
2077       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2078         // Special case: passing MMX values in XMM registers.
2079         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2080         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2081         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2082       } else
2083         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2084       break;
2085     case CCValAssign::BCvt:
2086       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2087       break;
2088     case CCValAssign::Indirect: {
2089       // Store the argument.
2090       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2091       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2092       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2093                            MachinePointerInfo::getFixedStack(FI),
2094                            false, false, 0);
2095       Arg = SpillSlot;
2096       break;
2097     }
2098     }
2099
2100     if (VA.isRegLoc()) {
2101       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2102       if (isVarArg && IsWin64) {
2103         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2104         // shadow reg if callee is a varargs function.
2105         unsigned ShadowReg = 0;
2106         switch (VA.getLocReg()) {
2107         case X86::XMM0: ShadowReg = X86::RCX; break;
2108         case X86::XMM1: ShadowReg = X86::RDX; break;
2109         case X86::XMM2: ShadowReg = X86::R8; break;
2110         case X86::XMM3: ShadowReg = X86::R9; break;
2111         }
2112         if (ShadowReg)
2113           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2114       }
2115     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2116       assert(VA.isMemLoc());
2117       if (StackPtr.getNode() == 0)
2118         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2119       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2120                                              dl, DAG, VA, Flags));
2121     }
2122   }
2123
2124   if (!MemOpChains.empty())
2125     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2126                         &MemOpChains[0], MemOpChains.size());
2127
2128   // Build a sequence of copy-to-reg nodes chained together with token chain
2129   // and flag operands which copy the outgoing args into registers.
2130   SDValue InFlag;
2131   // Tail call byval lowering might overwrite argument registers so in case of
2132   // tail call optimization the copies to registers are lowered later.
2133   if (!isTailCall)
2134     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2135       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2136                                RegsToPass[i].second, InFlag);
2137       InFlag = Chain.getValue(1);
2138     }
2139
2140   if (Subtarget->isPICStyleGOT()) {
2141     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2142     // GOT pointer.
2143     if (!isTailCall) {
2144       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2145                                DAG.getNode(X86ISD::GlobalBaseReg,
2146                                            DebugLoc(), getPointerTy()),
2147                                InFlag);
2148       InFlag = Chain.getValue(1);
2149     } else {
2150       // If we are tail calling and generating PIC/GOT style code load the
2151       // address of the callee into ECX. The value in ecx is used as target of
2152       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2153       // for tail calls on PIC/GOT architectures. Normally we would just put the
2154       // address of GOT into ebx and then call target@PLT. But for tail calls
2155       // ebx would be restored (since ebx is callee saved) before jumping to the
2156       // target@PLT.
2157
2158       // Note: The actual moving to ECX is done further down.
2159       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2160       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2161           !G->getGlobal()->hasProtectedVisibility())
2162         Callee = LowerGlobalAddress(Callee, DAG);
2163       else if (isa<ExternalSymbolSDNode>(Callee))
2164         Callee = LowerExternalSymbol(Callee, DAG);
2165     }
2166   }
2167
2168   if (Is64Bit && isVarArg && !IsWin64) {
2169     // From AMD64 ABI document:
2170     // For calls that may call functions that use varargs or stdargs
2171     // (prototype-less calls or calls to functions containing ellipsis (...) in
2172     // the declaration) %al is used as hidden argument to specify the number
2173     // of SSE registers used. The contents of %al do not need to match exactly
2174     // the number of registers, but must be an ubound on the number of SSE
2175     // registers used and is in the range 0 - 8 inclusive.
2176
2177     // Count the number of XMM registers allocated.
2178     static const unsigned XMMArgRegs[] = {
2179       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2180       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2181     };
2182     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2183     assert((Subtarget->hasXMM() || !NumXMMRegs)
2184            && "SSE registers cannot be used when SSE is disabled");
2185
2186     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2187                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2188     InFlag = Chain.getValue(1);
2189   }
2190
2191
2192   // For tail calls lower the arguments to the 'real' stack slot.
2193   if (isTailCall) {
2194     // Force all the incoming stack arguments to be loaded from the stack
2195     // before any new outgoing arguments are stored to the stack, because the
2196     // outgoing stack slots may alias the incoming argument stack slots, and
2197     // the alias isn't otherwise explicit. This is slightly more conservative
2198     // than necessary, because it means that each store effectively depends
2199     // on every argument instead of just those arguments it would clobber.
2200     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2201
2202     SmallVector<SDValue, 8> MemOpChains2;
2203     SDValue FIN;
2204     int FI = 0;
2205     // Do not flag preceding copytoreg stuff together with the following stuff.
2206     InFlag = SDValue();
2207     if (GuaranteedTailCallOpt) {
2208       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2209         CCValAssign &VA = ArgLocs[i];
2210         if (VA.isRegLoc())
2211           continue;
2212         assert(VA.isMemLoc());
2213         SDValue Arg = OutVals[i];
2214         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2215         // Create frame index.
2216         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2217         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2218         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2219         FIN = DAG.getFrameIndex(FI, getPointerTy());
2220
2221         if (Flags.isByVal()) {
2222           // Copy relative to framepointer.
2223           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2224           if (StackPtr.getNode() == 0)
2225             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2226                                           getPointerTy());
2227           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2228
2229           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2230                                                            ArgChain,
2231                                                            Flags, DAG, dl));
2232         } else {
2233           // Store relative to framepointer.
2234           MemOpChains2.push_back(
2235             DAG.getStore(ArgChain, dl, Arg, FIN,
2236                          MachinePointerInfo::getFixedStack(FI),
2237                          false, false, 0));
2238         }
2239       }
2240     }
2241
2242     if (!MemOpChains2.empty())
2243       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2244                           &MemOpChains2[0], MemOpChains2.size());
2245
2246     // Copy arguments to their registers.
2247     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2248       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2249                                RegsToPass[i].second, InFlag);
2250       InFlag = Chain.getValue(1);
2251     }
2252     InFlag =SDValue();
2253
2254     // Store the return address to the appropriate stack slot.
2255     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2256                                      FPDiff, dl);
2257   }
2258
2259   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2260     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2261     // In the 64-bit large code model, we have to make all calls
2262     // through a register, since the call instruction's 32-bit
2263     // pc-relative offset may not be large enough to hold the whole
2264     // address.
2265   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2266     // If the callee is a GlobalAddress node (quite common, every direct call
2267     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2268     // it.
2269
2270     // We should use extra load for direct calls to dllimported functions in
2271     // non-JIT mode.
2272     const GlobalValue *GV = G->getGlobal();
2273     if (!GV->hasDLLImportLinkage()) {
2274       unsigned char OpFlags = 0;
2275       bool ExtraLoad = false;
2276       unsigned WrapperKind = ISD::DELETED_NODE;
2277
2278       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2279       // external symbols most go through the PLT in PIC mode.  If the symbol
2280       // has hidden or protected visibility, or if it is static or local, then
2281       // we don't need to use the PLT - we can directly call it.
2282       if (Subtarget->isTargetELF() &&
2283           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2284           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2285         OpFlags = X86II::MO_PLT;
2286       } else if (Subtarget->isPICStyleStubAny() &&
2287                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2288                  (!Subtarget->getTargetTriple().isMacOSX() ||
2289                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2290         // PC-relative references to external symbols should go through $stub,
2291         // unless we're building with the leopard linker or later, which
2292         // automatically synthesizes these stubs.
2293         OpFlags = X86II::MO_DARWIN_STUB;
2294       } else if (Subtarget->isPICStyleRIPRel() &&
2295                  isa<Function>(GV) &&
2296                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2297         // If the function is marked as non-lazy, generate an indirect call
2298         // which loads from the GOT directly. This avoids runtime overhead
2299         // at the cost of eager binding (and one extra byte of encoding).
2300         OpFlags = X86II::MO_GOTPCREL;
2301         WrapperKind = X86ISD::WrapperRIP;
2302         ExtraLoad = true;
2303       }
2304
2305       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2306                                           G->getOffset(), OpFlags);
2307
2308       // Add a wrapper if needed.
2309       if (WrapperKind != ISD::DELETED_NODE)
2310         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2311       // Add extra indirection if needed.
2312       if (ExtraLoad)
2313         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2314                              MachinePointerInfo::getGOT(),
2315                              false, false, 0);
2316     }
2317   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2318     unsigned char OpFlags = 0;
2319
2320     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2321     // external symbols should go through the PLT.
2322     if (Subtarget->isTargetELF() &&
2323         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2324       OpFlags = X86II::MO_PLT;
2325     } else if (Subtarget->isPICStyleStubAny() &&
2326                (!Subtarget->getTargetTriple().isMacOSX() ||
2327                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2328       // PC-relative references to external symbols should go through $stub,
2329       // unless we're building with the leopard linker or later, which
2330       // automatically synthesizes these stubs.
2331       OpFlags = X86II::MO_DARWIN_STUB;
2332     }
2333
2334     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2335                                          OpFlags);
2336   }
2337
2338   // Returns a chain & a flag for retval copy to use.
2339   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2340   SmallVector<SDValue, 8> Ops;
2341
2342   if (!IsSibcall && isTailCall) {
2343     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2344                            DAG.getIntPtrConstant(0, true), InFlag);
2345     InFlag = Chain.getValue(1);
2346   }
2347
2348   Ops.push_back(Chain);
2349   Ops.push_back(Callee);
2350
2351   if (isTailCall)
2352     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2353
2354   // Add argument registers to the end of the list so that they are known live
2355   // into the call.
2356   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2357     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2358                                   RegsToPass[i].second.getValueType()));
2359
2360   // Add an implicit use GOT pointer in EBX.
2361   if (!isTailCall && Subtarget->isPICStyleGOT())
2362     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2363
2364   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2365   if (Is64Bit && isVarArg && !IsWin64)
2366     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2367
2368   if (InFlag.getNode())
2369     Ops.push_back(InFlag);
2370
2371   if (isTailCall) {
2372     // We used to do:
2373     //// If this is the first return lowered for this function, add the regs
2374     //// to the liveout set for the function.
2375     // This isn't right, although it's probably harmless on x86; liveouts
2376     // should be computed from returns not tail calls.  Consider a void
2377     // function making a tail call to a function returning int.
2378     return DAG.getNode(X86ISD::TC_RETURN, dl,
2379                        NodeTys, &Ops[0], Ops.size());
2380   }
2381
2382   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2383   InFlag = Chain.getValue(1);
2384
2385   // Create the CALLSEQ_END node.
2386   unsigned NumBytesForCalleeToPush;
2387   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2388     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2389   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2390     // If this is a call to a struct-return function, the callee
2391     // pops the hidden struct pointer, so we have to push it back.
2392     // This is common for Darwin/X86, Linux & Mingw32 targets.
2393     NumBytesForCalleeToPush = 4;
2394   else
2395     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2396
2397   // Returns a flag for retval copy to use.
2398   if (!IsSibcall) {
2399     Chain = DAG.getCALLSEQ_END(Chain,
2400                                DAG.getIntPtrConstant(NumBytes, true),
2401                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2402                                                      true),
2403                                InFlag);
2404     InFlag = Chain.getValue(1);
2405   }
2406
2407   // Handle result values, copying them out of physregs into vregs that we
2408   // return.
2409   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2410                          Ins, dl, DAG, InVals);
2411 }
2412
2413
2414 //===----------------------------------------------------------------------===//
2415 //                Fast Calling Convention (tail call) implementation
2416 //===----------------------------------------------------------------------===//
2417
2418 //  Like std call, callee cleans arguments, convention except that ECX is
2419 //  reserved for storing the tail called function address. Only 2 registers are
2420 //  free for argument passing (inreg). Tail call optimization is performed
2421 //  provided:
2422 //                * tailcallopt is enabled
2423 //                * caller/callee are fastcc
2424 //  On X86_64 architecture with GOT-style position independent code only local
2425 //  (within module) calls are supported at the moment.
2426 //  To keep the stack aligned according to platform abi the function
2427 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2428 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2429 //  If a tail called function callee has more arguments than the caller the
2430 //  caller needs to make sure that there is room to move the RETADDR to. This is
2431 //  achieved by reserving an area the size of the argument delta right after the
2432 //  original REtADDR, but before the saved framepointer or the spilled registers
2433 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2434 //  stack layout:
2435 //    arg1
2436 //    arg2
2437 //    RETADDR
2438 //    [ new RETADDR
2439 //      move area ]
2440 //    (possible EBP)
2441 //    ESI
2442 //    EDI
2443 //    local1 ..
2444
2445 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2446 /// for a 16 byte align requirement.
2447 unsigned
2448 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2449                                                SelectionDAG& DAG) const {
2450   MachineFunction &MF = DAG.getMachineFunction();
2451   const TargetMachine &TM = MF.getTarget();
2452   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2453   unsigned StackAlignment = TFI.getStackAlignment();
2454   uint64_t AlignMask = StackAlignment - 1;
2455   int64_t Offset = StackSize;
2456   uint64_t SlotSize = TD->getPointerSize();
2457   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2458     // Number smaller than 12 so just add the difference.
2459     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2460   } else {
2461     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2462     Offset = ((~AlignMask) & Offset) + StackAlignment +
2463       (StackAlignment-SlotSize);
2464   }
2465   return Offset;
2466 }
2467
2468 /// MatchingStackOffset - Return true if the given stack call argument is
2469 /// already available in the same position (relatively) of the caller's
2470 /// incoming argument stack.
2471 static
2472 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2473                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2474                          const X86InstrInfo *TII) {
2475   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2476   int FI = INT_MAX;
2477   if (Arg.getOpcode() == ISD::CopyFromReg) {
2478     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2479     if (!TargetRegisterInfo::isVirtualRegister(VR))
2480       return false;
2481     MachineInstr *Def = MRI->getVRegDef(VR);
2482     if (!Def)
2483       return false;
2484     if (!Flags.isByVal()) {
2485       if (!TII->isLoadFromStackSlot(Def, FI))
2486         return false;
2487     } else {
2488       unsigned Opcode = Def->getOpcode();
2489       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2490           Def->getOperand(1).isFI()) {
2491         FI = Def->getOperand(1).getIndex();
2492         Bytes = Flags.getByValSize();
2493       } else
2494         return false;
2495     }
2496   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2497     if (Flags.isByVal())
2498       // ByVal argument is passed in as a pointer but it's now being
2499       // dereferenced. e.g.
2500       // define @foo(%struct.X* %A) {
2501       //   tail call @bar(%struct.X* byval %A)
2502       // }
2503       return false;
2504     SDValue Ptr = Ld->getBasePtr();
2505     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2506     if (!FINode)
2507       return false;
2508     FI = FINode->getIndex();
2509   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2510     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2511     FI = FINode->getIndex();
2512     Bytes = Flags.getByValSize();
2513   } else
2514     return false;
2515
2516   assert(FI != INT_MAX);
2517   if (!MFI->isFixedObjectIndex(FI))
2518     return false;
2519   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2520 }
2521
2522 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2523 /// for tail call optimization. Targets which want to do tail call
2524 /// optimization should implement this function.
2525 bool
2526 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2527                                                      CallingConv::ID CalleeCC,
2528                                                      bool isVarArg,
2529                                                      bool isCalleeStructRet,
2530                                                      bool isCallerStructRet,
2531                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2532                                     const SmallVectorImpl<SDValue> &OutVals,
2533                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2534                                                      SelectionDAG& DAG) const {
2535   if (!IsTailCallConvention(CalleeCC) &&
2536       CalleeCC != CallingConv::C)
2537     return false;
2538
2539   // If -tailcallopt is specified, make fastcc functions tail-callable.
2540   const MachineFunction &MF = DAG.getMachineFunction();
2541   const Function *CallerF = DAG.getMachineFunction().getFunction();
2542   CallingConv::ID CallerCC = CallerF->getCallingConv();
2543   bool CCMatch = CallerCC == CalleeCC;
2544
2545   if (GuaranteedTailCallOpt) {
2546     if (IsTailCallConvention(CalleeCC) && CCMatch)
2547       return true;
2548     return false;
2549   }
2550
2551   // Look for obvious safe cases to perform tail call optimization that do not
2552   // require ABI changes. This is what gcc calls sibcall.
2553
2554   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2555   // emit a special epilogue.
2556   if (RegInfo->needsStackRealignment(MF))
2557     return false;
2558
2559   // Also avoid sibcall optimization if either caller or callee uses struct
2560   // return semantics.
2561   if (isCalleeStructRet || isCallerStructRet)
2562     return false;
2563
2564   // An stdcall caller is expected to clean up its arguments; the callee
2565   // isn't going to do that.
2566   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2567     return false;
2568
2569   // Do not sibcall optimize vararg calls unless all arguments are passed via
2570   // registers.
2571   if (isVarArg && !Outs.empty()) {
2572
2573     // Optimizing for varargs on Win64 is unlikely to be safe without
2574     // additional testing.
2575     if (Subtarget->isTargetWin64())
2576       return false;
2577
2578     SmallVector<CCValAssign, 16> ArgLocs;
2579     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2580                    getTargetMachine(), ArgLocs, *DAG.getContext());
2581
2582     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2583     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2584       if (!ArgLocs[i].isRegLoc())
2585         return false;
2586   }
2587
2588   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2589   // Therefore if it's not used by the call it is not safe to optimize this into
2590   // a sibcall.
2591   bool Unused = false;
2592   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2593     if (!Ins[i].Used) {
2594       Unused = true;
2595       break;
2596     }
2597   }
2598   if (Unused) {
2599     SmallVector<CCValAssign, 16> RVLocs;
2600     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2601                    getTargetMachine(), RVLocs, *DAG.getContext());
2602     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2603     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2604       CCValAssign &VA = RVLocs[i];
2605       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2606         return false;
2607     }
2608   }
2609
2610   // If the calling conventions do not match, then we'd better make sure the
2611   // results are returned in the same way as what the caller expects.
2612   if (!CCMatch) {
2613     SmallVector<CCValAssign, 16> RVLocs1;
2614     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2615                     getTargetMachine(), RVLocs1, *DAG.getContext());
2616     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2617
2618     SmallVector<CCValAssign, 16> RVLocs2;
2619     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2620                     getTargetMachine(), RVLocs2, *DAG.getContext());
2621     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2622
2623     if (RVLocs1.size() != RVLocs2.size())
2624       return false;
2625     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2626       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2627         return false;
2628       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2629         return false;
2630       if (RVLocs1[i].isRegLoc()) {
2631         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2632           return false;
2633       } else {
2634         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2635           return false;
2636       }
2637     }
2638   }
2639
2640   // If the callee takes no arguments then go on to check the results of the
2641   // call.
2642   if (!Outs.empty()) {
2643     // Check if stack adjustment is needed. For now, do not do this if any
2644     // argument is passed on the stack.
2645     SmallVector<CCValAssign, 16> ArgLocs;
2646     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2647                    getTargetMachine(), ArgLocs, *DAG.getContext());
2648
2649     // Allocate shadow area for Win64
2650     if (Subtarget->isTargetWin64()) {
2651       CCInfo.AllocateStack(32, 8);
2652     }
2653
2654     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2655     if (CCInfo.getNextStackOffset()) {
2656       MachineFunction &MF = DAG.getMachineFunction();
2657       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2658         return false;
2659
2660       // Check if the arguments are already laid out in the right way as
2661       // the caller's fixed stack objects.
2662       MachineFrameInfo *MFI = MF.getFrameInfo();
2663       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2664       const X86InstrInfo *TII =
2665         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2666       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2667         CCValAssign &VA = ArgLocs[i];
2668         SDValue Arg = OutVals[i];
2669         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2670         if (VA.getLocInfo() == CCValAssign::Indirect)
2671           return false;
2672         if (!VA.isRegLoc()) {
2673           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2674                                    MFI, MRI, TII))
2675             return false;
2676         }
2677       }
2678     }
2679
2680     // If the tailcall address may be in a register, then make sure it's
2681     // possible to register allocate for it. In 32-bit, the call address can
2682     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2683     // callee-saved registers are restored. These happen to be the same
2684     // registers used to pass 'inreg' arguments so watch out for those.
2685     if (!Subtarget->is64Bit() &&
2686         !isa<GlobalAddressSDNode>(Callee) &&
2687         !isa<ExternalSymbolSDNode>(Callee)) {
2688       unsigned NumInRegs = 0;
2689       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2690         CCValAssign &VA = ArgLocs[i];
2691         if (!VA.isRegLoc())
2692           continue;
2693         unsigned Reg = VA.getLocReg();
2694         switch (Reg) {
2695         default: break;
2696         case X86::EAX: case X86::EDX: case X86::ECX:
2697           if (++NumInRegs == 3)
2698             return false;
2699           break;
2700         }
2701       }
2702     }
2703   }
2704
2705   return true;
2706 }
2707
2708 FastISel *
2709 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2710   return X86::createFastISel(funcInfo);
2711 }
2712
2713
2714 //===----------------------------------------------------------------------===//
2715 //                           Other Lowering Hooks
2716 //===----------------------------------------------------------------------===//
2717
2718 static bool MayFoldLoad(SDValue Op) {
2719   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2720 }
2721
2722 static bool MayFoldIntoStore(SDValue Op) {
2723   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2724 }
2725
2726 static bool isTargetShuffle(unsigned Opcode) {
2727   switch(Opcode) {
2728   default: return false;
2729   case X86ISD::PSHUFD:
2730   case X86ISD::PSHUFHW:
2731   case X86ISD::PSHUFLW:
2732   case X86ISD::SHUFPD:
2733   case X86ISD::PALIGN:
2734   case X86ISD::SHUFPS:
2735   case X86ISD::MOVLHPS:
2736   case X86ISD::MOVLHPD:
2737   case X86ISD::MOVHLPS:
2738   case X86ISD::MOVLPS:
2739   case X86ISD::MOVLPD:
2740   case X86ISD::MOVSHDUP:
2741   case X86ISD::MOVSLDUP:
2742   case X86ISD::MOVDDUP:
2743   case X86ISD::MOVSS:
2744   case X86ISD::MOVSD:
2745   case X86ISD::UNPCKLPS:
2746   case X86ISD::UNPCKLPD:
2747   case X86ISD::VUNPCKLPS:
2748   case X86ISD::VUNPCKLPD:
2749   case X86ISD::VUNPCKLPSY:
2750   case X86ISD::VUNPCKLPDY:
2751   case X86ISD::PUNPCKLWD:
2752   case X86ISD::PUNPCKLBW:
2753   case X86ISD::PUNPCKLDQ:
2754   case X86ISD::PUNPCKLQDQ:
2755   case X86ISD::UNPCKHPS:
2756   case X86ISD::UNPCKHPD:
2757   case X86ISD::PUNPCKHWD:
2758   case X86ISD::PUNPCKHBW:
2759   case X86ISD::PUNPCKHDQ:
2760   case X86ISD::PUNPCKHQDQ:
2761     return true;
2762   }
2763   return false;
2764 }
2765
2766 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2767                                                SDValue V1, SelectionDAG &DAG) {
2768   switch(Opc) {
2769   default: llvm_unreachable("Unknown x86 shuffle node");
2770   case X86ISD::MOVSHDUP:
2771   case X86ISD::MOVSLDUP:
2772   case X86ISD::MOVDDUP:
2773     return DAG.getNode(Opc, dl, VT, V1);
2774   }
2775
2776   return SDValue();
2777 }
2778
2779 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2780                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2781   switch(Opc) {
2782   default: llvm_unreachable("Unknown x86 shuffle node");
2783   case X86ISD::PSHUFD:
2784   case X86ISD::PSHUFHW:
2785   case X86ISD::PSHUFLW:
2786     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2787   }
2788
2789   return SDValue();
2790 }
2791
2792 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2793                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2794   switch(Opc) {
2795   default: llvm_unreachable("Unknown x86 shuffle node");
2796   case X86ISD::PALIGN:
2797   case X86ISD::SHUFPD:
2798   case X86ISD::SHUFPS:
2799     return DAG.getNode(Opc, dl, VT, V1, V2,
2800                        DAG.getConstant(TargetMask, MVT::i8));
2801   }
2802   return SDValue();
2803 }
2804
2805 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2806                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2807   switch(Opc) {
2808   default: llvm_unreachable("Unknown x86 shuffle node");
2809   case X86ISD::MOVLHPS:
2810   case X86ISD::MOVLHPD:
2811   case X86ISD::MOVHLPS:
2812   case X86ISD::MOVLPS:
2813   case X86ISD::MOVLPD:
2814   case X86ISD::MOVSS:
2815   case X86ISD::MOVSD:
2816   case X86ISD::UNPCKLPS:
2817   case X86ISD::UNPCKLPD:
2818   case X86ISD::VUNPCKLPS:
2819   case X86ISD::VUNPCKLPD:
2820   case X86ISD::VUNPCKLPSY:
2821   case X86ISD::VUNPCKLPDY:
2822   case X86ISD::PUNPCKLWD:
2823   case X86ISD::PUNPCKLBW:
2824   case X86ISD::PUNPCKLDQ:
2825   case X86ISD::PUNPCKLQDQ:
2826   case X86ISD::UNPCKHPS:
2827   case X86ISD::UNPCKHPD:
2828   case X86ISD::PUNPCKHWD:
2829   case X86ISD::PUNPCKHBW:
2830   case X86ISD::PUNPCKHDQ:
2831   case X86ISD::PUNPCKHQDQ:
2832     return DAG.getNode(Opc, dl, VT, V1, V2);
2833   }
2834   return SDValue();
2835 }
2836
2837 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2838   MachineFunction &MF = DAG.getMachineFunction();
2839   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2840   int ReturnAddrIndex = FuncInfo->getRAIndex();
2841
2842   if (ReturnAddrIndex == 0) {
2843     // Set up a frame object for the return address.
2844     uint64_t SlotSize = TD->getPointerSize();
2845     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2846                                                            false);
2847     FuncInfo->setRAIndex(ReturnAddrIndex);
2848   }
2849
2850   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2851 }
2852
2853
2854 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2855                                        bool hasSymbolicDisplacement) {
2856   // Offset should fit into 32 bit immediate field.
2857   if (!isInt<32>(Offset))
2858     return false;
2859
2860   // If we don't have a symbolic displacement - we don't have any extra
2861   // restrictions.
2862   if (!hasSymbolicDisplacement)
2863     return true;
2864
2865   // FIXME: Some tweaks might be needed for medium code model.
2866   if (M != CodeModel::Small && M != CodeModel::Kernel)
2867     return false;
2868
2869   // For small code model we assume that latest object is 16MB before end of 31
2870   // bits boundary. We may also accept pretty large negative constants knowing
2871   // that all objects are in the positive half of address space.
2872   if (M == CodeModel::Small && Offset < 16*1024*1024)
2873     return true;
2874
2875   // For kernel code model we know that all object resist in the negative half
2876   // of 32bits address space. We may not accept negative offsets, since they may
2877   // be just off and we may accept pretty large positive ones.
2878   if (M == CodeModel::Kernel && Offset > 0)
2879     return true;
2880
2881   return false;
2882 }
2883
2884 /// isCalleePop - Determines whether the callee is required to pop its
2885 /// own arguments. Callee pop is necessary to support tail calls.
2886 bool X86::isCalleePop(CallingConv::ID CallingConv,
2887                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2888   if (IsVarArg)
2889     return false;
2890
2891   switch (CallingConv) {
2892   default:
2893     return false;
2894   case CallingConv::X86_StdCall:
2895     return !is64Bit;
2896   case CallingConv::X86_FastCall:
2897     return !is64Bit;
2898   case CallingConv::X86_ThisCall:
2899     return !is64Bit;
2900   case CallingConv::Fast:
2901     return TailCallOpt;
2902   case CallingConv::GHC:
2903     return TailCallOpt;
2904   }
2905 }
2906
2907 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2908 /// specific condition code, returning the condition code and the LHS/RHS of the
2909 /// comparison to make.
2910 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2911                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2912   if (!isFP) {
2913     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2914       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2915         // X > -1   -> X == 0, jump !sign.
2916         RHS = DAG.getConstant(0, RHS.getValueType());
2917         return X86::COND_NS;
2918       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2919         // X < 0   -> X == 0, jump on sign.
2920         return X86::COND_S;
2921       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2922         // X < 1   -> X <= 0
2923         RHS = DAG.getConstant(0, RHS.getValueType());
2924         return X86::COND_LE;
2925       }
2926     }
2927
2928     switch (SetCCOpcode) {
2929     default: llvm_unreachable("Invalid integer condition!");
2930     case ISD::SETEQ:  return X86::COND_E;
2931     case ISD::SETGT:  return X86::COND_G;
2932     case ISD::SETGE:  return X86::COND_GE;
2933     case ISD::SETLT:  return X86::COND_L;
2934     case ISD::SETLE:  return X86::COND_LE;
2935     case ISD::SETNE:  return X86::COND_NE;
2936     case ISD::SETULT: return X86::COND_B;
2937     case ISD::SETUGT: return X86::COND_A;
2938     case ISD::SETULE: return X86::COND_BE;
2939     case ISD::SETUGE: return X86::COND_AE;
2940     }
2941   }
2942
2943   // First determine if it is required or is profitable to flip the operands.
2944
2945   // If LHS is a foldable load, but RHS is not, flip the condition.
2946   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2947       !ISD::isNON_EXTLoad(RHS.getNode())) {
2948     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2949     std::swap(LHS, RHS);
2950   }
2951
2952   switch (SetCCOpcode) {
2953   default: break;
2954   case ISD::SETOLT:
2955   case ISD::SETOLE:
2956   case ISD::SETUGT:
2957   case ISD::SETUGE:
2958     std::swap(LHS, RHS);
2959     break;
2960   }
2961
2962   // On a floating point condition, the flags are set as follows:
2963   // ZF  PF  CF   op
2964   //  0 | 0 | 0 | X > Y
2965   //  0 | 0 | 1 | X < Y
2966   //  1 | 0 | 0 | X == Y
2967   //  1 | 1 | 1 | unordered
2968   switch (SetCCOpcode) {
2969   default: llvm_unreachable("Condcode should be pre-legalized away");
2970   case ISD::SETUEQ:
2971   case ISD::SETEQ:   return X86::COND_E;
2972   case ISD::SETOLT:              // flipped
2973   case ISD::SETOGT:
2974   case ISD::SETGT:   return X86::COND_A;
2975   case ISD::SETOLE:              // flipped
2976   case ISD::SETOGE:
2977   case ISD::SETGE:   return X86::COND_AE;
2978   case ISD::SETUGT:              // flipped
2979   case ISD::SETULT:
2980   case ISD::SETLT:   return X86::COND_B;
2981   case ISD::SETUGE:              // flipped
2982   case ISD::SETULE:
2983   case ISD::SETLE:   return X86::COND_BE;
2984   case ISD::SETONE:
2985   case ISD::SETNE:   return X86::COND_NE;
2986   case ISD::SETUO:   return X86::COND_P;
2987   case ISD::SETO:    return X86::COND_NP;
2988   case ISD::SETOEQ:
2989   case ISD::SETUNE:  return X86::COND_INVALID;
2990   }
2991 }
2992
2993 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2994 /// code. Current x86 isa includes the following FP cmov instructions:
2995 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2996 static bool hasFPCMov(unsigned X86CC) {
2997   switch (X86CC) {
2998   default:
2999     return false;
3000   case X86::COND_B:
3001   case X86::COND_BE:
3002   case X86::COND_E:
3003   case X86::COND_P:
3004   case X86::COND_A:
3005   case X86::COND_AE:
3006   case X86::COND_NE:
3007   case X86::COND_NP:
3008     return true;
3009   }
3010 }
3011
3012 /// isFPImmLegal - Returns true if the target can instruction select the
3013 /// specified FP immediate natively. If false, the legalizer will
3014 /// materialize the FP immediate as a load from a constant pool.
3015 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3016   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3017     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3018       return true;
3019   }
3020   return false;
3021 }
3022
3023 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3024 /// the specified range (L, H].
3025 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3026   return (Val < 0) || (Val >= Low && Val < Hi);
3027 }
3028
3029 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3030 /// specified value.
3031 static bool isUndefOrEqual(int Val, int CmpVal) {
3032   if (Val < 0 || Val == CmpVal)
3033     return true;
3034   return false;
3035 }
3036
3037 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3038 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3039 /// the second operand.
3040 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3041   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3042     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3043   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3044     return (Mask[0] < 2 && Mask[1] < 2);
3045   return false;
3046 }
3047
3048 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3049   SmallVector<int, 8> M;
3050   N->getMask(M);
3051   return ::isPSHUFDMask(M, N->getValueType(0));
3052 }
3053
3054 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3055 /// is suitable for input to PSHUFHW.
3056 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3057   if (VT != MVT::v8i16)
3058     return false;
3059
3060   // Lower quadword copied in order or undef.
3061   for (int i = 0; i != 4; ++i)
3062     if (Mask[i] >= 0 && Mask[i] != i)
3063       return false;
3064
3065   // Upper quadword shuffled.
3066   for (int i = 4; i != 8; ++i)
3067     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3068       return false;
3069
3070   return true;
3071 }
3072
3073 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3074   SmallVector<int, 8> M;
3075   N->getMask(M);
3076   return ::isPSHUFHWMask(M, N->getValueType(0));
3077 }
3078
3079 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3080 /// is suitable for input to PSHUFLW.
3081 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3082   if (VT != MVT::v8i16)
3083     return false;
3084
3085   // Upper quadword copied in order.
3086   for (int i = 4; i != 8; ++i)
3087     if (Mask[i] >= 0 && Mask[i] != i)
3088       return false;
3089
3090   // Lower quadword shuffled.
3091   for (int i = 0; i != 4; ++i)
3092     if (Mask[i] >= 4)
3093       return false;
3094
3095   return true;
3096 }
3097
3098 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3099   SmallVector<int, 8> M;
3100   N->getMask(M);
3101   return ::isPSHUFLWMask(M, N->getValueType(0));
3102 }
3103
3104 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3105 /// is suitable for input to PALIGNR.
3106 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3107                           bool hasSSSE3) {
3108   int i, e = VT.getVectorNumElements();
3109
3110   // Do not handle v2i64 / v2f64 shuffles with palignr.
3111   if (e < 4 || !hasSSSE3)
3112     return false;
3113
3114   for (i = 0; i != e; ++i)
3115     if (Mask[i] >= 0)
3116       break;
3117
3118   // All undef, not a palignr.
3119   if (i == e)
3120     return false;
3121
3122   // Determine if it's ok to perform a palignr with only the LHS, since we
3123   // don't have access to the actual shuffle elements to see if RHS is undef.
3124   bool Unary = Mask[i] < (int)e;
3125   bool NeedsUnary = false;
3126
3127   int s = Mask[i] - i;
3128
3129   // Check the rest of the elements to see if they are consecutive.
3130   for (++i; i != e; ++i) {
3131     int m = Mask[i];
3132     if (m < 0)
3133       continue;
3134
3135     Unary = Unary && (m < (int)e);
3136     NeedsUnary = NeedsUnary || (m < s);
3137
3138     if (NeedsUnary && !Unary)
3139       return false;
3140     if (Unary && m != ((s+i) & (e-1)))
3141       return false;
3142     if (!Unary && m != (s+i))
3143       return false;
3144   }
3145   return true;
3146 }
3147
3148 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3149   SmallVector<int, 8> M;
3150   N->getMask(M);
3151   return ::isPALIGNRMask(M, N->getValueType(0), true);
3152 }
3153
3154 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3155 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3156 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3157   int NumElems = VT.getVectorNumElements();
3158   if (NumElems != 2 && NumElems != 4)
3159     return false;
3160
3161   int Half = NumElems / 2;
3162   for (int i = 0; i < Half; ++i)
3163     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3164       return false;
3165   for (int i = Half; i < NumElems; ++i)
3166     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3167       return false;
3168
3169   return true;
3170 }
3171
3172 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3173   SmallVector<int, 8> M;
3174   N->getMask(M);
3175   return ::isSHUFPMask(M, N->getValueType(0));
3176 }
3177
3178 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3179 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3180 /// half elements to come from vector 1 (which would equal the dest.) and
3181 /// the upper half to come from vector 2.
3182 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3183   int NumElems = VT.getVectorNumElements();
3184
3185   if (NumElems != 2 && NumElems != 4)
3186     return false;
3187
3188   int Half = NumElems / 2;
3189   for (int i = 0; i < Half; ++i)
3190     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3191       return false;
3192   for (int i = Half; i < NumElems; ++i)
3193     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3194       return false;
3195   return true;
3196 }
3197
3198 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3199   SmallVector<int, 8> M;
3200   N->getMask(M);
3201   return isCommutedSHUFPMask(M, N->getValueType(0));
3202 }
3203
3204 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3205 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3206 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3207   if (N->getValueType(0).getVectorNumElements() != 4)
3208     return false;
3209
3210   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3211   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3212          isUndefOrEqual(N->getMaskElt(1), 7) &&
3213          isUndefOrEqual(N->getMaskElt(2), 2) &&
3214          isUndefOrEqual(N->getMaskElt(3), 3);
3215 }
3216
3217 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3218 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3219 /// <2, 3, 2, 3>
3220 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3221   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3222
3223   if (NumElems != 4)
3224     return false;
3225
3226   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3227   isUndefOrEqual(N->getMaskElt(1), 3) &&
3228   isUndefOrEqual(N->getMaskElt(2), 2) &&
3229   isUndefOrEqual(N->getMaskElt(3), 3);
3230 }
3231
3232 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3233 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3234 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3235   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3236
3237   if (NumElems != 2 && NumElems != 4)
3238     return false;
3239
3240   for (unsigned i = 0; i < NumElems/2; ++i)
3241     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3242       return false;
3243
3244   for (unsigned i = NumElems/2; i < NumElems; ++i)
3245     if (!isUndefOrEqual(N->getMaskElt(i), i))
3246       return false;
3247
3248   return true;
3249 }
3250
3251 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3252 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3253 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3254   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3255
3256   if ((NumElems != 2 && NumElems != 4)
3257       || N->getValueType(0).getSizeInBits() > 128)
3258     return false;
3259
3260   for (unsigned i = 0; i < NumElems/2; ++i)
3261     if (!isUndefOrEqual(N->getMaskElt(i), i))
3262       return false;
3263
3264   for (unsigned i = 0; i < NumElems/2; ++i)
3265     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3266       return false;
3267
3268   return true;
3269 }
3270
3271 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3273 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3274                          bool V2IsSplat = false) {
3275   int NumElts = VT.getVectorNumElements();
3276   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3277     return false;
3278
3279   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3280   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3281   // sections.
3282   unsigned NumSections = VT.getSizeInBits() / 128;
3283   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3284   unsigned NumSectionElts = NumElts / NumSections;
3285
3286   unsigned Start = 0;
3287   unsigned End = NumSectionElts;
3288   for (unsigned s = 0; s < NumSections; ++s) {
3289     for (unsigned i = Start, j = s * NumSectionElts;
3290          i != End;
3291          i += 2, ++j) {
3292       int BitI  = Mask[i];
3293       int BitI1 = Mask[i+1];
3294       if (!isUndefOrEqual(BitI, j))
3295         return false;
3296       if (V2IsSplat) {
3297         if (!isUndefOrEqual(BitI1, NumElts))
3298           return false;
3299       } else {
3300         if (!isUndefOrEqual(BitI1, j + NumElts))
3301           return false;
3302       }
3303     }
3304     // Process the next 128 bits.
3305     Start += NumSectionElts;
3306     End += NumSectionElts;
3307   }
3308
3309   return true;
3310 }
3311
3312 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3313   SmallVector<int, 8> M;
3314   N->getMask(M);
3315   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3316 }
3317
3318 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3319 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3320 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3321                          bool V2IsSplat = false) {
3322   int NumElts = VT.getVectorNumElements();
3323   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3324     return false;
3325
3326   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3327     int BitI  = Mask[i];
3328     int BitI1 = Mask[i+1];
3329     if (!isUndefOrEqual(BitI, j + NumElts/2))
3330       return false;
3331     if (V2IsSplat) {
3332       if (isUndefOrEqual(BitI1, NumElts))
3333         return false;
3334     } else {
3335       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3336         return false;
3337     }
3338   }
3339   return true;
3340 }
3341
3342 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3343   SmallVector<int, 8> M;
3344   N->getMask(M);
3345   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3346 }
3347
3348 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3349 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3350 /// <0, 0, 1, 1>
3351 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3352   int NumElems = VT.getVectorNumElements();
3353   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3354     return false;
3355
3356   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3357   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3358   // sections.
3359   unsigned NumSections = VT.getSizeInBits() / 128;
3360   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3361   unsigned NumSectionElts = NumElems / NumSections;
3362
3363   for (unsigned s = 0; s < NumSections; ++s) {
3364     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3365          i != NumSectionElts * (s + 1);
3366          i += 2, ++j) {
3367       int BitI  = Mask[i];
3368       int BitI1 = Mask[i+1];
3369
3370       if (!isUndefOrEqual(BitI, j))
3371         return false;
3372       if (!isUndefOrEqual(BitI1, j))
3373         return false;
3374     }
3375   }
3376
3377   return true;
3378 }
3379
3380 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3381   SmallVector<int, 8> M;
3382   N->getMask(M);
3383   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3384 }
3385
3386 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3387 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3388 /// <2, 2, 3, 3>
3389 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3390   int NumElems = VT.getVectorNumElements();
3391   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3392     return false;
3393
3394   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3395     int BitI  = Mask[i];
3396     int BitI1 = Mask[i+1];
3397     if (!isUndefOrEqual(BitI, j))
3398       return false;
3399     if (!isUndefOrEqual(BitI1, j))
3400       return false;
3401   }
3402   return true;
3403 }
3404
3405 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3406   SmallVector<int, 8> M;
3407   N->getMask(M);
3408   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3409 }
3410
3411 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3412 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3413 /// MOVSD, and MOVD, i.e. setting the lowest element.
3414 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3415   if (VT.getVectorElementType().getSizeInBits() < 32)
3416     return false;
3417
3418   int NumElts = VT.getVectorNumElements();
3419
3420   if (!isUndefOrEqual(Mask[0], NumElts))
3421     return false;
3422
3423   for (int i = 1; i < NumElts; ++i)
3424     if (!isUndefOrEqual(Mask[i], i))
3425       return false;
3426
3427   return true;
3428 }
3429
3430 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3431   SmallVector<int, 8> M;
3432   N->getMask(M);
3433   return ::isMOVLMask(M, N->getValueType(0));
3434 }
3435
3436 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3437 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3438 /// element of vector 2 and the other elements to come from vector 1 in order.
3439 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3440                                bool V2IsSplat = false, bool V2IsUndef = false) {
3441   int NumOps = VT.getVectorNumElements();
3442   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3443     return false;
3444
3445   if (!isUndefOrEqual(Mask[0], 0))
3446     return false;
3447
3448   for (int i = 1; i < NumOps; ++i)
3449     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3450           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3451           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3452       return false;
3453
3454   return true;
3455 }
3456
3457 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3458                            bool V2IsUndef = false) {
3459   SmallVector<int, 8> M;
3460   N->getMask(M);
3461   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3462 }
3463
3464 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3465 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3466 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3467   if (N->getValueType(0).getVectorNumElements() != 4)
3468     return false;
3469
3470   // Expect 1, 1, 3, 3
3471   for (unsigned i = 0; i < 2; ++i) {
3472     int Elt = N->getMaskElt(i);
3473     if (Elt >= 0 && Elt != 1)
3474       return false;
3475   }
3476
3477   bool HasHi = false;
3478   for (unsigned i = 2; i < 4; ++i) {
3479     int Elt = N->getMaskElt(i);
3480     if (Elt >= 0 && Elt != 3)
3481       return false;
3482     if (Elt == 3)
3483       HasHi = true;
3484   }
3485   // Don't use movshdup if it can be done with a shufps.
3486   // FIXME: verify that matching u, u, 3, 3 is what we want.
3487   return HasHi;
3488 }
3489
3490 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3491 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3492 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3493   if (N->getValueType(0).getVectorNumElements() != 4)
3494     return false;
3495
3496   // Expect 0, 0, 2, 2
3497   for (unsigned i = 0; i < 2; ++i)
3498     if (N->getMaskElt(i) > 0)
3499       return false;
3500
3501   bool HasHi = false;
3502   for (unsigned i = 2; i < 4; ++i) {
3503     int Elt = N->getMaskElt(i);
3504     if (Elt >= 0 && Elt != 2)
3505       return false;
3506     if (Elt == 2)
3507       HasHi = true;
3508   }
3509   // Don't use movsldup if it can be done with a shufps.
3510   return HasHi;
3511 }
3512
3513 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3514 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3515 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3516   int e = N->getValueType(0).getVectorNumElements() / 2;
3517
3518   for (int i = 0; i < e; ++i)
3519     if (!isUndefOrEqual(N->getMaskElt(i), i))
3520       return false;
3521   for (int i = 0; i < e; ++i)
3522     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3523       return false;
3524   return true;
3525 }
3526
3527 /// isVEXTRACTF128Index - Return true if the specified
3528 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3529 /// suitable for input to VEXTRACTF128.
3530 bool X86::isVEXTRACTF128Index(SDNode *N) {
3531   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3532     return false;
3533
3534   // The index should be aligned on a 128-bit boundary.
3535   uint64_t Index =
3536     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3537
3538   unsigned VL = N->getValueType(0).getVectorNumElements();
3539   unsigned VBits = N->getValueType(0).getSizeInBits();
3540   unsigned ElSize = VBits / VL;
3541   bool Result = (Index * ElSize) % 128 == 0;
3542
3543   return Result;
3544 }
3545
3546 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3547 /// operand specifies a subvector insert that is suitable for input to
3548 /// VINSERTF128.
3549 bool X86::isVINSERTF128Index(SDNode *N) {
3550   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3551     return false;
3552
3553   // The index should be aligned on a 128-bit boundary.
3554   uint64_t Index =
3555     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3556
3557   unsigned VL = N->getValueType(0).getVectorNumElements();
3558   unsigned VBits = N->getValueType(0).getSizeInBits();
3559   unsigned ElSize = VBits / VL;
3560   bool Result = (Index * ElSize) % 128 == 0;
3561
3562   return Result;
3563 }
3564
3565 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3566 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3567 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3568   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3569   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3570
3571   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3572   unsigned Mask = 0;
3573   for (int i = 0; i < NumOperands; ++i) {
3574     int Val = SVOp->getMaskElt(NumOperands-i-1);
3575     if (Val < 0) Val = 0;
3576     if (Val >= NumOperands) Val -= NumOperands;
3577     Mask |= Val;
3578     if (i != NumOperands - 1)
3579       Mask <<= Shift;
3580   }
3581   return Mask;
3582 }
3583
3584 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3585 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3586 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3587   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3588   unsigned Mask = 0;
3589   // 8 nodes, but we only care about the last 4.
3590   for (unsigned i = 7; i >= 4; --i) {
3591     int Val = SVOp->getMaskElt(i);
3592     if (Val >= 0)
3593       Mask |= (Val - 4);
3594     if (i != 4)
3595       Mask <<= 2;
3596   }
3597   return Mask;
3598 }
3599
3600 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3601 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3602 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3603   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3604   unsigned Mask = 0;
3605   // 8 nodes, but we only care about the first 4.
3606   for (int i = 3; i >= 0; --i) {
3607     int Val = SVOp->getMaskElt(i);
3608     if (Val >= 0)
3609       Mask |= Val;
3610     if (i != 0)
3611       Mask <<= 2;
3612   }
3613   return Mask;
3614 }
3615
3616 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3617 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3618 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3619   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3620   EVT VVT = N->getValueType(0);
3621   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3622   int Val = 0;
3623
3624   unsigned i, e;
3625   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3626     Val = SVOp->getMaskElt(i);
3627     if (Val >= 0)
3628       break;
3629   }
3630   return (Val - i) * EltSize;
3631 }
3632
3633 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3634 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3635 /// instructions.
3636 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3637   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3638     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3639
3640   uint64_t Index =
3641     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3642
3643   EVT VecVT = N->getOperand(0).getValueType();
3644   EVT ElVT = VecVT.getVectorElementType();
3645
3646   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3647
3648   return Index / NumElemsPerChunk;
3649 }
3650
3651 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3652 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3653 /// instructions.
3654 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3655   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3656     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3657
3658   uint64_t Index =
3659     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3660
3661   EVT VecVT = N->getValueType(0);
3662   EVT ElVT = VecVT.getVectorElementType();
3663
3664   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3665
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> or <8 x i32> bitcasted to
3842 /// their original type, ensuring they get CSE'd.
3843 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3844   assert(VT.isVector() && "Expected a vector type");
3845   assert((VT.is128BitVector() || VT.is256BitVector())
3846          && "Expected a 128-bit or 256-bit vector type");
3847
3848   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3849
3850   SDValue Vec;
3851   if (VT.is256BitVector()) {
3852     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3853     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
3854   } else
3855     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3856   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3857 }
3858
3859 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3860 /// that point to V2 points to its first element.
3861 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3862   EVT VT = SVOp->getValueType(0);
3863   unsigned NumElems = VT.getVectorNumElements();
3864
3865   bool Changed = false;
3866   SmallVector<int, 8> MaskVec;
3867   SVOp->getMask(MaskVec);
3868
3869   for (unsigned i = 0; i != NumElems; ++i) {
3870     if (MaskVec[i] > (int)NumElems) {
3871       MaskVec[i] = NumElems;
3872       Changed = true;
3873     }
3874   }
3875   if (Changed)
3876     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3877                                 SVOp->getOperand(1), &MaskVec[0]);
3878   return SDValue(SVOp, 0);
3879 }
3880
3881 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3882 /// operation of specified width.
3883 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3884                        SDValue V2) {
3885   unsigned NumElems = VT.getVectorNumElements();
3886   SmallVector<int, 8> Mask;
3887   Mask.push_back(NumElems);
3888   for (unsigned i = 1; i != NumElems; ++i)
3889     Mask.push_back(i);
3890   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3891 }
3892
3893 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3894 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3895                           SDValue V2) {
3896   unsigned NumElems = VT.getVectorNumElements();
3897   SmallVector<int, 8> Mask;
3898   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3899     Mask.push_back(i);
3900     Mask.push_back(i + NumElems);
3901   }
3902   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3903 }
3904
3905 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3906 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3907                           SDValue V2) {
3908   unsigned NumElems = VT.getVectorNumElements();
3909   unsigned Half = NumElems/2;
3910   SmallVector<int, 8> Mask;
3911   for (unsigned i = 0; i != Half; ++i) {
3912     Mask.push_back(i + Half);
3913     Mask.push_back(i + NumElems + Half);
3914   }
3915   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3916 }
3917
3918 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3919 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3920   EVT PVT = MVT::v4f32;
3921   EVT VT = SV->getValueType(0);
3922   DebugLoc dl = SV->getDebugLoc();
3923   SDValue V1 = SV->getOperand(0);
3924   int NumElems = VT.getVectorNumElements();
3925   int EltNo = SV->getSplatIndex();
3926
3927   // unpack elements to the correct location
3928   while (NumElems > 4) {
3929     if (EltNo < NumElems/2) {
3930       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3931     } else {
3932       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3933       EltNo -= NumElems/2;
3934     }
3935     NumElems >>= 1;
3936   }
3937
3938   // Perform the splat.
3939   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3940   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3941   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3942   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3943 }
3944
3945 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3946 /// vector of zero or undef vector.  This produces a shuffle where the low
3947 /// element of V2 is swizzled into the zero/undef vector, landing at element
3948 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3949 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3950                                              bool isZero, bool HasSSE2,
3951                                              SelectionDAG &DAG) {
3952   EVT VT = V2.getValueType();
3953   SDValue V1 = isZero
3954     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3955   unsigned NumElems = VT.getVectorNumElements();
3956   SmallVector<int, 16> MaskVec;
3957   for (unsigned i = 0; i != NumElems; ++i)
3958     // If this is the insertion idx, put the low elt of V2 here.
3959     MaskVec.push_back(i == Idx ? NumElems : i);
3960   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3961 }
3962
3963 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3964 /// element of the result of the vector shuffle.
3965 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3966                                    unsigned Depth) {
3967   if (Depth == 6)
3968     return SDValue();  // Limit search depth.
3969
3970   SDValue V = SDValue(N, 0);
3971   EVT VT = V.getValueType();
3972   unsigned Opcode = V.getOpcode();
3973
3974   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3975   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3976     Index = SV->getMaskElt(Index);
3977
3978     if (Index < 0)
3979       return DAG.getUNDEF(VT.getVectorElementType());
3980
3981     int NumElems = VT.getVectorNumElements();
3982     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3983     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3984   }
3985
3986   // Recurse into target specific vector shuffles to find scalars.
3987   if (isTargetShuffle(Opcode)) {
3988     int NumElems = VT.getVectorNumElements();
3989     SmallVector<unsigned, 16> ShuffleMask;
3990     SDValue ImmN;
3991
3992     switch(Opcode) {
3993     case X86ISD::SHUFPS:
3994     case X86ISD::SHUFPD:
3995       ImmN = N->getOperand(N->getNumOperands()-1);
3996       DecodeSHUFPSMask(NumElems,
3997                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3998                        ShuffleMask);
3999       break;
4000     case X86ISD::PUNPCKHBW:
4001     case X86ISD::PUNPCKHWD:
4002     case X86ISD::PUNPCKHDQ:
4003     case X86ISD::PUNPCKHQDQ:
4004       DecodePUNPCKHMask(NumElems, ShuffleMask);
4005       break;
4006     case X86ISD::UNPCKHPS:
4007     case X86ISD::UNPCKHPD:
4008       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4009       break;
4010     case X86ISD::PUNPCKLBW:
4011     case X86ISD::PUNPCKLWD:
4012     case X86ISD::PUNPCKLDQ:
4013     case X86ISD::PUNPCKLQDQ:
4014       DecodePUNPCKLMask(VT, ShuffleMask);
4015       break;
4016     case X86ISD::UNPCKLPS:
4017     case X86ISD::UNPCKLPD:
4018     case X86ISD::VUNPCKLPS:
4019     case X86ISD::VUNPCKLPD:
4020     case X86ISD::VUNPCKLPSY:
4021     case X86ISD::VUNPCKLPDY:
4022       DecodeUNPCKLPMask(VT, ShuffleMask);
4023       break;
4024     case X86ISD::MOVHLPS:
4025       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4026       break;
4027     case X86ISD::MOVLHPS:
4028       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4029       break;
4030     case X86ISD::PSHUFD:
4031       ImmN = N->getOperand(N->getNumOperands()-1);
4032       DecodePSHUFMask(NumElems,
4033                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4034                       ShuffleMask);
4035       break;
4036     case X86ISD::PSHUFHW:
4037       ImmN = N->getOperand(N->getNumOperands()-1);
4038       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4039                         ShuffleMask);
4040       break;
4041     case X86ISD::PSHUFLW:
4042       ImmN = N->getOperand(N->getNumOperands()-1);
4043       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4044                         ShuffleMask);
4045       break;
4046     case X86ISD::MOVSS:
4047     case X86ISD::MOVSD: {
4048       // The index 0 always comes from the first element of the second source,
4049       // this is why MOVSS and MOVSD are used in the first place. The other
4050       // elements come from the other positions of the first source vector.
4051       unsigned OpNum = (Index == 0) ? 1 : 0;
4052       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4053                                  Depth+1);
4054     }
4055     default:
4056       assert("not implemented for target shuffle node");
4057       return SDValue();
4058     }
4059
4060     Index = ShuffleMask[Index];
4061     if (Index < 0)
4062       return DAG.getUNDEF(VT.getVectorElementType());
4063
4064     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4065     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4066                                Depth+1);
4067   }
4068
4069   // Actual nodes that may contain scalar elements
4070   if (Opcode == ISD::BITCAST) {
4071     V = V.getOperand(0);
4072     EVT SrcVT = V.getValueType();
4073     unsigned NumElems = VT.getVectorNumElements();
4074
4075     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4076       return SDValue();
4077   }
4078
4079   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4080     return (Index == 0) ? V.getOperand(0)
4081                           : DAG.getUNDEF(VT.getVectorElementType());
4082
4083   if (V.getOpcode() == ISD::BUILD_VECTOR)
4084     return V.getOperand(Index);
4085
4086   return SDValue();
4087 }
4088
4089 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4090 /// shuffle operation which come from a consecutively from a zero. The
4091 /// search can start in two different directions, from left or right.
4092 static
4093 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4094                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4095   int i = 0;
4096
4097   while (i < NumElems) {
4098     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4099     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4100     if (!(Elt.getNode() &&
4101          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4102       break;
4103     ++i;
4104   }
4105
4106   return i;
4107 }
4108
4109 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4110 /// MaskE correspond consecutively to elements from one of the vector operands,
4111 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4112 static
4113 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4114                               int OpIdx, int NumElems, unsigned &OpNum) {
4115   bool SeenV1 = false;
4116   bool SeenV2 = false;
4117
4118   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4119     int Idx = SVOp->getMaskElt(i);
4120     // Ignore undef indicies
4121     if (Idx < 0)
4122       continue;
4123
4124     if (Idx < NumElems)
4125       SeenV1 = true;
4126     else
4127       SeenV2 = true;
4128
4129     // Only accept consecutive elements from the same vector
4130     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4131       return false;
4132   }
4133
4134   OpNum = SeenV1 ? 0 : 1;
4135   return true;
4136 }
4137
4138 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4139 /// logical left shift of a vector.
4140 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4141                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4142   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4143   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4144               false /* check zeros from right */, DAG);
4145   unsigned OpSrc;
4146
4147   if (!NumZeros)
4148     return false;
4149
4150   // Considering the elements in the mask that are not consecutive zeros,
4151   // check if they consecutively come from only one of the source vectors.
4152   //
4153   //               V1 = {X, A, B, C}     0
4154   //                         \  \  \    /
4155   //   vector_shuffle V1, V2 <1, 2, 3, X>
4156   //
4157   if (!isShuffleMaskConsecutive(SVOp,
4158             0,                   // Mask Start Index
4159             NumElems-NumZeros-1, // Mask End Index
4160             NumZeros,            // Where to start looking in the src vector
4161             NumElems,            // Number of elements in vector
4162             OpSrc))              // Which source operand ?
4163     return false;
4164
4165   isLeft = false;
4166   ShAmt = NumZeros;
4167   ShVal = SVOp->getOperand(OpSrc);
4168   return true;
4169 }
4170
4171 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4172 /// logical left shift of a vector.
4173 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4174                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4175   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4176   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4177               true /* check zeros from left */, DAG);
4178   unsigned OpSrc;
4179
4180   if (!NumZeros)
4181     return false;
4182
4183   // Considering the elements in the mask that are not consecutive zeros,
4184   // check if they consecutively come from only one of the source vectors.
4185   //
4186   //                           0    { A, B, X, X } = V2
4187   //                          / \    /  /
4188   //   vector_shuffle V1, V2 <X, X, 4, 5>
4189   //
4190   if (!isShuffleMaskConsecutive(SVOp,
4191             NumZeros,     // Mask Start Index
4192             NumElems-1,   // Mask End Index
4193             0,            // Where to start looking in the src vector
4194             NumElems,     // Number of elements in vector
4195             OpSrc))       // Which source operand ?
4196     return false;
4197
4198   isLeft = true;
4199   ShAmt = NumZeros;
4200   ShVal = SVOp->getOperand(OpSrc);
4201   return true;
4202 }
4203
4204 /// isVectorShift - Returns true if the shuffle can be implemented as a
4205 /// logical left or right shift of a vector.
4206 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4207                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4208   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4209       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4210     return true;
4211
4212   return false;
4213 }
4214
4215 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4216 ///
4217 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4218                                        unsigned NumNonZero, unsigned NumZero,
4219                                        SelectionDAG &DAG,
4220                                        const TargetLowering &TLI) {
4221   if (NumNonZero > 8)
4222     return SDValue();
4223
4224   DebugLoc dl = Op.getDebugLoc();
4225   SDValue V(0, 0);
4226   bool First = true;
4227   for (unsigned i = 0; i < 16; ++i) {
4228     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4229     if (ThisIsNonZero && First) {
4230       if (NumZero)
4231         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4232       else
4233         V = DAG.getUNDEF(MVT::v8i16);
4234       First = false;
4235     }
4236
4237     if ((i & 1) != 0) {
4238       SDValue ThisElt(0, 0), LastElt(0, 0);
4239       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4240       if (LastIsNonZero) {
4241         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4242                               MVT::i16, Op.getOperand(i-1));
4243       }
4244       if (ThisIsNonZero) {
4245         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4246         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4247                               ThisElt, DAG.getConstant(8, MVT::i8));
4248         if (LastIsNonZero)
4249           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4250       } else
4251         ThisElt = LastElt;
4252
4253       if (ThisElt.getNode())
4254         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4255                         DAG.getIntPtrConstant(i/2));
4256     }
4257   }
4258
4259   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4260 }
4261
4262 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4263 ///
4264 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4265                                      unsigned NumNonZero, unsigned NumZero,
4266                                      SelectionDAG &DAG,
4267                                      const TargetLowering &TLI) {
4268   if (NumNonZero > 4)
4269     return SDValue();
4270
4271   DebugLoc dl = Op.getDebugLoc();
4272   SDValue V(0, 0);
4273   bool First = true;
4274   for (unsigned i = 0; i < 8; ++i) {
4275     bool isNonZero = (NonZeros & (1 << i)) != 0;
4276     if (isNonZero) {
4277       if (First) {
4278         if (NumZero)
4279           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4280         else
4281           V = DAG.getUNDEF(MVT::v8i16);
4282         First = false;
4283       }
4284       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4285                       MVT::v8i16, V, Op.getOperand(i),
4286                       DAG.getIntPtrConstant(i));
4287     }
4288   }
4289
4290   return V;
4291 }
4292
4293 /// getVShift - Return a vector logical shift node.
4294 ///
4295 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4296                          unsigned NumBits, SelectionDAG &DAG,
4297                          const TargetLowering &TLI, DebugLoc dl) {
4298   EVT ShVT = MVT::v2i64;
4299   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4300   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4301   return DAG.getNode(ISD::BITCAST, dl, VT,
4302                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4303                              DAG.getConstant(NumBits,
4304                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4305 }
4306
4307 SDValue
4308 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4309                                           SelectionDAG &DAG) const {
4310
4311   // Check if the scalar load can be widened into a vector load. And if
4312   // the address is "base + cst" see if the cst can be "absorbed" into
4313   // the shuffle mask.
4314   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4315     SDValue Ptr = LD->getBasePtr();
4316     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4317       return SDValue();
4318     EVT PVT = LD->getValueType(0);
4319     if (PVT != MVT::i32 && PVT != MVT::f32)
4320       return SDValue();
4321
4322     int FI = -1;
4323     int64_t Offset = 0;
4324     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4325       FI = FINode->getIndex();
4326       Offset = 0;
4327     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4328                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4329       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4330       Offset = Ptr.getConstantOperandVal(1);
4331       Ptr = Ptr.getOperand(0);
4332     } else {
4333       return SDValue();
4334     }
4335
4336     SDValue Chain = LD->getChain();
4337     // Make sure the stack object alignment is at least 16.
4338     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4339     if (DAG.InferPtrAlignment(Ptr) < 16) {
4340       if (MFI->isFixedObjectIndex(FI)) {
4341         // Can't change the alignment. FIXME: It's possible to compute
4342         // the exact stack offset and reference FI + adjust offset instead.
4343         // If someone *really* cares about this. That's the way to implement it.
4344         return SDValue();
4345       } else {
4346         MFI->setObjectAlignment(FI, 16);
4347       }
4348     }
4349
4350     // (Offset % 16) must be multiple of 4. Then address is then
4351     // Ptr + (Offset & ~15).
4352     if (Offset < 0)
4353       return SDValue();
4354     if ((Offset % 16) & 3)
4355       return SDValue();
4356     int64_t StartOffset = Offset & ~15;
4357     if (StartOffset)
4358       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4359                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4360
4361     int EltNo = (Offset - StartOffset) >> 2;
4362     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4363     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4364     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4365                              LD->getPointerInfo().getWithOffset(StartOffset),
4366                              false, false, 0);
4367     // Canonicalize it to a v4i32 shuffle.
4368     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4369     return DAG.getNode(ISD::BITCAST, dl, VT,
4370                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4371                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4372   }
4373
4374   return SDValue();
4375 }
4376
4377 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4378 /// vector of type 'VT', see if the elements can be replaced by a single large
4379 /// load which has the same value as a build_vector whose operands are 'elts'.
4380 ///
4381 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4382 ///
4383 /// FIXME: we'd also like to handle the case where the last elements are zero
4384 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4385 /// There's even a handy isZeroNode for that purpose.
4386 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4387                                         DebugLoc &DL, SelectionDAG &DAG) {
4388   EVT EltVT = VT.getVectorElementType();
4389   unsigned NumElems = Elts.size();
4390
4391   LoadSDNode *LDBase = NULL;
4392   unsigned LastLoadedElt = -1U;
4393
4394   // For each element in the initializer, see if we've found a load or an undef.
4395   // If we don't find an initial load element, or later load elements are
4396   // non-consecutive, bail out.
4397   for (unsigned i = 0; i < NumElems; ++i) {
4398     SDValue Elt = Elts[i];
4399
4400     if (!Elt.getNode() ||
4401         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4402       return SDValue();
4403     if (!LDBase) {
4404       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4405         return SDValue();
4406       LDBase = cast<LoadSDNode>(Elt.getNode());
4407       LastLoadedElt = i;
4408       continue;
4409     }
4410     if (Elt.getOpcode() == ISD::UNDEF)
4411       continue;
4412
4413     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4414     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4415       return SDValue();
4416     LastLoadedElt = i;
4417   }
4418
4419   // If we have found an entire vector of loads and undefs, then return a large
4420   // load of the entire vector width starting at the base pointer.  If we found
4421   // consecutive loads for the low half, generate a vzext_load node.
4422   if (LastLoadedElt == NumElems - 1) {
4423     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4424       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4425                          LDBase->getPointerInfo(),
4426                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4427     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4428                        LDBase->getPointerInfo(),
4429                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4430                        LDBase->getAlignment());
4431   } else if (NumElems == 4 && LastLoadedElt == 1) {
4432     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4433     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4434     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4435                                               Ops, 2, MVT::i32,
4436                                               LDBase->getMemOperand());
4437     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4438   }
4439   return SDValue();
4440 }
4441
4442 SDValue
4443 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4444   DebugLoc dl = Op.getDebugLoc();
4445
4446   EVT VT = Op.getValueType();
4447   EVT ExtVT = VT.getVectorElementType();
4448
4449   unsigned NumElems = Op.getNumOperands();
4450
4451   // For AVX-length vectors, build the individual 128-bit pieces and
4452   // use shuffles to put them in place.
4453   if (VT.getSizeInBits() > 256 &&
4454       Subtarget->hasAVX() &&
4455       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4456     SmallVector<SDValue, 8> V;
4457     V.resize(NumElems);
4458     for (unsigned i = 0; i < NumElems; ++i) {
4459       V[i] = Op.getOperand(i);
4460     }
4461
4462     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4463
4464     // Build the lower subvector.
4465     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4466     // Build the upper subvector.
4467     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4468                                 NumElems/2);
4469
4470     return ConcatVectors(Lower, Upper, DAG);
4471   }
4472
4473   // All zero's:
4474   //  - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4475   // All one's:
4476   //  - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4477   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4478       ISD::isBuildVectorAllOnes(Op.getNode())) {
4479     // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4480     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4481     // eliminated on x86-32 hosts.
4482     if (Op.getValueType() == MVT::v4i32 ||
4483         Op.getValueType() == MVT::v8i32)
4484       return Op;
4485
4486     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4487       return getOnesVector(Op.getValueType(), DAG, dl);
4488     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4489   }
4490
4491   unsigned EVTBits = ExtVT.getSizeInBits();
4492
4493   unsigned NumZero  = 0;
4494   unsigned NumNonZero = 0;
4495   unsigned NonZeros = 0;
4496   bool IsAllConstants = true;
4497   SmallSet<SDValue, 8> Values;
4498   for (unsigned i = 0; i < NumElems; ++i) {
4499     SDValue Elt = Op.getOperand(i);
4500     if (Elt.getOpcode() == ISD::UNDEF)
4501       continue;
4502     Values.insert(Elt);
4503     if (Elt.getOpcode() != ISD::Constant &&
4504         Elt.getOpcode() != ISD::ConstantFP)
4505       IsAllConstants = false;
4506     if (X86::isZeroNode(Elt))
4507       NumZero++;
4508     else {
4509       NonZeros |= (1 << i);
4510       NumNonZero++;
4511     }
4512   }
4513
4514   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4515   if (NumNonZero == 0)
4516     return DAG.getUNDEF(VT);
4517
4518   // Special case for single non-zero, non-undef, element.
4519   if (NumNonZero == 1) {
4520     unsigned Idx = CountTrailingZeros_32(NonZeros);
4521     SDValue Item = Op.getOperand(Idx);
4522
4523     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4524     // the value are obviously zero, truncate the value to i32 and do the
4525     // insertion that way.  Only do this if the value is non-constant or if the
4526     // value is a constant being inserted into element 0.  It is cheaper to do
4527     // a constant pool load than it is to do a movd + shuffle.
4528     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4529         (!IsAllConstants || Idx == 0)) {
4530       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4531         // Handle SSE only.
4532         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4533         EVT VecVT = MVT::v4i32;
4534         unsigned VecElts = 4;
4535
4536         // Truncate the value (which may itself be a constant) to i32, and
4537         // convert it to a vector with movd (S2V+shuffle to zero extend).
4538         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4539         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4540         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4541                                            Subtarget->hasSSE2(), DAG);
4542
4543         // Now we have our 32-bit value zero extended in the low element of
4544         // a vector.  If Idx != 0, swizzle it into place.
4545         if (Idx != 0) {
4546           SmallVector<int, 4> Mask;
4547           Mask.push_back(Idx);
4548           for (unsigned i = 1; i != VecElts; ++i)
4549             Mask.push_back(i);
4550           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4551                                       DAG.getUNDEF(Item.getValueType()),
4552                                       &Mask[0]);
4553         }
4554         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4555       }
4556     }
4557
4558     // If we have a constant or non-constant insertion into the low element of
4559     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4560     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4561     // depending on what the source datatype is.
4562     if (Idx == 0) {
4563       if (NumZero == 0) {
4564         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4565       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4566           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4567         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4568         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4569         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4570                                            DAG);
4571       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4572         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4573         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4574         EVT MiddleVT = MVT::v4i32;
4575         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4576         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4577                                            Subtarget->hasSSE2(), DAG);
4578         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4579       }
4580     }
4581
4582     // Is it a vector logical left shift?
4583     if (NumElems == 2 && Idx == 1 &&
4584         X86::isZeroNode(Op.getOperand(0)) &&
4585         !X86::isZeroNode(Op.getOperand(1))) {
4586       unsigned NumBits = VT.getSizeInBits();
4587       return getVShift(true, VT,
4588                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4589                                    VT, Op.getOperand(1)),
4590                        NumBits/2, DAG, *this, dl);
4591     }
4592
4593     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4594       return SDValue();
4595
4596     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4597     // is a non-constant being inserted into an element other than the low one,
4598     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4599     // movd/movss) to move this into the low element, then shuffle it into
4600     // place.
4601     if (EVTBits == 32) {
4602       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4603
4604       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4605       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4606                                          Subtarget->hasSSE2(), DAG);
4607       SmallVector<int, 8> MaskVec;
4608       for (unsigned i = 0; i < NumElems; i++)
4609         MaskVec.push_back(i == Idx ? 0 : 1);
4610       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4611     }
4612   }
4613
4614   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4615   if (Values.size() == 1) {
4616     if (EVTBits == 32) {
4617       // Instead of a shuffle like this:
4618       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4619       // Check if it's possible to issue this instead.
4620       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4621       unsigned Idx = CountTrailingZeros_32(NonZeros);
4622       SDValue Item = Op.getOperand(Idx);
4623       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4624         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4625     }
4626     return SDValue();
4627   }
4628
4629   // A vector full of immediates; various special cases are already
4630   // handled, so this is best done with a single constant-pool load.
4631   if (IsAllConstants)
4632     return SDValue();
4633
4634   // Let legalizer expand 2-wide build_vectors.
4635   if (EVTBits == 64) {
4636     if (NumNonZero == 1) {
4637       // One half is zero or undef.
4638       unsigned Idx = CountTrailingZeros_32(NonZeros);
4639       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4640                                  Op.getOperand(Idx));
4641       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4642                                          Subtarget->hasSSE2(), DAG);
4643     }
4644     return SDValue();
4645   }
4646
4647   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4648   if (EVTBits == 8 && NumElems == 16) {
4649     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4650                                         *this);
4651     if (V.getNode()) return V;
4652   }
4653
4654   if (EVTBits == 16 && NumElems == 8) {
4655     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4656                                       *this);
4657     if (V.getNode()) return V;
4658   }
4659
4660   // If element VT is == 32 bits, turn it into a number of shuffles.
4661   SmallVector<SDValue, 8> V;
4662   V.resize(NumElems);
4663   if (NumElems == 4 && NumZero > 0) {
4664     for (unsigned i = 0; i < 4; ++i) {
4665       bool isZero = !(NonZeros & (1 << i));
4666       if (isZero)
4667         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4668       else
4669         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4670     }
4671
4672     for (unsigned i = 0; i < 2; ++i) {
4673       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4674         default: break;
4675         case 0:
4676           V[i] = V[i*2];  // Must be a zero vector.
4677           break;
4678         case 1:
4679           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4680           break;
4681         case 2:
4682           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4683           break;
4684         case 3:
4685           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4686           break;
4687       }
4688     }
4689
4690     SmallVector<int, 8> MaskVec;
4691     bool Reverse = (NonZeros & 0x3) == 2;
4692     for (unsigned i = 0; i < 2; ++i)
4693       MaskVec.push_back(Reverse ? 1-i : i);
4694     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4695     for (unsigned i = 0; i < 2; ++i)
4696       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4697     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4698   }
4699
4700   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4701     // Check for a build vector of consecutive loads.
4702     for (unsigned i = 0; i < NumElems; ++i)
4703       V[i] = Op.getOperand(i);
4704
4705     // Check for elements which are consecutive loads.
4706     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4707     if (LD.getNode())
4708       return LD;
4709
4710     // For SSE 4.1, use insertps to put the high elements into the low element.
4711     if (getSubtarget()->hasSSE41()) {
4712       SDValue Result;
4713       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4714         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4715       else
4716         Result = DAG.getUNDEF(VT);
4717
4718       for (unsigned i = 1; i < NumElems; ++i) {
4719         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4720         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4721                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4722       }
4723       return Result;
4724     }
4725
4726     // Otherwise, expand into a number of unpckl*, start by extending each of
4727     // our (non-undef) elements to the full vector width with the element in the
4728     // bottom slot of the vector (which generates no code for SSE).
4729     for (unsigned i = 0; i < NumElems; ++i) {
4730       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4731         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4732       else
4733         V[i] = DAG.getUNDEF(VT);
4734     }
4735
4736     // Next, we iteratively mix elements, e.g. for v4f32:
4737     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4738     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4739     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4740     unsigned EltStride = NumElems >> 1;
4741     while (EltStride != 0) {
4742       for (unsigned i = 0; i < EltStride; ++i) {
4743         // If V[i+EltStride] is undef and this is the first round of mixing,
4744         // then it is safe to just drop this shuffle: V[i] is already in the
4745         // right place, the one element (since it's the first round) being
4746         // inserted as undef can be dropped.  This isn't safe for successive
4747         // rounds because they will permute elements within both vectors.
4748         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4749             EltStride == NumElems/2)
4750           continue;
4751
4752         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4753       }
4754       EltStride >>= 1;
4755     }
4756     return V[0];
4757   }
4758   return SDValue();
4759 }
4760
4761 SDValue
4762 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4763   // We support concatenate two MMX registers and place them in a MMX
4764   // register.  This is better than doing a stack convert.
4765   DebugLoc dl = Op.getDebugLoc();
4766   EVT ResVT = Op.getValueType();
4767   assert(Op.getNumOperands() == 2);
4768   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4769          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4770   int Mask[2];
4771   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4772   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4773   InVec = Op.getOperand(1);
4774   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4775     unsigned NumElts = ResVT.getVectorNumElements();
4776     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4777     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4778                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4779   } else {
4780     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4781     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4782     Mask[0] = 0; Mask[1] = 2;
4783     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4784   }
4785   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4786 }
4787
4788 // v8i16 shuffles - Prefer shuffles in the following order:
4789 // 1. [all]   pshuflw, pshufhw, optional move
4790 // 2. [ssse3] 1 x pshufb
4791 // 3. [ssse3] 2 x pshufb + 1 x por
4792 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4793 SDValue
4794 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4795                                             SelectionDAG &DAG) const {
4796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4797   SDValue V1 = SVOp->getOperand(0);
4798   SDValue V2 = SVOp->getOperand(1);
4799   DebugLoc dl = SVOp->getDebugLoc();
4800   SmallVector<int, 8> MaskVals;
4801
4802   // Determine if more than 1 of the words in each of the low and high quadwords
4803   // of the result come from the same quadword of one of the two inputs.  Undef
4804   // mask values count as coming from any quadword, for better codegen.
4805   SmallVector<unsigned, 4> LoQuad(4);
4806   SmallVector<unsigned, 4> HiQuad(4);
4807   BitVector InputQuads(4);
4808   for (unsigned i = 0; i < 8; ++i) {
4809     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4810     int EltIdx = SVOp->getMaskElt(i);
4811     MaskVals.push_back(EltIdx);
4812     if (EltIdx < 0) {
4813       ++Quad[0];
4814       ++Quad[1];
4815       ++Quad[2];
4816       ++Quad[3];
4817       continue;
4818     }
4819     ++Quad[EltIdx / 4];
4820     InputQuads.set(EltIdx / 4);
4821   }
4822
4823   int BestLoQuad = -1;
4824   unsigned MaxQuad = 1;
4825   for (unsigned i = 0; i < 4; ++i) {
4826     if (LoQuad[i] > MaxQuad) {
4827       BestLoQuad = i;
4828       MaxQuad = LoQuad[i];
4829     }
4830   }
4831
4832   int BestHiQuad = -1;
4833   MaxQuad = 1;
4834   for (unsigned i = 0; i < 4; ++i) {
4835     if (HiQuad[i] > MaxQuad) {
4836       BestHiQuad = i;
4837       MaxQuad = HiQuad[i];
4838     }
4839   }
4840
4841   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4842   // of the two input vectors, shuffle them into one input vector so only a
4843   // single pshufb instruction is necessary. If There are more than 2 input
4844   // quads, disable the next transformation since it does not help SSSE3.
4845   bool V1Used = InputQuads[0] || InputQuads[1];
4846   bool V2Used = InputQuads[2] || InputQuads[3];
4847   if (Subtarget->hasSSSE3()) {
4848     if (InputQuads.count() == 2 && V1Used && V2Used) {
4849       BestLoQuad = InputQuads.find_first();
4850       BestHiQuad = InputQuads.find_next(BestLoQuad);
4851     }
4852     if (InputQuads.count() > 2) {
4853       BestLoQuad = -1;
4854       BestHiQuad = -1;
4855     }
4856   }
4857
4858   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4859   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4860   // words from all 4 input quadwords.
4861   SDValue NewV;
4862   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4863     SmallVector<int, 8> MaskV;
4864     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4865     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4866     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4867                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4868                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4869     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4870
4871     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4872     // source words for the shuffle, to aid later transformations.
4873     bool AllWordsInNewV = true;
4874     bool InOrder[2] = { true, true };
4875     for (unsigned i = 0; i != 8; ++i) {
4876       int idx = MaskVals[i];
4877       if (idx != (int)i)
4878         InOrder[i/4] = false;
4879       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4880         continue;
4881       AllWordsInNewV = false;
4882       break;
4883     }
4884
4885     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4886     if (AllWordsInNewV) {
4887       for (int i = 0; i != 8; ++i) {
4888         int idx = MaskVals[i];
4889         if (idx < 0)
4890           continue;
4891         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4892         if ((idx != i) && idx < 4)
4893           pshufhw = false;
4894         if ((idx != i) && idx > 3)
4895           pshuflw = false;
4896       }
4897       V1 = NewV;
4898       V2Used = false;
4899       BestLoQuad = 0;
4900       BestHiQuad = 1;
4901     }
4902
4903     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4904     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4905     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4906       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4907       unsigned TargetMask = 0;
4908       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4909                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4910       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4911                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4912       V1 = NewV.getOperand(0);
4913       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4914     }
4915   }
4916
4917   // If we have SSSE3, and all words of the result are from 1 input vector,
4918   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4919   // is present, fall back to case 4.
4920   if (Subtarget->hasSSSE3()) {
4921     SmallVector<SDValue,16> pshufbMask;
4922
4923     // If we have elements from both input vectors, set the high bit of the
4924     // shuffle mask element to zero out elements that come from V2 in the V1
4925     // mask, and elements that come from V1 in the V2 mask, so that the two
4926     // results can be OR'd together.
4927     bool TwoInputs = V1Used && V2Used;
4928     for (unsigned i = 0; i != 8; ++i) {
4929       int EltIdx = MaskVals[i] * 2;
4930       if (TwoInputs && (EltIdx >= 16)) {
4931         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4932         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4933         continue;
4934       }
4935       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4936       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4937     }
4938     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4939     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4940                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4941                                  MVT::v16i8, &pshufbMask[0], 16));
4942     if (!TwoInputs)
4943       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4944
4945     // Calculate the shuffle mask for the second input, shuffle it, and
4946     // OR it with the first shuffled input.
4947     pshufbMask.clear();
4948     for (unsigned i = 0; i != 8; ++i) {
4949       int EltIdx = MaskVals[i] * 2;
4950       if (EltIdx < 16) {
4951         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4952         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4953         continue;
4954       }
4955       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4956       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4957     }
4958     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4959     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4960                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4961                                  MVT::v16i8, &pshufbMask[0], 16));
4962     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4963     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4964   }
4965
4966   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4967   // and update MaskVals with new element order.
4968   BitVector InOrder(8);
4969   if (BestLoQuad >= 0) {
4970     SmallVector<int, 8> MaskV;
4971     for (int i = 0; i != 4; ++i) {
4972       int idx = MaskVals[i];
4973       if (idx < 0) {
4974         MaskV.push_back(-1);
4975         InOrder.set(i);
4976       } else if ((idx / 4) == BestLoQuad) {
4977         MaskV.push_back(idx & 3);
4978         InOrder.set(i);
4979       } else {
4980         MaskV.push_back(-1);
4981       }
4982     }
4983     for (unsigned i = 4; i != 8; ++i)
4984       MaskV.push_back(i);
4985     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4986                                 &MaskV[0]);
4987
4988     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4989       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4990                                NewV.getOperand(0),
4991                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4992                                DAG);
4993   }
4994
4995   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4996   // and update MaskVals with the new element order.
4997   if (BestHiQuad >= 0) {
4998     SmallVector<int, 8> MaskV;
4999     for (unsigned i = 0; i != 4; ++i)
5000       MaskV.push_back(i);
5001     for (unsigned i = 4; i != 8; ++i) {
5002       int idx = MaskVals[i];
5003       if (idx < 0) {
5004         MaskV.push_back(-1);
5005         InOrder.set(i);
5006       } else if ((idx / 4) == BestHiQuad) {
5007         MaskV.push_back((idx & 3) + 4);
5008         InOrder.set(i);
5009       } else {
5010         MaskV.push_back(-1);
5011       }
5012     }
5013     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5014                                 &MaskV[0]);
5015
5016     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5017       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5018                               NewV.getOperand(0),
5019                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5020                               DAG);
5021   }
5022
5023   // In case BestHi & BestLo were both -1, which means each quadword has a word
5024   // from each of the four input quadwords, calculate the InOrder bitvector now
5025   // before falling through to the insert/extract cleanup.
5026   if (BestLoQuad == -1 && BestHiQuad == -1) {
5027     NewV = V1;
5028     for (int i = 0; i != 8; ++i)
5029       if (MaskVals[i] < 0 || MaskVals[i] == i)
5030         InOrder.set(i);
5031   }
5032
5033   // The other elements are put in the right place using pextrw and pinsrw.
5034   for (unsigned i = 0; i != 8; ++i) {
5035     if (InOrder[i])
5036       continue;
5037     int EltIdx = MaskVals[i];
5038     if (EltIdx < 0)
5039       continue;
5040     SDValue ExtOp = (EltIdx < 8)
5041     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5042                   DAG.getIntPtrConstant(EltIdx))
5043     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5044                   DAG.getIntPtrConstant(EltIdx - 8));
5045     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5046                        DAG.getIntPtrConstant(i));
5047   }
5048   return NewV;
5049 }
5050
5051 // v16i8 shuffles - Prefer shuffles in the following order:
5052 // 1. [ssse3] 1 x pshufb
5053 // 2. [ssse3] 2 x pshufb + 1 x por
5054 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5055 static
5056 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5057                                  SelectionDAG &DAG,
5058                                  const X86TargetLowering &TLI) {
5059   SDValue V1 = SVOp->getOperand(0);
5060   SDValue V2 = SVOp->getOperand(1);
5061   DebugLoc dl = SVOp->getDebugLoc();
5062   SmallVector<int, 16> MaskVals;
5063   SVOp->getMask(MaskVals);
5064
5065   // If we have SSSE3, case 1 is generated when all result bytes come from
5066   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5067   // present, fall back to case 3.
5068   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5069   bool V1Only = true;
5070   bool V2Only = true;
5071   for (unsigned i = 0; i < 16; ++i) {
5072     int EltIdx = MaskVals[i];
5073     if (EltIdx < 0)
5074       continue;
5075     if (EltIdx < 16)
5076       V2Only = false;
5077     else
5078       V1Only = false;
5079   }
5080
5081   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5082   if (TLI.getSubtarget()->hasSSSE3()) {
5083     SmallVector<SDValue,16> pshufbMask;
5084
5085     // If all result elements are from one input vector, then only translate
5086     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5087     //
5088     // Otherwise, we have elements from both input vectors, and must zero out
5089     // elements that come from V2 in the first mask, and V1 in the second mask
5090     // so that we can OR them together.
5091     bool TwoInputs = !(V1Only || V2Only);
5092     for (unsigned i = 0; i != 16; ++i) {
5093       int EltIdx = MaskVals[i];
5094       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5095         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5096         continue;
5097       }
5098       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5099     }
5100     // If all the elements are from V2, assign it to V1 and return after
5101     // building the first pshufb.
5102     if (V2Only)
5103       V1 = V2;
5104     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5105                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5106                                  MVT::v16i8, &pshufbMask[0], 16));
5107     if (!TwoInputs)
5108       return V1;
5109
5110     // Calculate the shuffle mask for the second input, shuffle it, and
5111     // OR it with the first shuffled input.
5112     pshufbMask.clear();
5113     for (unsigned i = 0; i != 16; ++i) {
5114       int EltIdx = MaskVals[i];
5115       if (EltIdx < 16) {
5116         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5117         continue;
5118       }
5119       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5120     }
5121     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5122                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5123                                  MVT::v16i8, &pshufbMask[0], 16));
5124     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5125   }
5126
5127   // No SSSE3 - Calculate in place words and then fix all out of place words
5128   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5129   // the 16 different words that comprise the two doublequadword input vectors.
5130   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5131   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5132   SDValue NewV = V2Only ? V2 : V1;
5133   for (int i = 0; i != 8; ++i) {
5134     int Elt0 = MaskVals[i*2];
5135     int Elt1 = MaskVals[i*2+1];
5136
5137     // This word of the result is all undef, skip it.
5138     if (Elt0 < 0 && Elt1 < 0)
5139       continue;
5140
5141     // This word of the result is already in the correct place, skip it.
5142     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5143       continue;
5144     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5145       continue;
5146
5147     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5148     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5149     SDValue InsElt;
5150
5151     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5152     // using a single extract together, load it and store it.
5153     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5154       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5155                            DAG.getIntPtrConstant(Elt1 / 2));
5156       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5157                         DAG.getIntPtrConstant(i));
5158       continue;
5159     }
5160
5161     // If Elt1 is defined, extract it from the appropriate source.  If the
5162     // source byte is not also odd, shift the extracted word left 8 bits
5163     // otherwise clear the bottom 8 bits if we need to do an or.
5164     if (Elt1 >= 0) {
5165       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5166                            DAG.getIntPtrConstant(Elt1 / 2));
5167       if ((Elt1 & 1) == 0)
5168         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5169                              DAG.getConstant(8,
5170                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5171       else if (Elt0 >= 0)
5172         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5173                              DAG.getConstant(0xFF00, MVT::i16));
5174     }
5175     // If Elt0 is defined, extract it from the appropriate source.  If the
5176     // source byte is not also even, shift the extracted word right 8 bits. If
5177     // Elt1 was also defined, OR the extracted values together before
5178     // inserting them in the result.
5179     if (Elt0 >= 0) {
5180       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5181                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5182       if ((Elt0 & 1) != 0)
5183         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5184                               DAG.getConstant(8,
5185                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5186       else if (Elt1 >= 0)
5187         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5188                              DAG.getConstant(0x00FF, MVT::i16));
5189       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5190                          : InsElt0;
5191     }
5192     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5193                        DAG.getIntPtrConstant(i));
5194   }
5195   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5196 }
5197
5198 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5199 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5200 /// done when every pair / quad of shuffle mask elements point to elements in
5201 /// the right sequence. e.g.
5202 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5203 static
5204 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5205                                  SelectionDAG &DAG, DebugLoc dl) {
5206   EVT VT = SVOp->getValueType(0);
5207   SDValue V1 = SVOp->getOperand(0);
5208   SDValue V2 = SVOp->getOperand(1);
5209   unsigned NumElems = VT.getVectorNumElements();
5210   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5211   EVT NewVT;
5212   switch (VT.getSimpleVT().SimpleTy) {
5213   default: assert(false && "Unexpected!");
5214   case MVT::v4f32: NewVT = MVT::v2f64; break;
5215   case MVT::v4i32: NewVT = MVT::v2i64; break;
5216   case MVT::v8i16: NewVT = MVT::v4i32; break;
5217   case MVT::v16i8: NewVT = MVT::v4i32; break;
5218   }
5219
5220   int Scale = NumElems / NewWidth;
5221   SmallVector<int, 8> MaskVec;
5222   for (unsigned i = 0; i < NumElems; i += Scale) {
5223     int StartIdx = -1;
5224     for (int j = 0; j < Scale; ++j) {
5225       int EltIdx = SVOp->getMaskElt(i+j);
5226       if (EltIdx < 0)
5227         continue;
5228       if (StartIdx == -1)
5229         StartIdx = EltIdx - (EltIdx % Scale);
5230       if (EltIdx != StartIdx + j)
5231         return SDValue();
5232     }
5233     if (StartIdx == -1)
5234       MaskVec.push_back(-1);
5235     else
5236       MaskVec.push_back(StartIdx / Scale);
5237   }
5238
5239   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5240   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5241   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5242 }
5243
5244 /// getVZextMovL - Return a zero-extending vector move low node.
5245 ///
5246 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5247                             SDValue SrcOp, SelectionDAG &DAG,
5248                             const X86Subtarget *Subtarget, DebugLoc dl) {
5249   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5250     LoadSDNode *LD = NULL;
5251     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5252       LD = dyn_cast<LoadSDNode>(SrcOp);
5253     if (!LD) {
5254       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5255       // instead.
5256       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5257       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5258           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5259           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5260           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5261         // PR2108
5262         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5263         return DAG.getNode(ISD::BITCAST, dl, VT,
5264                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5265                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5266                                                    OpVT,
5267                                                    SrcOp.getOperand(0)
5268                                                           .getOperand(0))));
5269       }
5270     }
5271   }
5272
5273   return DAG.getNode(ISD::BITCAST, dl, VT,
5274                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5275                                  DAG.getNode(ISD::BITCAST, dl,
5276                                              OpVT, SrcOp)));
5277 }
5278
5279 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5280 /// shuffles.
5281 static SDValue
5282 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5283   SDValue V1 = SVOp->getOperand(0);
5284   SDValue V2 = SVOp->getOperand(1);
5285   DebugLoc dl = SVOp->getDebugLoc();
5286   EVT VT = SVOp->getValueType(0);
5287
5288   SmallVector<std::pair<int, int>, 8> Locs;
5289   Locs.resize(4);
5290   SmallVector<int, 8> Mask1(4U, -1);
5291   SmallVector<int, 8> PermMask;
5292   SVOp->getMask(PermMask);
5293
5294   unsigned NumHi = 0;
5295   unsigned NumLo = 0;
5296   for (unsigned i = 0; i != 4; ++i) {
5297     int Idx = PermMask[i];
5298     if (Idx < 0) {
5299       Locs[i] = std::make_pair(-1, -1);
5300     } else {
5301       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5302       if (Idx < 4) {
5303         Locs[i] = std::make_pair(0, NumLo);
5304         Mask1[NumLo] = Idx;
5305         NumLo++;
5306       } else {
5307         Locs[i] = std::make_pair(1, NumHi);
5308         if (2+NumHi < 4)
5309           Mask1[2+NumHi] = Idx;
5310         NumHi++;
5311       }
5312     }
5313   }
5314
5315   if (NumLo <= 2 && NumHi <= 2) {
5316     // If no more than two elements come from either vector. This can be
5317     // implemented with two shuffles. First shuffle gather the elements.
5318     // The second shuffle, which takes the first shuffle as both of its
5319     // vector operands, put the elements into the right order.
5320     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5321
5322     SmallVector<int, 8> Mask2(4U, -1);
5323
5324     for (unsigned i = 0; i != 4; ++i) {
5325       if (Locs[i].first == -1)
5326         continue;
5327       else {
5328         unsigned Idx = (i < 2) ? 0 : 4;
5329         Idx += Locs[i].first * 2 + Locs[i].second;
5330         Mask2[i] = Idx;
5331       }
5332     }
5333
5334     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5335   } else if (NumLo == 3 || NumHi == 3) {
5336     // Otherwise, we must have three elements from one vector, call it X, and
5337     // one element from the other, call it Y.  First, use a shufps to build an
5338     // intermediate vector with the one element from Y and the element from X
5339     // that will be in the same half in the final destination (the indexes don't
5340     // matter). Then, use a shufps to build the final vector, taking the half
5341     // containing the element from Y from the intermediate, and the other half
5342     // from X.
5343     if (NumHi == 3) {
5344       // Normalize it so the 3 elements come from V1.
5345       CommuteVectorShuffleMask(PermMask, VT);
5346       std::swap(V1, V2);
5347     }
5348
5349     // Find the element from V2.
5350     unsigned HiIndex;
5351     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5352       int Val = PermMask[HiIndex];
5353       if (Val < 0)
5354         continue;
5355       if (Val >= 4)
5356         break;
5357     }
5358
5359     Mask1[0] = PermMask[HiIndex];
5360     Mask1[1] = -1;
5361     Mask1[2] = PermMask[HiIndex^1];
5362     Mask1[3] = -1;
5363     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5364
5365     if (HiIndex >= 2) {
5366       Mask1[0] = PermMask[0];
5367       Mask1[1] = PermMask[1];
5368       Mask1[2] = HiIndex & 1 ? 6 : 4;
5369       Mask1[3] = HiIndex & 1 ? 4 : 6;
5370       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5371     } else {
5372       Mask1[0] = HiIndex & 1 ? 2 : 0;
5373       Mask1[1] = HiIndex & 1 ? 0 : 2;
5374       Mask1[2] = PermMask[2];
5375       Mask1[3] = PermMask[3];
5376       if (Mask1[2] >= 0)
5377         Mask1[2] += 4;
5378       if (Mask1[3] >= 0)
5379         Mask1[3] += 4;
5380       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5381     }
5382   }
5383
5384   // Break it into (shuffle shuffle_hi, shuffle_lo).
5385   Locs.clear();
5386   Locs.resize(4);
5387   SmallVector<int,8> LoMask(4U, -1);
5388   SmallVector<int,8> HiMask(4U, -1);
5389
5390   SmallVector<int,8> *MaskPtr = &LoMask;
5391   unsigned MaskIdx = 0;
5392   unsigned LoIdx = 0;
5393   unsigned HiIdx = 2;
5394   for (unsigned i = 0; i != 4; ++i) {
5395     if (i == 2) {
5396       MaskPtr = &HiMask;
5397       MaskIdx = 1;
5398       LoIdx = 0;
5399       HiIdx = 2;
5400     }
5401     int Idx = PermMask[i];
5402     if (Idx < 0) {
5403       Locs[i] = std::make_pair(-1, -1);
5404     } else if (Idx < 4) {
5405       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5406       (*MaskPtr)[LoIdx] = Idx;
5407       LoIdx++;
5408     } else {
5409       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5410       (*MaskPtr)[HiIdx] = Idx;
5411       HiIdx++;
5412     }
5413   }
5414
5415   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5416   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5417   SmallVector<int, 8> MaskOps;
5418   for (unsigned i = 0; i != 4; ++i) {
5419     if (Locs[i].first == -1) {
5420       MaskOps.push_back(-1);
5421     } else {
5422       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5423       MaskOps.push_back(Idx);
5424     }
5425   }
5426   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5427 }
5428
5429 static bool MayFoldVectorLoad(SDValue V) {
5430   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5431     V = V.getOperand(0);
5432   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5433     V = V.getOperand(0);
5434   if (MayFoldLoad(V))
5435     return true;
5436   return false;
5437 }
5438
5439 // FIXME: the version above should always be used. Since there's
5440 // a bug where several vector shuffles can't be folded because the
5441 // DAG is not updated during lowering and a node claims to have two
5442 // uses while it only has one, use this version, and let isel match
5443 // another instruction if the load really happens to have more than
5444 // one use. Remove this version after this bug get fixed.
5445 // rdar://8434668, PR8156
5446 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5447   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5448     V = V.getOperand(0);
5449   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5450     V = V.getOperand(0);
5451   if (ISD::isNormalLoad(V.getNode()))
5452     return true;
5453   return false;
5454 }
5455
5456 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5457 /// a vector extract, and if both can be later optimized into a single load.
5458 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5459 /// here because otherwise a target specific shuffle node is going to be
5460 /// emitted for this shuffle, and the optimization not done.
5461 /// FIXME: This is probably not the best approach, but fix the problem
5462 /// until the right path is decided.
5463 static
5464 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5465                                          const TargetLowering &TLI) {
5466   EVT VT = V.getValueType();
5467   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5468
5469   // Be sure that the vector shuffle is present in a pattern like this:
5470   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5471   if (!V.hasOneUse())
5472     return false;
5473
5474   SDNode *N = *V.getNode()->use_begin();
5475   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5476     return false;
5477
5478   SDValue EltNo = N->getOperand(1);
5479   if (!isa<ConstantSDNode>(EltNo))
5480     return false;
5481
5482   // If the bit convert changed the number of elements, it is unsafe
5483   // to examine the mask.
5484   bool HasShuffleIntoBitcast = false;
5485   if (V.getOpcode() == ISD::BITCAST) {
5486     EVT SrcVT = V.getOperand(0).getValueType();
5487     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5488       return false;
5489     V = V.getOperand(0);
5490     HasShuffleIntoBitcast = true;
5491   }
5492
5493   // Select the input vector, guarding against out of range extract vector.
5494   unsigned NumElems = VT.getVectorNumElements();
5495   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5496   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5497   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5498
5499   // Skip one more bit_convert if necessary
5500   if (V.getOpcode() == ISD::BITCAST)
5501     V = V.getOperand(0);
5502
5503   if (ISD::isNormalLoad(V.getNode())) {
5504     // Is the original load suitable?
5505     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5506
5507     // FIXME: avoid the multi-use bug that is preventing lots of
5508     // of foldings to be detected, this is still wrong of course, but
5509     // give the temporary desired behavior, and if it happens that
5510     // the load has real more uses, during isel it will not fold, and
5511     // will generate poor code.
5512     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5513       return false;
5514
5515     if (!HasShuffleIntoBitcast)
5516       return true;
5517
5518     // If there's a bitcast before the shuffle, check if the load type and
5519     // alignment is valid.
5520     unsigned Align = LN0->getAlignment();
5521     unsigned NewAlign =
5522       TLI.getTargetData()->getABITypeAlignment(
5523                                     VT.getTypeForEVT(*DAG.getContext()));
5524
5525     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5526       return false;
5527   }
5528
5529   return true;
5530 }
5531
5532 static
5533 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5534   EVT VT = Op.getValueType();
5535
5536   // Canonizalize to v2f64.
5537   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5538   return DAG.getNode(ISD::BITCAST, dl, VT,
5539                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5540                                           V1, DAG));
5541 }
5542
5543 static
5544 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5545                         bool HasSSE2) {
5546   SDValue V1 = Op.getOperand(0);
5547   SDValue V2 = Op.getOperand(1);
5548   EVT VT = Op.getValueType();
5549
5550   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5551
5552   if (HasSSE2 && VT == MVT::v2f64)
5553     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5554
5555   // v4f32 or v4i32
5556   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5557 }
5558
5559 static
5560 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5561   SDValue V1 = Op.getOperand(0);
5562   SDValue V2 = Op.getOperand(1);
5563   EVT VT = Op.getValueType();
5564
5565   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5566          "unsupported shuffle type");
5567
5568   if (V2.getOpcode() == ISD::UNDEF)
5569     V2 = V1;
5570
5571   // v4i32 or v4f32
5572   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5573 }
5574
5575 static
5576 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5577   SDValue V1 = Op.getOperand(0);
5578   SDValue V2 = Op.getOperand(1);
5579   EVT VT = Op.getValueType();
5580   unsigned NumElems = VT.getVectorNumElements();
5581
5582   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5583   // operand of these instructions is only memory, so check if there's a
5584   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5585   // same masks.
5586   bool CanFoldLoad = false;
5587
5588   // Trivial case, when V2 comes from a load.
5589   if (MayFoldVectorLoad(V2))
5590     CanFoldLoad = true;
5591
5592   // When V1 is a load, it can be folded later into a store in isel, example:
5593   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5594   //    turns into:
5595   //  (MOVLPSmr addr:$src1, VR128:$src2)
5596   // So, recognize this potential and also use MOVLPS or MOVLPD
5597   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5598     CanFoldLoad = true;
5599
5600   // Both of them can't be memory operations though.
5601   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5602     CanFoldLoad = false;
5603
5604   if (CanFoldLoad) {
5605     if (HasSSE2 && NumElems == 2)
5606       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5607
5608     if (NumElems == 4)
5609       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5610   }
5611
5612   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5613   // movl and movlp will both match v2i64, but v2i64 is never matched by
5614   // movl earlier because we make it strict to avoid messing with the movlp load
5615   // folding logic (see the code above getMOVLP call). Match it here then,
5616   // this is horrible, but will stay like this until we move all shuffle
5617   // matching to x86 specific nodes. Note that for the 1st condition all
5618   // types are matched with movsd.
5619   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5620     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5621   else if (HasSSE2)
5622     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5623
5624
5625   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5626
5627   // Invert the operand order and use SHUFPS to match it.
5628   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5629                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5630 }
5631
5632 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5633   switch(VT.getSimpleVT().SimpleTy) {
5634   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5635   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5636   case MVT::v4f32:
5637     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5638   case MVT::v2f64:
5639     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5640   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5641   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5642   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5643   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5644   default:
5645     llvm_unreachable("Unknown type for unpckl");
5646   }
5647   return 0;
5648 }
5649
5650 static inline unsigned getUNPCKHOpcode(EVT VT) {
5651   switch(VT.getSimpleVT().SimpleTy) {
5652   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5653   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5654   case MVT::v4f32: return X86ISD::UNPCKHPS;
5655   case MVT::v2f64: return X86ISD::UNPCKHPD;
5656   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5657   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5658   default:
5659     llvm_unreachable("Unknown type for unpckh");
5660   }
5661   return 0;
5662 }
5663
5664 static
5665 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5666                                const TargetLowering &TLI,
5667                                const X86Subtarget *Subtarget) {
5668   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5669   EVT VT = Op.getValueType();
5670   DebugLoc dl = Op.getDebugLoc();
5671   SDValue V1 = Op.getOperand(0);
5672   SDValue V2 = Op.getOperand(1);
5673
5674   if (isZeroShuffle(SVOp))
5675     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5676
5677   // Handle splat operations
5678   if (SVOp->isSplat()) {
5679     // Special case, this is the only place now where it's
5680     // allowed to return a vector_shuffle operation without
5681     // using a target specific node, because *hopefully* it
5682     // will be optimized away by the dag combiner.
5683     if (VT.getVectorNumElements() <= 4 &&
5684         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5685       return Op;
5686
5687     // Handle splats by matching through known masks
5688     if (VT.getVectorNumElements() <= 4)
5689       return SDValue();
5690
5691     // Canonicalize all of the remaining to v4f32.
5692     return PromoteSplat(SVOp, DAG);
5693   }
5694
5695   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5696   // do it!
5697   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5698     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5699     if (NewOp.getNode())
5700       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5701   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5702     // FIXME: Figure out a cleaner way to do this.
5703     // Try to make use of movq to zero out the top part.
5704     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5705       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5706       if (NewOp.getNode()) {
5707         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5708           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5709                               DAG, Subtarget, dl);
5710       }
5711     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5712       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5713       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5714         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5715                             DAG, Subtarget, dl);
5716     }
5717   }
5718   return SDValue();
5719 }
5720
5721 SDValue
5722 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5723   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5724   SDValue V1 = Op.getOperand(0);
5725   SDValue V2 = Op.getOperand(1);
5726   EVT VT = Op.getValueType();
5727   DebugLoc dl = Op.getDebugLoc();
5728   unsigned NumElems = VT.getVectorNumElements();
5729   bool isMMX = VT.getSizeInBits() == 64;
5730   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5731   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5732   bool V1IsSplat = false;
5733   bool V2IsSplat = false;
5734   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5735   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5736   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5737   MachineFunction &MF = DAG.getMachineFunction();
5738   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5739
5740   // Shuffle operations on MMX not supported.
5741   if (isMMX)
5742     return Op;
5743
5744   // Vector shuffle lowering takes 3 steps:
5745   //
5746   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5747   //    narrowing and commutation of operands should be handled.
5748   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5749   //    shuffle nodes.
5750   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5751   //    so the shuffle can be broken into other shuffles and the legalizer can
5752   //    try the lowering again.
5753   //
5754   // The general ideia is that no vector_shuffle operation should be left to
5755   // be matched during isel, all of them must be converted to a target specific
5756   // node here.
5757
5758   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5759   // narrowing and commutation of operands should be handled. The actual code
5760   // doesn't include all of those, work in progress...
5761   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5762   if (NewOp.getNode())
5763     return NewOp;
5764
5765   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5766   // unpckh_undef). Only use pshufd if speed is more important than size.
5767   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5768     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5769       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5770   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5771     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5772       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5773
5774   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5775       RelaxedMayFoldVectorLoad(V1))
5776     return getMOVDDup(Op, dl, V1, DAG);
5777
5778   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5779     return getMOVHighToLow(Op, dl, DAG);
5780
5781   // Use to match splats
5782   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5783       (VT == MVT::v2f64 || VT == MVT::v2i64))
5784     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5785
5786   if (X86::isPSHUFDMask(SVOp)) {
5787     // The actual implementation will match the mask in the if above and then
5788     // during isel it can match several different instructions, not only pshufd
5789     // as its name says, sad but true, emulate the behavior for now...
5790     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5791         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5792
5793     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5794
5795     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5796       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5797
5798     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5799       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5800                                   TargetMask, DAG);
5801
5802     if (VT == MVT::v4f32)
5803       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5804                                   TargetMask, DAG);
5805   }
5806
5807   // Check if this can be converted into a logical shift.
5808   bool isLeft = false;
5809   unsigned ShAmt = 0;
5810   SDValue ShVal;
5811   bool isShift = getSubtarget()->hasSSE2() &&
5812     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5813   if (isShift && ShVal.hasOneUse()) {
5814     // If the shifted value has multiple uses, it may be cheaper to use
5815     // v_set0 + movlhps or movhlps, etc.
5816     EVT EltVT = VT.getVectorElementType();
5817     ShAmt *= EltVT.getSizeInBits();
5818     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5819   }
5820
5821   if (X86::isMOVLMask(SVOp)) {
5822     if (V1IsUndef)
5823       return V2;
5824     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5825       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5826     if (!X86::isMOVLPMask(SVOp)) {
5827       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5828         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5829
5830       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5831         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5832     }
5833   }
5834
5835   // FIXME: fold these into legal mask.
5836   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5837     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5838
5839   if (X86::isMOVHLPSMask(SVOp))
5840     return getMOVHighToLow(Op, dl, DAG);
5841
5842   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5843     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5844
5845   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5846     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5847
5848   if (X86::isMOVLPMask(SVOp))
5849     return getMOVLP(Op, dl, DAG, HasSSE2);
5850
5851   if (ShouldXformToMOVHLPS(SVOp) ||
5852       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5853     return CommuteVectorShuffle(SVOp, DAG);
5854
5855   if (isShift) {
5856     // No better options. Use a vshl / vsrl.
5857     EVT EltVT = VT.getVectorElementType();
5858     ShAmt *= EltVT.getSizeInBits();
5859     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5860   }
5861
5862   bool Commuted = false;
5863   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5864   // 1,1,1,1 -> v8i16 though.
5865   V1IsSplat = isSplatVector(V1.getNode());
5866   V2IsSplat = isSplatVector(V2.getNode());
5867
5868   // Canonicalize the splat or undef, if present, to be on the RHS.
5869   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5870     Op = CommuteVectorShuffle(SVOp, DAG);
5871     SVOp = cast<ShuffleVectorSDNode>(Op);
5872     V1 = SVOp->getOperand(0);
5873     V2 = SVOp->getOperand(1);
5874     std::swap(V1IsSplat, V2IsSplat);
5875     std::swap(V1IsUndef, V2IsUndef);
5876     Commuted = true;
5877   }
5878
5879   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5880     // Shuffling low element of v1 into undef, just return v1.
5881     if (V2IsUndef)
5882       return V1;
5883     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5884     // the instruction selector will not match, so get a canonical MOVL with
5885     // swapped operands to undo the commute.
5886     return getMOVL(DAG, dl, VT, V2, V1);
5887   }
5888
5889   if (X86::isUNPCKLMask(SVOp))
5890     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5891                                 dl, VT, V1, V2, DAG);
5892
5893   if (X86::isUNPCKHMask(SVOp))
5894     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5895
5896   if (V2IsSplat) {
5897     // Normalize mask so all entries that point to V2 points to its first
5898     // element then try to match unpck{h|l} again. If match, return a
5899     // new vector_shuffle with the corrected mask.
5900     SDValue NewMask = NormalizeMask(SVOp, DAG);
5901     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5902     if (NSVOp != SVOp) {
5903       if (X86::isUNPCKLMask(NSVOp, true)) {
5904         return NewMask;
5905       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5906         return NewMask;
5907       }
5908     }
5909   }
5910
5911   if (Commuted) {
5912     // Commute is back and try unpck* again.
5913     // FIXME: this seems wrong.
5914     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5915     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5916
5917     if (X86::isUNPCKLMask(NewSVOp))
5918       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5919                                   dl, VT, V2, V1, DAG);
5920
5921     if (X86::isUNPCKHMask(NewSVOp))
5922       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5923   }
5924
5925   // Normalize the node to match x86 shuffle ops if needed
5926   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5927     return CommuteVectorShuffle(SVOp, DAG);
5928
5929   // The checks below are all present in isShuffleMaskLegal, but they are
5930   // inlined here right now to enable us to directly emit target specific
5931   // nodes, and remove one by one until they don't return Op anymore.
5932   SmallVector<int, 16> M;
5933   SVOp->getMask(M);
5934
5935   if (isPALIGNRMask(M, VT, HasSSSE3))
5936     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5937                                 X86::getShufflePALIGNRImmediate(SVOp),
5938                                 DAG);
5939
5940   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5941       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5942     if (VT == MVT::v2f64) {
5943       X86ISD::NodeType Opcode =
5944         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5945       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5946     }
5947     if (VT == MVT::v2i64)
5948       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5949   }
5950
5951   if (isPSHUFHWMask(M, VT))
5952     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5953                                 X86::getShufflePSHUFHWImmediate(SVOp),
5954                                 DAG);
5955
5956   if (isPSHUFLWMask(M, VT))
5957     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5958                                 X86::getShufflePSHUFLWImmediate(SVOp),
5959                                 DAG);
5960
5961   if (isSHUFPMask(M, VT)) {
5962     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5963     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5964       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5965                                   TargetMask, DAG);
5966     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5967       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5968                                   TargetMask, DAG);
5969   }
5970
5971   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5972     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5973       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5974                                   dl, VT, V1, V1, DAG);
5975   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5976     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5977       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5978
5979   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5980   if (VT == MVT::v8i16) {
5981     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5982     if (NewOp.getNode())
5983       return NewOp;
5984   }
5985
5986   if (VT == MVT::v16i8) {
5987     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5988     if (NewOp.getNode())
5989       return NewOp;
5990   }
5991
5992   // Handle all 4 wide cases with a number of shuffles.
5993   if (NumElems == 4)
5994     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5995
5996   return SDValue();
5997 }
5998
5999 SDValue
6000 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6001                                                 SelectionDAG &DAG) const {
6002   EVT VT = Op.getValueType();
6003   DebugLoc dl = Op.getDebugLoc();
6004   if (VT.getSizeInBits() == 8) {
6005     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6006                                     Op.getOperand(0), Op.getOperand(1));
6007     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6008                                     DAG.getValueType(VT));
6009     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6010   } else if (VT.getSizeInBits() == 16) {
6011     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6012     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6013     if (Idx == 0)
6014       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6015                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6016                                      DAG.getNode(ISD::BITCAST, dl,
6017                                                  MVT::v4i32,
6018                                                  Op.getOperand(0)),
6019                                      Op.getOperand(1)));
6020     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6021                                     Op.getOperand(0), Op.getOperand(1));
6022     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6023                                     DAG.getValueType(VT));
6024     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6025   } else if (VT == MVT::f32) {
6026     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6027     // the result back to FR32 register. It's only worth matching if the
6028     // result has a single use which is a store or a bitcast to i32.  And in
6029     // the case of a store, it's not worth it if the index is a constant 0,
6030     // because a MOVSSmr can be used instead, which is smaller and faster.
6031     if (!Op.hasOneUse())
6032       return SDValue();
6033     SDNode *User = *Op.getNode()->use_begin();
6034     if ((User->getOpcode() != ISD::STORE ||
6035          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6036           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6037         (User->getOpcode() != ISD::BITCAST ||
6038          User->getValueType(0) != MVT::i32))
6039       return SDValue();
6040     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6041                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6042                                               Op.getOperand(0)),
6043                                               Op.getOperand(1));
6044     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6045   } else if (VT == MVT::i32) {
6046     // ExtractPS works with constant index.
6047     if (isa<ConstantSDNode>(Op.getOperand(1)))
6048       return Op;
6049   }
6050   return SDValue();
6051 }
6052
6053
6054 SDValue
6055 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6056                                            SelectionDAG &DAG) const {
6057   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6058     return SDValue();
6059
6060   SDValue Vec = Op.getOperand(0);
6061   EVT VecVT = Vec.getValueType();
6062
6063   // If this is a 256-bit vector result, first extract the 128-bit
6064   // vector and then extract from the 128-bit vector.
6065   if (VecVT.getSizeInBits() > 128) {
6066     DebugLoc dl = Op.getNode()->getDebugLoc();
6067     unsigned NumElems = VecVT.getVectorNumElements();
6068     SDValue Idx = Op.getOperand(1);
6069
6070     if (!isa<ConstantSDNode>(Idx))
6071       return SDValue();
6072
6073     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6074     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6075
6076     // Get the 128-bit vector.
6077     bool Upper = IdxVal >= ExtractNumElems;
6078     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6079
6080     // Extract from it.
6081     SDValue ScaledIdx = Idx;
6082     if (Upper)
6083       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6084                               DAG.getConstant(ExtractNumElems,
6085                                               Idx.getValueType()));
6086     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6087                        ScaledIdx);
6088   }
6089
6090   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6091
6092   if (Subtarget->hasSSE41()) {
6093     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6094     if (Res.getNode())
6095       return Res;
6096   }
6097
6098   EVT VT = Op.getValueType();
6099   DebugLoc dl = Op.getDebugLoc();
6100   // TODO: handle v16i8.
6101   if (VT.getSizeInBits() == 16) {
6102     SDValue Vec = Op.getOperand(0);
6103     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6104     if (Idx == 0)
6105       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6106                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6107                                      DAG.getNode(ISD::BITCAST, dl,
6108                                                  MVT::v4i32, Vec),
6109                                      Op.getOperand(1)));
6110     // Transform it so it match pextrw which produces a 32-bit result.
6111     EVT EltVT = MVT::i32;
6112     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6113                                     Op.getOperand(0), Op.getOperand(1));
6114     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6115                                     DAG.getValueType(VT));
6116     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6117   } else if (VT.getSizeInBits() == 32) {
6118     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6119     if (Idx == 0)
6120       return Op;
6121
6122     // SHUFPS the element to the lowest double word, then movss.
6123     int Mask[4] = { Idx, -1, -1, -1 };
6124     EVT VVT = Op.getOperand(0).getValueType();
6125     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6126                                        DAG.getUNDEF(VVT), Mask);
6127     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6128                        DAG.getIntPtrConstant(0));
6129   } else if (VT.getSizeInBits() == 64) {
6130     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6131     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6132     //        to match extract_elt for f64.
6133     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6134     if (Idx == 0)
6135       return Op;
6136
6137     // UNPCKHPD the element to the lowest double word, then movsd.
6138     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6139     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6140     int Mask[2] = { 1, -1 };
6141     EVT VVT = Op.getOperand(0).getValueType();
6142     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6143                                        DAG.getUNDEF(VVT), Mask);
6144     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6145                        DAG.getIntPtrConstant(0));
6146   }
6147
6148   return SDValue();
6149 }
6150
6151 SDValue
6152 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6153                                                SelectionDAG &DAG) const {
6154   EVT VT = Op.getValueType();
6155   EVT EltVT = VT.getVectorElementType();
6156   DebugLoc dl = Op.getDebugLoc();
6157
6158   SDValue N0 = Op.getOperand(0);
6159   SDValue N1 = Op.getOperand(1);
6160   SDValue N2 = Op.getOperand(2);
6161
6162   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6163       isa<ConstantSDNode>(N2)) {
6164     unsigned Opc;
6165     if (VT == MVT::v8i16)
6166       Opc = X86ISD::PINSRW;
6167     else if (VT == MVT::v16i8)
6168       Opc = X86ISD::PINSRB;
6169     else
6170       Opc = X86ISD::PINSRB;
6171
6172     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6173     // argument.
6174     if (N1.getValueType() != MVT::i32)
6175       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6176     if (N2.getValueType() != MVT::i32)
6177       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6178     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6179   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6180     // Bits [7:6] of the constant are the source select.  This will always be
6181     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6182     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6183     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6184     // Bits [5:4] of the constant are the destination select.  This is the
6185     //  value of the incoming immediate.
6186     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6187     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6188     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6189     // Create this as a scalar to vector..
6190     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6191     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6192   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6193     // PINSR* works with constant index.
6194     return Op;
6195   }
6196   return SDValue();
6197 }
6198
6199 SDValue
6200 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6201   EVT VT = Op.getValueType();
6202   EVT EltVT = VT.getVectorElementType();
6203
6204   DebugLoc dl = Op.getDebugLoc();
6205   SDValue N0 = Op.getOperand(0);
6206   SDValue N1 = Op.getOperand(1);
6207   SDValue N2 = Op.getOperand(2);
6208
6209   // If this is a 256-bit vector result, first insert into a 128-bit
6210   // vector and then insert into the 256-bit vector.
6211   if (VT.getSizeInBits() > 128) {
6212     if (!isa<ConstantSDNode>(N2))
6213       return SDValue();
6214
6215     // Get the 128-bit vector.
6216     unsigned NumElems = VT.getVectorNumElements();
6217     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6218     bool Upper = IdxVal >= NumElems / 2;
6219
6220     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6221
6222     // Insert into it.
6223     SDValue ScaledN2 = N2;
6224     if (Upper)
6225       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6226                              DAG.getConstant(NumElems /
6227                                              (VT.getSizeInBits() / 128),
6228                                              N2.getValueType()));
6229     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6230                      N1, ScaledN2);
6231
6232     // Insert the 128-bit vector
6233     // FIXME: Why UNDEF?
6234     return Insert128BitVector(N0, Op, N2, DAG, dl);
6235   }
6236
6237   if (Subtarget->hasSSE41())
6238     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6239
6240   if (EltVT == MVT::i8)
6241     return SDValue();
6242
6243   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6244     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6245     // as its second argument.
6246     if (N1.getValueType() != MVT::i32)
6247       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6248     if (N2.getValueType() != MVT::i32)
6249       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6250     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6251   }
6252   return SDValue();
6253 }
6254
6255 SDValue
6256 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6257   LLVMContext *Context = DAG.getContext();
6258   DebugLoc dl = Op.getDebugLoc();
6259   EVT OpVT = Op.getValueType();
6260
6261   // If this is a 256-bit vector result, first insert into a 128-bit
6262   // vector and then insert into the 256-bit vector.
6263   if (OpVT.getSizeInBits() > 128) {
6264     // Insert into a 128-bit vector.
6265     EVT VT128 = EVT::getVectorVT(*Context,
6266                                  OpVT.getVectorElementType(),
6267                                  OpVT.getVectorNumElements() / 2);
6268
6269     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6270
6271     // Insert the 128-bit vector.
6272     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6273                               DAG.getConstant(0, MVT::i32),
6274                               DAG, dl);
6275   }
6276
6277   if (Op.getValueType() == MVT::v1i64 &&
6278       Op.getOperand(0).getValueType() == MVT::i64)
6279     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6280
6281   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6282   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6283          "Expected an SSE type!");
6284   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6285                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6286 }
6287
6288 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6289 // a simple subregister reference or explicit instructions to grab
6290 // upper bits of a vector.
6291 SDValue
6292 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6293   if (Subtarget->hasAVX()) {
6294     DebugLoc dl = Op.getNode()->getDebugLoc();
6295     SDValue Vec = Op.getNode()->getOperand(0);
6296     SDValue Idx = Op.getNode()->getOperand(1);
6297
6298     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6299         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6300         return Extract128BitVector(Vec, Idx, DAG, dl);
6301     }
6302   }
6303   return SDValue();
6304 }
6305
6306 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6307 // simple superregister reference or explicit instructions to insert
6308 // the upper bits of a vector.
6309 SDValue
6310 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6311   if (Subtarget->hasAVX()) {
6312     DebugLoc dl = Op.getNode()->getDebugLoc();
6313     SDValue Vec = Op.getNode()->getOperand(0);
6314     SDValue SubVec = Op.getNode()->getOperand(1);
6315     SDValue Idx = Op.getNode()->getOperand(2);
6316
6317     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6318         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6319       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6320     }
6321   }
6322   return SDValue();
6323 }
6324
6325 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6326 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6327 // one of the above mentioned nodes. It has to be wrapped because otherwise
6328 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6329 // be used to form addressing mode. These wrapped nodes will be selected
6330 // into MOV32ri.
6331 SDValue
6332 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6333   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6334
6335   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6336   // global base reg.
6337   unsigned char OpFlag = 0;
6338   unsigned WrapperKind = X86ISD::Wrapper;
6339   CodeModel::Model M = getTargetMachine().getCodeModel();
6340
6341   if (Subtarget->isPICStyleRIPRel() &&
6342       (M == CodeModel::Small || M == CodeModel::Kernel))
6343     WrapperKind = X86ISD::WrapperRIP;
6344   else if (Subtarget->isPICStyleGOT())
6345     OpFlag = X86II::MO_GOTOFF;
6346   else if (Subtarget->isPICStyleStubPIC())
6347     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6348
6349   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6350                                              CP->getAlignment(),
6351                                              CP->getOffset(), OpFlag);
6352   DebugLoc DL = CP->getDebugLoc();
6353   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6354   // With PIC, the address is actually $g + Offset.
6355   if (OpFlag) {
6356     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6357                          DAG.getNode(X86ISD::GlobalBaseReg,
6358                                      DebugLoc(), getPointerTy()),
6359                          Result);
6360   }
6361
6362   return Result;
6363 }
6364
6365 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6366   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6367
6368   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6369   // global base reg.
6370   unsigned char OpFlag = 0;
6371   unsigned WrapperKind = X86ISD::Wrapper;
6372   CodeModel::Model M = getTargetMachine().getCodeModel();
6373
6374   if (Subtarget->isPICStyleRIPRel() &&
6375       (M == CodeModel::Small || M == CodeModel::Kernel))
6376     WrapperKind = X86ISD::WrapperRIP;
6377   else if (Subtarget->isPICStyleGOT())
6378     OpFlag = X86II::MO_GOTOFF;
6379   else if (Subtarget->isPICStyleStubPIC())
6380     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6381
6382   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6383                                           OpFlag);
6384   DebugLoc DL = JT->getDebugLoc();
6385   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6386
6387   // With PIC, the address is actually $g + Offset.
6388   if (OpFlag)
6389     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6390                          DAG.getNode(X86ISD::GlobalBaseReg,
6391                                      DebugLoc(), getPointerTy()),
6392                          Result);
6393
6394   return Result;
6395 }
6396
6397 SDValue
6398 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6399   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6400
6401   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6402   // global base reg.
6403   unsigned char OpFlag = 0;
6404   unsigned WrapperKind = X86ISD::Wrapper;
6405   CodeModel::Model M = getTargetMachine().getCodeModel();
6406
6407   if (Subtarget->isPICStyleRIPRel() &&
6408       (M == CodeModel::Small || M == CodeModel::Kernel))
6409     WrapperKind = X86ISD::WrapperRIP;
6410   else if (Subtarget->isPICStyleGOT())
6411     OpFlag = X86II::MO_GOTOFF;
6412   else if (Subtarget->isPICStyleStubPIC())
6413     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6414
6415   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6416
6417   DebugLoc DL = Op.getDebugLoc();
6418   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6419
6420
6421   // With PIC, the address is actually $g + Offset.
6422   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6423       !Subtarget->is64Bit()) {
6424     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6425                          DAG.getNode(X86ISD::GlobalBaseReg,
6426                                      DebugLoc(), getPointerTy()),
6427                          Result);
6428   }
6429
6430   return Result;
6431 }
6432
6433 SDValue
6434 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6435   // Create the TargetBlockAddressAddress node.
6436   unsigned char OpFlags =
6437     Subtarget->ClassifyBlockAddressReference();
6438   CodeModel::Model M = getTargetMachine().getCodeModel();
6439   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6440   DebugLoc dl = Op.getDebugLoc();
6441   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6442                                        /*isTarget=*/true, OpFlags);
6443
6444   if (Subtarget->isPICStyleRIPRel() &&
6445       (M == CodeModel::Small || M == CodeModel::Kernel))
6446     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6447   else
6448     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6449
6450   // With PIC, the address is actually $g + Offset.
6451   if (isGlobalRelativeToPICBase(OpFlags)) {
6452     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6453                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6454                          Result);
6455   }
6456
6457   return Result;
6458 }
6459
6460 SDValue
6461 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6462                                       int64_t Offset,
6463                                       SelectionDAG &DAG) const {
6464   // Create the TargetGlobalAddress node, folding in the constant
6465   // offset if it is legal.
6466   unsigned char OpFlags =
6467     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6468   CodeModel::Model M = getTargetMachine().getCodeModel();
6469   SDValue Result;
6470   if (OpFlags == X86II::MO_NO_FLAG &&
6471       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6472     // A direct static reference to a global.
6473     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6474     Offset = 0;
6475   } else {
6476     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6477   }
6478
6479   if (Subtarget->isPICStyleRIPRel() &&
6480       (M == CodeModel::Small || M == CodeModel::Kernel))
6481     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6482   else
6483     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6484
6485   // With PIC, the address is actually $g + Offset.
6486   if (isGlobalRelativeToPICBase(OpFlags)) {
6487     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6488                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6489                          Result);
6490   }
6491
6492   // For globals that require a load from a stub to get the address, emit the
6493   // load.
6494   if (isGlobalStubReference(OpFlags))
6495     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6496                          MachinePointerInfo::getGOT(), false, false, 0);
6497
6498   // If there was a non-zero offset that we didn't fold, create an explicit
6499   // addition for it.
6500   if (Offset != 0)
6501     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6502                          DAG.getConstant(Offset, getPointerTy()));
6503
6504   return Result;
6505 }
6506
6507 SDValue
6508 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6509   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6510   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6511   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6512 }
6513
6514 static SDValue
6515 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6516            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6517            unsigned char OperandFlags) {
6518   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6519   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6520   DebugLoc dl = GA->getDebugLoc();
6521   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6522                                            GA->getValueType(0),
6523                                            GA->getOffset(),
6524                                            OperandFlags);
6525   if (InFlag) {
6526     SDValue Ops[] = { Chain,  TGA, *InFlag };
6527     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6528   } else {
6529     SDValue Ops[]  = { Chain, TGA };
6530     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6531   }
6532
6533   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6534   MFI->setAdjustsStack(true);
6535
6536   SDValue Flag = Chain.getValue(1);
6537   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6538 }
6539
6540 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6541 static SDValue
6542 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6543                                 const EVT PtrVT) {
6544   SDValue InFlag;
6545   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6546   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6547                                      DAG.getNode(X86ISD::GlobalBaseReg,
6548                                                  DebugLoc(), PtrVT), InFlag);
6549   InFlag = Chain.getValue(1);
6550
6551   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6552 }
6553
6554 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6555 static SDValue
6556 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6557                                 const EVT PtrVT) {
6558   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6559                     X86::RAX, X86II::MO_TLSGD);
6560 }
6561
6562 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6563 // "local exec" model.
6564 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6565                                    const EVT PtrVT, TLSModel::Model model,
6566                                    bool is64Bit) {
6567   DebugLoc dl = GA->getDebugLoc();
6568
6569   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6570   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6571                                                          is64Bit ? 257 : 256));
6572
6573   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6574                                       DAG.getIntPtrConstant(0),
6575                                       MachinePointerInfo(Ptr), false, false, 0);
6576
6577   unsigned char OperandFlags = 0;
6578   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6579   // initialexec.
6580   unsigned WrapperKind = X86ISD::Wrapper;
6581   if (model == TLSModel::LocalExec) {
6582     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6583   } else if (is64Bit) {
6584     assert(model == TLSModel::InitialExec);
6585     OperandFlags = X86II::MO_GOTTPOFF;
6586     WrapperKind = X86ISD::WrapperRIP;
6587   } else {
6588     assert(model == TLSModel::InitialExec);
6589     OperandFlags = X86II::MO_INDNTPOFF;
6590   }
6591
6592   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6593   // exec)
6594   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6595                                            GA->getValueType(0),
6596                                            GA->getOffset(), OperandFlags);
6597   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6598
6599   if (model == TLSModel::InitialExec)
6600     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6601                          MachinePointerInfo::getGOT(), false, false, 0);
6602
6603   // The address of the thread local variable is the add of the thread
6604   // pointer with the offset of the variable.
6605   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6606 }
6607
6608 SDValue
6609 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6610
6611   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6612   const GlobalValue *GV = GA->getGlobal();
6613
6614   if (Subtarget->isTargetELF()) {
6615     // TODO: implement the "local dynamic" model
6616     // TODO: implement the "initial exec"model for pic executables
6617
6618     // If GV is an alias then use the aliasee for determining
6619     // thread-localness.
6620     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6621       GV = GA->resolveAliasedGlobal(false);
6622
6623     TLSModel::Model model
6624       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6625
6626     switch (model) {
6627       case TLSModel::GeneralDynamic:
6628       case TLSModel::LocalDynamic: // not implemented
6629         if (Subtarget->is64Bit())
6630           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6631         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6632
6633       case TLSModel::InitialExec:
6634       case TLSModel::LocalExec:
6635         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6636                                    Subtarget->is64Bit());
6637     }
6638   } else if (Subtarget->isTargetDarwin()) {
6639     // Darwin only has one model of TLS.  Lower to that.
6640     unsigned char OpFlag = 0;
6641     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6642                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6643
6644     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6645     // global base reg.
6646     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6647                   !Subtarget->is64Bit();
6648     if (PIC32)
6649       OpFlag = X86II::MO_TLVP_PIC_BASE;
6650     else
6651       OpFlag = X86II::MO_TLVP;
6652     DebugLoc DL = Op.getDebugLoc();
6653     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6654                                                 GA->getValueType(0),
6655                                                 GA->getOffset(), OpFlag);
6656     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6657
6658     // With PIC32, the address is actually $g + Offset.
6659     if (PIC32)
6660       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6661                            DAG.getNode(X86ISD::GlobalBaseReg,
6662                                        DebugLoc(), getPointerTy()),
6663                            Offset);
6664
6665     // Lowering the machine isd will make sure everything is in the right
6666     // location.
6667     SDValue Chain = DAG.getEntryNode();
6668     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6669     SDValue Args[] = { Chain, Offset };
6670     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6671
6672     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6673     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6674     MFI->setAdjustsStack(true);
6675
6676     // And our return value (tls address) is in the standard call return value
6677     // location.
6678     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6679     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6680   }
6681
6682   assert(false &&
6683          "TLS not implemented for this target.");
6684
6685   llvm_unreachable("Unreachable");
6686   return SDValue();
6687 }
6688
6689
6690 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6691 /// take a 2 x i32 value to shift plus a shift amount.
6692 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6693   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6694   EVT VT = Op.getValueType();
6695   unsigned VTBits = VT.getSizeInBits();
6696   DebugLoc dl = Op.getDebugLoc();
6697   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6698   SDValue ShOpLo = Op.getOperand(0);
6699   SDValue ShOpHi = Op.getOperand(1);
6700   SDValue ShAmt  = Op.getOperand(2);
6701   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6702                                      DAG.getConstant(VTBits - 1, MVT::i8))
6703                        : DAG.getConstant(0, VT);
6704
6705   SDValue Tmp2, Tmp3;
6706   if (Op.getOpcode() == ISD::SHL_PARTS) {
6707     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6708     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6709   } else {
6710     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6711     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6712   }
6713
6714   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6715                                 DAG.getConstant(VTBits, MVT::i8));
6716   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6717                              AndNode, DAG.getConstant(0, MVT::i8));
6718
6719   SDValue Hi, Lo;
6720   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6721   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6722   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6723
6724   if (Op.getOpcode() == ISD::SHL_PARTS) {
6725     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6726     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6727   } else {
6728     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6729     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6730   }
6731
6732   SDValue Ops[2] = { Lo, Hi };
6733   return DAG.getMergeValues(Ops, 2, dl);
6734 }
6735
6736 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6737                                            SelectionDAG &DAG) const {
6738   EVT SrcVT = Op.getOperand(0).getValueType();
6739
6740   if (SrcVT.isVector())
6741     return SDValue();
6742
6743   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6744          "Unknown SINT_TO_FP to lower!");
6745
6746   // These are really Legal; return the operand so the caller accepts it as
6747   // Legal.
6748   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6749     return Op;
6750   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6751       Subtarget->is64Bit()) {
6752     return Op;
6753   }
6754
6755   DebugLoc dl = Op.getDebugLoc();
6756   unsigned Size = SrcVT.getSizeInBits()/8;
6757   MachineFunction &MF = DAG.getMachineFunction();
6758   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6759   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6760   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6761                                StackSlot,
6762                                MachinePointerInfo::getFixedStack(SSFI),
6763                                false, false, 0);
6764   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6765 }
6766
6767 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6768                                      SDValue StackSlot,
6769                                      SelectionDAG &DAG) const {
6770   // Build the FILD
6771   DebugLoc DL = Op.getDebugLoc();
6772   SDVTList Tys;
6773   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6774   if (useSSE)
6775     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6776   else
6777     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6778
6779   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6780
6781   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6782   MachineMemOperand *MMO;
6783   if (FI) {
6784     int SSFI = FI->getIndex();
6785     MMO =
6786       DAG.getMachineFunction()
6787       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6788                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6789   } else {
6790     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6791     StackSlot = StackSlot.getOperand(1);
6792   }
6793   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6794   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6795                                            X86ISD::FILD, DL,
6796                                            Tys, Ops, array_lengthof(Ops),
6797                                            SrcVT, MMO);
6798
6799   if (useSSE) {
6800     Chain = Result.getValue(1);
6801     SDValue InFlag = Result.getValue(2);
6802
6803     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6804     // shouldn't be necessary except that RFP cannot be live across
6805     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6806     MachineFunction &MF = DAG.getMachineFunction();
6807     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6808     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6809     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6810     Tys = DAG.getVTList(MVT::Other);
6811     SDValue Ops[] = {
6812       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6813     };
6814     MachineMemOperand *MMO =
6815       DAG.getMachineFunction()
6816       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6817                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6818
6819     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6820                                     Ops, array_lengthof(Ops),
6821                                     Op.getValueType(), MMO);
6822     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6823                          MachinePointerInfo::getFixedStack(SSFI),
6824                          false, false, 0);
6825   }
6826
6827   return Result;
6828 }
6829
6830 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6831 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6832                                                SelectionDAG &DAG) const {
6833   // This algorithm is not obvious. Here it is in C code, more or less:
6834   /*
6835     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6836       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6837       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6838
6839       // Copy ints to xmm registers.
6840       __m128i xh = _mm_cvtsi32_si128( hi );
6841       __m128i xl = _mm_cvtsi32_si128( lo );
6842
6843       // Combine into low half of a single xmm register.
6844       __m128i x = _mm_unpacklo_epi32( xh, xl );
6845       __m128d d;
6846       double sd;
6847
6848       // Merge in appropriate exponents to give the integer bits the right
6849       // magnitude.
6850       x = _mm_unpacklo_epi32( x, exp );
6851
6852       // Subtract away the biases to deal with the IEEE-754 double precision
6853       // implicit 1.
6854       d = _mm_sub_pd( (__m128d) x, bias );
6855
6856       // All conversions up to here are exact. The correctly rounded result is
6857       // calculated using the current rounding mode using the following
6858       // horizontal add.
6859       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6860       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6861                                 // store doesn't really need to be here (except
6862                                 // maybe to zero the other double)
6863       return sd;
6864     }
6865   */
6866
6867   DebugLoc dl = Op.getDebugLoc();
6868   LLVMContext *Context = DAG.getContext();
6869
6870   // Build some magic constants.
6871   std::vector<Constant*> CV0;
6872   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6873   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6874   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6875   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6876   Constant *C0 = ConstantVector::get(CV0);
6877   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6878
6879   std::vector<Constant*> CV1;
6880   CV1.push_back(
6881     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6882   CV1.push_back(
6883     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6884   Constant *C1 = ConstantVector::get(CV1);
6885   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6886
6887   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6888                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6889                                         Op.getOperand(0),
6890                                         DAG.getIntPtrConstant(1)));
6891   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6892                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6893                                         Op.getOperand(0),
6894                                         DAG.getIntPtrConstant(0)));
6895   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6896   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6897                               MachinePointerInfo::getConstantPool(),
6898                               false, false, 16);
6899   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6900   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6901   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6902                               MachinePointerInfo::getConstantPool(),
6903                               false, false, 16);
6904   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6905
6906   // Add the halves; easiest way is to swap them into another reg first.
6907   int ShufMask[2] = { 1, -1 };
6908   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6909                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6910   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6911   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6912                      DAG.getIntPtrConstant(0));
6913 }
6914
6915 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6916 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6917                                                SelectionDAG &DAG) const {
6918   DebugLoc dl = Op.getDebugLoc();
6919   // FP constant to bias correct the final result.
6920   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6921                                    MVT::f64);
6922
6923   // Load the 32-bit value into an XMM register.
6924   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6925                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6926                                          Op.getOperand(0),
6927                                          DAG.getIntPtrConstant(0)));
6928
6929   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6930                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6931                      DAG.getIntPtrConstant(0));
6932
6933   // Or the load with the bias.
6934   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6935                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6936                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6937                                                    MVT::v2f64, Load)),
6938                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6939                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6940                                                    MVT::v2f64, Bias)));
6941   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6942                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6943                    DAG.getIntPtrConstant(0));
6944
6945   // Subtract the bias.
6946   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6947
6948   // Handle final rounding.
6949   EVT DestVT = Op.getValueType();
6950
6951   if (DestVT.bitsLT(MVT::f64)) {
6952     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6953                        DAG.getIntPtrConstant(0));
6954   } else if (DestVT.bitsGT(MVT::f64)) {
6955     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6956   }
6957
6958   // Handle final rounding.
6959   return Sub;
6960 }
6961
6962 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6963                                            SelectionDAG &DAG) const {
6964   SDValue N0 = Op.getOperand(0);
6965   DebugLoc dl = Op.getDebugLoc();
6966
6967   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6968   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6969   // the optimization here.
6970   if (DAG.SignBitIsZero(N0))
6971     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6972
6973   EVT SrcVT = N0.getValueType();
6974   EVT DstVT = Op.getValueType();
6975   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6976     return LowerUINT_TO_FP_i64(Op, DAG);
6977   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6978     return LowerUINT_TO_FP_i32(Op, DAG);
6979
6980   // Make a 64-bit buffer, and use it to build an FILD.
6981   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6982   if (SrcVT == MVT::i32) {
6983     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6984     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6985                                      getPointerTy(), StackSlot, WordOff);
6986     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6987                                   StackSlot, MachinePointerInfo(),
6988                                   false, false, 0);
6989     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6990                                   OffsetSlot, MachinePointerInfo(),
6991                                   false, false, 0);
6992     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6993     return Fild;
6994   }
6995
6996   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6997   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6998                                 StackSlot, MachinePointerInfo(),
6999                                false, false, 0);
7000   // For i64 source, we need to add the appropriate power of 2 if the input
7001   // was negative.  This is the same as the optimization in
7002   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7003   // we must be careful to do the computation in x87 extended precision, not
7004   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7005   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7006   MachineMemOperand *MMO =
7007     DAG.getMachineFunction()
7008     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7009                           MachineMemOperand::MOLoad, 8, 8);
7010
7011   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7012   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7013   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7014                                          MVT::i64, MMO);
7015
7016   APInt FF(32, 0x5F800000ULL);
7017
7018   // Check whether the sign bit is set.
7019   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7020                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7021                                  ISD::SETLT);
7022
7023   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7024   SDValue FudgePtr = DAG.getConstantPool(
7025                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7026                                          getPointerTy());
7027
7028   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7029   SDValue Zero = DAG.getIntPtrConstant(0);
7030   SDValue Four = DAG.getIntPtrConstant(4);
7031   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7032                                Zero, Four);
7033   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7034
7035   // Load the value out, extending it from f32 to f80.
7036   // FIXME: Avoid the extend by constructing the right constant pool?
7037   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7038                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7039                                  MVT::f32, false, false, 4);
7040   // Extend everything to 80 bits to force it to be done on x87.
7041   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7042   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7043 }
7044
7045 std::pair<SDValue,SDValue> X86TargetLowering::
7046 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7047   DebugLoc DL = Op.getDebugLoc();
7048
7049   EVT DstTy = Op.getValueType();
7050
7051   if (!IsSigned) {
7052     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7053     DstTy = MVT::i64;
7054   }
7055
7056   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7057          DstTy.getSimpleVT() >= MVT::i16 &&
7058          "Unknown FP_TO_SINT to lower!");
7059
7060   // These are really Legal.
7061   if (DstTy == MVT::i32 &&
7062       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7063     return std::make_pair(SDValue(), SDValue());
7064   if (Subtarget->is64Bit() &&
7065       DstTy == MVT::i64 &&
7066       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7067     return std::make_pair(SDValue(), SDValue());
7068
7069   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7070   // stack slot.
7071   MachineFunction &MF = DAG.getMachineFunction();
7072   unsigned MemSize = DstTy.getSizeInBits()/8;
7073   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7074   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7075
7076
7077
7078   unsigned Opc;
7079   switch (DstTy.getSimpleVT().SimpleTy) {
7080   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7081   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7082   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7083   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7084   }
7085
7086   SDValue Chain = DAG.getEntryNode();
7087   SDValue Value = Op.getOperand(0);
7088   EVT TheVT = Op.getOperand(0).getValueType();
7089   if (isScalarFPTypeInSSEReg(TheVT)) {
7090     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7091     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7092                          MachinePointerInfo::getFixedStack(SSFI),
7093                          false, false, 0);
7094     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7095     SDValue Ops[] = {
7096       Chain, StackSlot, DAG.getValueType(TheVT)
7097     };
7098
7099     MachineMemOperand *MMO =
7100       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7101                               MachineMemOperand::MOLoad, MemSize, MemSize);
7102     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7103                                     DstTy, MMO);
7104     Chain = Value.getValue(1);
7105     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7106     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7107   }
7108
7109   MachineMemOperand *MMO =
7110     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7111                             MachineMemOperand::MOStore, MemSize, MemSize);
7112
7113   // Build the FP_TO_INT*_IN_MEM
7114   SDValue Ops[] = { Chain, Value, StackSlot };
7115   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7116                                          Ops, 3, DstTy, MMO);
7117
7118   return std::make_pair(FIST, StackSlot);
7119 }
7120
7121 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7122                                            SelectionDAG &DAG) const {
7123   if (Op.getValueType().isVector())
7124     return SDValue();
7125
7126   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7127   SDValue FIST = Vals.first, StackSlot = Vals.second;
7128   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7129   if (FIST.getNode() == 0) return Op;
7130
7131   // Load the result.
7132   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7133                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7134 }
7135
7136 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7137                                            SelectionDAG &DAG) const {
7138   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7139   SDValue FIST = Vals.first, StackSlot = Vals.second;
7140   assert(FIST.getNode() && "Unexpected failure");
7141
7142   // Load the result.
7143   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7144                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7145 }
7146
7147 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7148                                      SelectionDAG &DAG) const {
7149   LLVMContext *Context = DAG.getContext();
7150   DebugLoc dl = Op.getDebugLoc();
7151   EVT VT = Op.getValueType();
7152   EVT EltVT = VT;
7153   if (VT.isVector())
7154     EltVT = VT.getVectorElementType();
7155   std::vector<Constant*> CV;
7156   if (EltVT == MVT::f64) {
7157     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7158     CV.push_back(C);
7159     CV.push_back(C);
7160   } else {
7161     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7162     CV.push_back(C);
7163     CV.push_back(C);
7164     CV.push_back(C);
7165     CV.push_back(C);
7166   }
7167   Constant *C = ConstantVector::get(CV);
7168   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7169   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7170                              MachinePointerInfo::getConstantPool(),
7171                              false, false, 16);
7172   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7173 }
7174
7175 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7176   LLVMContext *Context = DAG.getContext();
7177   DebugLoc dl = Op.getDebugLoc();
7178   EVT VT = Op.getValueType();
7179   EVT EltVT = VT;
7180   if (VT.isVector())
7181     EltVT = VT.getVectorElementType();
7182   std::vector<Constant*> CV;
7183   if (EltVT == MVT::f64) {
7184     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7185     CV.push_back(C);
7186     CV.push_back(C);
7187   } else {
7188     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7189     CV.push_back(C);
7190     CV.push_back(C);
7191     CV.push_back(C);
7192     CV.push_back(C);
7193   }
7194   Constant *C = ConstantVector::get(CV);
7195   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7196   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7197                              MachinePointerInfo::getConstantPool(),
7198                              false, false, 16);
7199   if (VT.isVector()) {
7200     return DAG.getNode(ISD::BITCAST, dl, VT,
7201                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7202                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7203                                 Op.getOperand(0)),
7204                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7205   } else {
7206     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7207   }
7208 }
7209
7210 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7211   LLVMContext *Context = DAG.getContext();
7212   SDValue Op0 = Op.getOperand(0);
7213   SDValue Op1 = Op.getOperand(1);
7214   DebugLoc dl = Op.getDebugLoc();
7215   EVT VT = Op.getValueType();
7216   EVT SrcVT = Op1.getValueType();
7217
7218   // If second operand is smaller, extend it first.
7219   if (SrcVT.bitsLT(VT)) {
7220     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7221     SrcVT = VT;
7222   }
7223   // And if it is bigger, shrink it first.
7224   if (SrcVT.bitsGT(VT)) {
7225     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7226     SrcVT = VT;
7227   }
7228
7229   // At this point the operands and the result should have the same
7230   // type, and that won't be f80 since that is not custom lowered.
7231
7232   // First get the sign bit of second operand.
7233   std::vector<Constant*> CV;
7234   if (SrcVT == MVT::f64) {
7235     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7236     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7237   } else {
7238     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7239     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7240     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7241     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7242   }
7243   Constant *C = ConstantVector::get(CV);
7244   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7245   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7246                               MachinePointerInfo::getConstantPool(),
7247                               false, false, 16);
7248   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7249
7250   // Shift sign bit right or left if the two operands have different types.
7251   if (SrcVT.bitsGT(VT)) {
7252     // Op0 is MVT::f32, Op1 is MVT::f64.
7253     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7254     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7255                           DAG.getConstant(32, MVT::i32));
7256     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7257     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7258                           DAG.getIntPtrConstant(0));
7259   }
7260
7261   // Clear first operand sign bit.
7262   CV.clear();
7263   if (VT == MVT::f64) {
7264     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7265     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7266   } else {
7267     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7268     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7269     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7270     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7271   }
7272   C = ConstantVector::get(CV);
7273   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7274   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7275                               MachinePointerInfo::getConstantPool(),
7276                               false, false, 16);
7277   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7278
7279   // Or the value with the sign bit.
7280   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7281 }
7282
7283 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7284   SDValue N0 = Op.getOperand(0);
7285   DebugLoc dl = Op.getDebugLoc();
7286   EVT VT = Op.getValueType();
7287
7288   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7289   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7290                                   DAG.getConstant(1, VT));
7291   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7292 }
7293
7294 /// Emit nodes that will be selected as "test Op0,Op0", or something
7295 /// equivalent.
7296 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7297                                     SelectionDAG &DAG) const {
7298   DebugLoc dl = Op.getDebugLoc();
7299
7300   // CF and OF aren't always set the way we want. Determine which
7301   // of these we need.
7302   bool NeedCF = false;
7303   bool NeedOF = false;
7304   switch (X86CC) {
7305   default: break;
7306   case X86::COND_A: case X86::COND_AE:
7307   case X86::COND_B: case X86::COND_BE:
7308     NeedCF = true;
7309     break;
7310   case X86::COND_G: case X86::COND_GE:
7311   case X86::COND_L: case X86::COND_LE:
7312   case X86::COND_O: case X86::COND_NO:
7313     NeedOF = true;
7314     break;
7315   }
7316
7317   // See if we can use the EFLAGS value from the operand instead of
7318   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7319   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7320   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7321     // Emit a CMP with 0, which is the TEST pattern.
7322     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7323                        DAG.getConstant(0, Op.getValueType()));
7324
7325   unsigned Opcode = 0;
7326   unsigned NumOperands = 0;
7327   switch (Op.getNode()->getOpcode()) {
7328   case ISD::ADD:
7329     // Due to an isel shortcoming, be conservative if this add is likely to be
7330     // selected as part of a load-modify-store instruction. When the root node
7331     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7332     // uses of other nodes in the match, such as the ADD in this case. This
7333     // leads to the ADD being left around and reselected, with the result being
7334     // two adds in the output.  Alas, even if none our users are stores, that
7335     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7336     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7337     // climbing the DAG back to the root, and it doesn't seem to be worth the
7338     // effort.
7339     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7340            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7341       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7342         goto default_case;
7343
7344     if (ConstantSDNode *C =
7345         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7346       // An add of one will be selected as an INC.
7347       if (C->getAPIntValue() == 1) {
7348         Opcode = X86ISD::INC;
7349         NumOperands = 1;
7350         break;
7351       }
7352
7353       // An add of negative one (subtract of one) will be selected as a DEC.
7354       if (C->getAPIntValue().isAllOnesValue()) {
7355         Opcode = X86ISD::DEC;
7356         NumOperands = 1;
7357         break;
7358       }
7359     }
7360
7361     // Otherwise use a regular EFLAGS-setting add.
7362     Opcode = X86ISD::ADD;
7363     NumOperands = 2;
7364     break;
7365   case ISD::AND: {
7366     // If the primary and result isn't used, don't bother using X86ISD::AND,
7367     // because a TEST instruction will be better.
7368     bool NonFlagUse = false;
7369     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7370            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7371       SDNode *User = *UI;
7372       unsigned UOpNo = UI.getOperandNo();
7373       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7374         // Look pass truncate.
7375         UOpNo = User->use_begin().getOperandNo();
7376         User = *User->use_begin();
7377       }
7378
7379       if (User->getOpcode() != ISD::BRCOND &&
7380           User->getOpcode() != ISD::SETCC &&
7381           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7382         NonFlagUse = true;
7383         break;
7384       }
7385     }
7386
7387     if (!NonFlagUse)
7388       break;
7389   }
7390     // FALL THROUGH
7391   case ISD::SUB:
7392   case ISD::OR:
7393   case ISD::XOR:
7394     // Due to the ISEL shortcoming noted above, be conservative if this op is
7395     // likely to be selected as part of a load-modify-store instruction.
7396     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7397            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7398       if (UI->getOpcode() == ISD::STORE)
7399         goto default_case;
7400
7401     // Otherwise use a regular EFLAGS-setting instruction.
7402     switch (Op.getNode()->getOpcode()) {
7403     default: llvm_unreachable("unexpected operator!");
7404     case ISD::SUB: Opcode = X86ISD::SUB; break;
7405     case ISD::OR:  Opcode = X86ISD::OR;  break;
7406     case ISD::XOR: Opcode = X86ISD::XOR; break;
7407     case ISD::AND: Opcode = X86ISD::AND; break;
7408     }
7409
7410     NumOperands = 2;
7411     break;
7412   case X86ISD::ADD:
7413   case X86ISD::SUB:
7414   case X86ISD::INC:
7415   case X86ISD::DEC:
7416   case X86ISD::OR:
7417   case X86ISD::XOR:
7418   case X86ISD::AND:
7419     return SDValue(Op.getNode(), 1);
7420   default:
7421   default_case:
7422     break;
7423   }
7424
7425   if (Opcode == 0)
7426     // Emit a CMP with 0, which is the TEST pattern.
7427     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7428                        DAG.getConstant(0, Op.getValueType()));
7429
7430   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7431   SmallVector<SDValue, 4> Ops;
7432   for (unsigned i = 0; i != NumOperands; ++i)
7433     Ops.push_back(Op.getOperand(i));
7434
7435   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7436   DAG.ReplaceAllUsesWith(Op, New);
7437   return SDValue(New.getNode(), 1);
7438 }
7439
7440 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7441 /// equivalent.
7442 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7443                                    SelectionDAG &DAG) const {
7444   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7445     if (C->getAPIntValue() == 0)
7446       return EmitTest(Op0, X86CC, DAG);
7447
7448   DebugLoc dl = Op0.getDebugLoc();
7449   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7450 }
7451
7452 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7453 /// if it's possible.
7454 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7455                                      DebugLoc dl, SelectionDAG &DAG) const {
7456   SDValue Op0 = And.getOperand(0);
7457   SDValue Op1 = And.getOperand(1);
7458   if (Op0.getOpcode() == ISD::TRUNCATE)
7459     Op0 = Op0.getOperand(0);
7460   if (Op1.getOpcode() == ISD::TRUNCATE)
7461     Op1 = Op1.getOperand(0);
7462
7463   SDValue LHS, RHS;
7464   if (Op1.getOpcode() == ISD::SHL)
7465     std::swap(Op0, Op1);
7466   if (Op0.getOpcode() == ISD::SHL) {
7467     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7468       if (And00C->getZExtValue() == 1) {
7469         // If we looked past a truncate, check that it's only truncating away
7470         // known zeros.
7471         unsigned BitWidth = Op0.getValueSizeInBits();
7472         unsigned AndBitWidth = And.getValueSizeInBits();
7473         if (BitWidth > AndBitWidth) {
7474           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7475           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7476           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7477             return SDValue();
7478         }
7479         LHS = Op1;
7480         RHS = Op0.getOperand(1);
7481       }
7482   } else if (Op1.getOpcode() == ISD::Constant) {
7483     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7484     SDValue AndLHS = Op0;
7485     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7486       LHS = AndLHS.getOperand(0);
7487       RHS = AndLHS.getOperand(1);
7488     }
7489   }
7490
7491   if (LHS.getNode()) {
7492     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7493     // instruction.  Since the shift amount is in-range-or-undefined, we know
7494     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7495     // the encoding for the i16 version is larger than the i32 version.
7496     // Also promote i16 to i32 for performance / code size reason.
7497     if (LHS.getValueType() == MVT::i8 ||
7498         LHS.getValueType() == MVT::i16)
7499       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7500
7501     // If the operand types disagree, extend the shift amount to match.  Since
7502     // BT ignores high bits (like shifts) we can use anyextend.
7503     if (LHS.getValueType() != RHS.getValueType())
7504       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7505
7506     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7507     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7508     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7509                        DAG.getConstant(Cond, MVT::i8), BT);
7510   }
7511
7512   return SDValue();
7513 }
7514
7515 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7516   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7517   SDValue Op0 = Op.getOperand(0);
7518   SDValue Op1 = Op.getOperand(1);
7519   DebugLoc dl = Op.getDebugLoc();
7520   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7521
7522   // Optimize to BT if possible.
7523   // Lower (X & (1 << N)) == 0 to BT(X, N).
7524   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7525   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7526   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7527       Op1.getOpcode() == ISD::Constant &&
7528       cast<ConstantSDNode>(Op1)->isNullValue() &&
7529       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7530     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7531     if (NewSetCC.getNode())
7532       return NewSetCC;
7533   }
7534
7535   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7536   // these.
7537   if (Op1.getOpcode() == ISD::Constant &&
7538       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7539        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7540       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7541
7542     // If the input is a setcc, then reuse the input setcc or use a new one with
7543     // the inverted condition.
7544     if (Op0.getOpcode() == X86ISD::SETCC) {
7545       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7546       bool Invert = (CC == ISD::SETNE) ^
7547         cast<ConstantSDNode>(Op1)->isNullValue();
7548       if (!Invert) return Op0;
7549
7550       CCode = X86::GetOppositeBranchCondition(CCode);
7551       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7552                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7553     }
7554   }
7555
7556   bool isFP = Op1.getValueType().isFloatingPoint();
7557   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7558   if (X86CC == X86::COND_INVALID)
7559     return SDValue();
7560
7561   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7562   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7563                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7564 }
7565
7566 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7567   SDValue Cond;
7568   SDValue Op0 = Op.getOperand(0);
7569   SDValue Op1 = Op.getOperand(1);
7570   SDValue CC = Op.getOperand(2);
7571   EVT VT = Op.getValueType();
7572   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7573   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7574   DebugLoc dl = Op.getDebugLoc();
7575
7576   if (isFP) {
7577     unsigned SSECC = 8;
7578     EVT VT0 = Op0.getValueType();
7579     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7580     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7581     bool Swap = false;
7582
7583     switch (SetCCOpcode) {
7584     default: break;
7585     case ISD::SETOEQ:
7586     case ISD::SETEQ:  SSECC = 0; break;
7587     case ISD::SETOGT:
7588     case ISD::SETGT: Swap = true; // Fallthrough
7589     case ISD::SETLT:
7590     case ISD::SETOLT: SSECC = 1; break;
7591     case ISD::SETOGE:
7592     case ISD::SETGE: Swap = true; // Fallthrough
7593     case ISD::SETLE:
7594     case ISD::SETOLE: SSECC = 2; break;
7595     case ISD::SETUO:  SSECC = 3; break;
7596     case ISD::SETUNE:
7597     case ISD::SETNE:  SSECC = 4; break;
7598     case ISD::SETULE: Swap = true;
7599     case ISD::SETUGE: SSECC = 5; break;
7600     case ISD::SETULT: Swap = true;
7601     case ISD::SETUGT: SSECC = 6; break;
7602     case ISD::SETO:   SSECC = 7; break;
7603     }
7604     if (Swap)
7605       std::swap(Op0, Op1);
7606
7607     // In the two special cases we can't handle, emit two comparisons.
7608     if (SSECC == 8) {
7609       if (SetCCOpcode == ISD::SETUEQ) {
7610         SDValue UNORD, EQ;
7611         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7612         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7613         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7614       }
7615       else if (SetCCOpcode == ISD::SETONE) {
7616         SDValue ORD, NEQ;
7617         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7618         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7619         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7620       }
7621       llvm_unreachable("Illegal FP comparison");
7622     }
7623     // Handle all other FP comparisons here.
7624     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7625   }
7626
7627   // We are handling one of the integer comparisons here.  Since SSE only has
7628   // GT and EQ comparisons for integer, swapping operands and multiple
7629   // operations may be required for some comparisons.
7630   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7631   bool Swap = false, Invert = false, FlipSigns = false;
7632
7633   switch (VT.getSimpleVT().SimpleTy) {
7634   default: break;
7635   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7636   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7637   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7638   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7639   }
7640
7641   switch (SetCCOpcode) {
7642   default: break;
7643   case ISD::SETNE:  Invert = true;
7644   case ISD::SETEQ:  Opc = EQOpc; break;
7645   case ISD::SETLT:  Swap = true;
7646   case ISD::SETGT:  Opc = GTOpc; break;
7647   case ISD::SETGE:  Swap = true;
7648   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7649   case ISD::SETULT: Swap = true;
7650   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7651   case ISD::SETUGE: Swap = true;
7652   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7653   }
7654   if (Swap)
7655     std::swap(Op0, Op1);
7656
7657   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7658   // bits of the inputs before performing those operations.
7659   if (FlipSigns) {
7660     EVT EltVT = VT.getVectorElementType();
7661     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7662                                       EltVT);
7663     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7664     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7665                                     SignBits.size());
7666     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7667     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7668   }
7669
7670   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7671
7672   // If the logical-not of the result is required, perform that now.
7673   if (Invert)
7674     Result = DAG.getNOT(dl, Result, VT);
7675
7676   return Result;
7677 }
7678
7679 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7680 static bool isX86LogicalCmp(SDValue Op) {
7681   unsigned Opc = Op.getNode()->getOpcode();
7682   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7683     return true;
7684   if (Op.getResNo() == 1 &&
7685       (Opc == X86ISD::ADD ||
7686        Opc == X86ISD::SUB ||
7687        Opc == X86ISD::ADC ||
7688        Opc == X86ISD::SBB ||
7689        Opc == X86ISD::SMUL ||
7690        Opc == X86ISD::UMUL ||
7691        Opc == X86ISD::INC ||
7692        Opc == X86ISD::DEC ||
7693        Opc == X86ISD::OR ||
7694        Opc == X86ISD::XOR ||
7695        Opc == X86ISD::AND))
7696     return true;
7697
7698   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7699     return true;
7700
7701   return false;
7702 }
7703
7704 static bool isZero(SDValue V) {
7705   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7706   return C && C->isNullValue();
7707 }
7708
7709 static bool isAllOnes(SDValue V) {
7710   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7711   return C && C->isAllOnesValue();
7712 }
7713
7714 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7715   bool addTest = true;
7716   SDValue Cond  = Op.getOperand(0);
7717   SDValue Op1 = Op.getOperand(1);
7718   SDValue Op2 = Op.getOperand(2);
7719   DebugLoc DL = Op.getDebugLoc();
7720   SDValue CC;
7721
7722   if (Cond.getOpcode() == ISD::SETCC) {
7723     SDValue NewCond = LowerSETCC(Cond, DAG);
7724     if (NewCond.getNode())
7725       Cond = NewCond;
7726   }
7727
7728   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7729   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7730   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7731   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7732   if (Cond.getOpcode() == X86ISD::SETCC &&
7733       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7734       isZero(Cond.getOperand(1).getOperand(1))) {
7735     SDValue Cmp = Cond.getOperand(1);
7736
7737     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7738
7739     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7740         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7741       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7742
7743       SDValue CmpOp0 = Cmp.getOperand(0);
7744       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7745                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7746
7747       SDValue Res =   // Res = 0 or -1.
7748         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7749                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7750
7751       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7752         Res = DAG.getNOT(DL, Res, Res.getValueType());
7753
7754       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7755       if (N2C == 0 || !N2C->isNullValue())
7756         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7757       return Res;
7758     }
7759   }
7760
7761   // Look past (and (setcc_carry (cmp ...)), 1).
7762   if (Cond.getOpcode() == ISD::AND &&
7763       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7764     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7765     if (C && C->getAPIntValue() == 1)
7766       Cond = Cond.getOperand(0);
7767   }
7768
7769   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7770   // setting operand in place of the X86ISD::SETCC.
7771   if (Cond.getOpcode() == X86ISD::SETCC ||
7772       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7773     CC = Cond.getOperand(0);
7774
7775     SDValue Cmp = Cond.getOperand(1);
7776     unsigned Opc = Cmp.getOpcode();
7777     EVT VT = Op.getValueType();
7778
7779     bool IllegalFPCMov = false;
7780     if (VT.isFloatingPoint() && !VT.isVector() &&
7781         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7782       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7783
7784     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7785         Opc == X86ISD::BT) { // FIXME
7786       Cond = Cmp;
7787       addTest = false;
7788     }
7789   }
7790
7791   if (addTest) {
7792     // Look pass the truncate.
7793     if (Cond.getOpcode() == ISD::TRUNCATE)
7794       Cond = Cond.getOperand(0);
7795
7796     // We know the result of AND is compared against zero. Try to match
7797     // it to BT.
7798     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7799       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7800       if (NewSetCC.getNode()) {
7801         CC = NewSetCC.getOperand(0);
7802         Cond = NewSetCC.getOperand(1);
7803         addTest = false;
7804       }
7805     }
7806   }
7807
7808   if (addTest) {
7809     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7810     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7811   }
7812
7813   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7814   // a <  b ?  0 : -1 -> RES = setcc_carry
7815   // a >= b ? -1 :  0 -> RES = setcc_carry
7816   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7817   if (Cond.getOpcode() == X86ISD::CMP) {
7818     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7819
7820     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7821         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7822       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7823                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7824       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7825         return DAG.getNOT(DL, Res, Res.getValueType());
7826       return Res;
7827     }
7828   }
7829
7830   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7831   // condition is true.
7832   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7833   SDValue Ops[] = { Op2, Op1, CC, Cond };
7834   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7835 }
7836
7837 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7838 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7839 // from the AND / OR.
7840 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7841   Opc = Op.getOpcode();
7842   if (Opc != ISD::OR && Opc != ISD::AND)
7843     return false;
7844   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7845           Op.getOperand(0).hasOneUse() &&
7846           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7847           Op.getOperand(1).hasOneUse());
7848 }
7849
7850 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7851 // 1 and that the SETCC node has a single use.
7852 static bool isXor1OfSetCC(SDValue Op) {
7853   if (Op.getOpcode() != ISD::XOR)
7854     return false;
7855   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7856   if (N1C && N1C->getAPIntValue() == 1) {
7857     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7858       Op.getOperand(0).hasOneUse();
7859   }
7860   return false;
7861 }
7862
7863 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7864   bool addTest = true;
7865   SDValue Chain = Op.getOperand(0);
7866   SDValue Cond  = Op.getOperand(1);
7867   SDValue Dest  = Op.getOperand(2);
7868   DebugLoc dl = Op.getDebugLoc();
7869   SDValue CC;
7870
7871   if (Cond.getOpcode() == ISD::SETCC) {
7872     SDValue NewCond = LowerSETCC(Cond, DAG);
7873     if (NewCond.getNode())
7874       Cond = NewCond;
7875   }
7876 #if 0
7877   // FIXME: LowerXALUO doesn't handle these!!
7878   else if (Cond.getOpcode() == X86ISD::ADD  ||
7879            Cond.getOpcode() == X86ISD::SUB  ||
7880            Cond.getOpcode() == X86ISD::SMUL ||
7881            Cond.getOpcode() == X86ISD::UMUL)
7882     Cond = LowerXALUO(Cond, DAG);
7883 #endif
7884
7885   // Look pass (and (setcc_carry (cmp ...)), 1).
7886   if (Cond.getOpcode() == ISD::AND &&
7887       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7888     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7889     if (C && C->getAPIntValue() == 1)
7890       Cond = Cond.getOperand(0);
7891   }
7892
7893   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7894   // setting operand in place of the X86ISD::SETCC.
7895   if (Cond.getOpcode() == X86ISD::SETCC ||
7896       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7897     CC = Cond.getOperand(0);
7898
7899     SDValue Cmp = Cond.getOperand(1);
7900     unsigned Opc = Cmp.getOpcode();
7901     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7902     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7903       Cond = Cmp;
7904       addTest = false;
7905     } else {
7906       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7907       default: break;
7908       case X86::COND_O:
7909       case X86::COND_B:
7910         // These can only come from an arithmetic instruction with overflow,
7911         // e.g. SADDO, UADDO.
7912         Cond = Cond.getNode()->getOperand(1);
7913         addTest = false;
7914         break;
7915       }
7916     }
7917   } else {
7918     unsigned CondOpc;
7919     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7920       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7921       if (CondOpc == ISD::OR) {
7922         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7923         // two branches instead of an explicit OR instruction with a
7924         // separate test.
7925         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7926             isX86LogicalCmp(Cmp)) {
7927           CC = Cond.getOperand(0).getOperand(0);
7928           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7929                               Chain, Dest, CC, Cmp);
7930           CC = Cond.getOperand(1).getOperand(0);
7931           Cond = Cmp;
7932           addTest = false;
7933         }
7934       } else { // ISD::AND
7935         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7936         // two branches instead of an explicit AND instruction with a
7937         // separate test. However, we only do this if this block doesn't
7938         // have a fall-through edge, because this requires an explicit
7939         // jmp when the condition is false.
7940         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7941             isX86LogicalCmp(Cmp) &&
7942             Op.getNode()->hasOneUse()) {
7943           X86::CondCode CCode =
7944             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7945           CCode = X86::GetOppositeBranchCondition(CCode);
7946           CC = DAG.getConstant(CCode, MVT::i8);
7947           SDNode *User = *Op.getNode()->use_begin();
7948           // Look for an unconditional branch following this conditional branch.
7949           // We need this because we need to reverse the successors in order
7950           // to implement FCMP_OEQ.
7951           if (User->getOpcode() == ISD::BR) {
7952             SDValue FalseBB = User->getOperand(1);
7953             SDNode *NewBR =
7954               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7955             assert(NewBR == User);
7956             (void)NewBR;
7957             Dest = FalseBB;
7958
7959             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7960                                 Chain, Dest, CC, Cmp);
7961             X86::CondCode CCode =
7962               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7963             CCode = X86::GetOppositeBranchCondition(CCode);
7964             CC = DAG.getConstant(CCode, MVT::i8);
7965             Cond = Cmp;
7966             addTest = false;
7967           }
7968         }
7969       }
7970     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7971       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7972       // It should be transformed during dag combiner except when the condition
7973       // is set by a arithmetics with overflow node.
7974       X86::CondCode CCode =
7975         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7976       CCode = X86::GetOppositeBranchCondition(CCode);
7977       CC = DAG.getConstant(CCode, MVT::i8);
7978       Cond = Cond.getOperand(0).getOperand(1);
7979       addTest = false;
7980     }
7981   }
7982
7983   if (addTest) {
7984     // Look pass the truncate.
7985     if (Cond.getOpcode() == ISD::TRUNCATE)
7986       Cond = Cond.getOperand(0);
7987
7988     // We know the result of AND is compared against zero. Try to match
7989     // it to BT.
7990     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7991       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7992       if (NewSetCC.getNode()) {
7993         CC = NewSetCC.getOperand(0);
7994         Cond = NewSetCC.getOperand(1);
7995         addTest = false;
7996       }
7997     }
7998   }
7999
8000   if (addTest) {
8001     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8002     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8003   }
8004   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8005                      Chain, Dest, CC, Cond);
8006 }
8007
8008
8009 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8010 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8011 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8012 // that the guard pages used by the OS virtual memory manager are allocated in
8013 // correct sequence.
8014 SDValue
8015 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8016                                            SelectionDAG &DAG) const {
8017   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8018          "This should be used only on Windows targets");
8019   assert(!Subtarget->isTargetEnvMacho());
8020   DebugLoc dl = Op.getDebugLoc();
8021
8022   // Get the inputs.
8023   SDValue Chain = Op.getOperand(0);
8024   SDValue Size  = Op.getOperand(1);
8025   // FIXME: Ensure alignment here
8026
8027   SDValue Flag;
8028
8029   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8030   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8031
8032   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8033   Flag = Chain.getValue(1);
8034
8035   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8036
8037   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8038   Flag = Chain.getValue(1);
8039
8040   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8041
8042   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8043   return DAG.getMergeValues(Ops1, 2, dl);
8044 }
8045
8046 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8047   MachineFunction &MF = DAG.getMachineFunction();
8048   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8049
8050   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8051   DebugLoc DL = Op.getDebugLoc();
8052
8053   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8054     // vastart just stores the address of the VarArgsFrameIndex slot into the
8055     // memory location argument.
8056     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8057                                    getPointerTy());
8058     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8059                         MachinePointerInfo(SV), false, false, 0);
8060   }
8061
8062   // __va_list_tag:
8063   //   gp_offset         (0 - 6 * 8)
8064   //   fp_offset         (48 - 48 + 8 * 16)
8065   //   overflow_arg_area (point to parameters coming in memory).
8066   //   reg_save_area
8067   SmallVector<SDValue, 8> MemOps;
8068   SDValue FIN = Op.getOperand(1);
8069   // Store gp_offset
8070   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8071                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8072                                                MVT::i32),
8073                                FIN, MachinePointerInfo(SV), false, false, 0);
8074   MemOps.push_back(Store);
8075
8076   // Store fp_offset
8077   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8078                     FIN, DAG.getIntPtrConstant(4));
8079   Store = DAG.getStore(Op.getOperand(0), DL,
8080                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8081                                        MVT::i32),
8082                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8083   MemOps.push_back(Store);
8084
8085   // Store ptr to overflow_arg_area
8086   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8087                     FIN, DAG.getIntPtrConstant(4));
8088   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8089                                     getPointerTy());
8090   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8091                        MachinePointerInfo(SV, 8),
8092                        false, false, 0);
8093   MemOps.push_back(Store);
8094
8095   // Store ptr to reg_save_area.
8096   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8097                     FIN, DAG.getIntPtrConstant(8));
8098   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8099                                     getPointerTy());
8100   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8101                        MachinePointerInfo(SV, 16), false, false, 0);
8102   MemOps.push_back(Store);
8103   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8104                      &MemOps[0], MemOps.size());
8105 }
8106
8107 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8108   assert(Subtarget->is64Bit() &&
8109          "LowerVAARG only handles 64-bit va_arg!");
8110   assert((Subtarget->isTargetLinux() ||
8111           Subtarget->isTargetDarwin()) &&
8112           "Unhandled target in LowerVAARG");
8113   assert(Op.getNode()->getNumOperands() == 4);
8114   SDValue Chain = Op.getOperand(0);
8115   SDValue SrcPtr = Op.getOperand(1);
8116   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8117   unsigned Align = Op.getConstantOperandVal(3);
8118   DebugLoc dl = Op.getDebugLoc();
8119
8120   EVT ArgVT = Op.getNode()->getValueType(0);
8121   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8122   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8123   uint8_t ArgMode;
8124
8125   // Decide which area this value should be read from.
8126   // TODO: Implement the AMD64 ABI in its entirety. This simple
8127   // selection mechanism works only for the basic types.
8128   if (ArgVT == MVT::f80) {
8129     llvm_unreachable("va_arg for f80 not yet implemented");
8130   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8131     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8132   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8133     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8134   } else {
8135     llvm_unreachable("Unhandled argument type in LowerVAARG");
8136   }
8137
8138   if (ArgMode == 2) {
8139     // Sanity Check: Make sure using fp_offset makes sense.
8140     assert(!UseSoftFloat &&
8141            !(DAG.getMachineFunction()
8142                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8143            Subtarget->hasXMM());
8144   }
8145
8146   // Insert VAARG_64 node into the DAG
8147   // VAARG_64 returns two values: Variable Argument Address, Chain
8148   SmallVector<SDValue, 11> InstOps;
8149   InstOps.push_back(Chain);
8150   InstOps.push_back(SrcPtr);
8151   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8152   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8153   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8154   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8155   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8156                                           VTs, &InstOps[0], InstOps.size(),
8157                                           MVT::i64,
8158                                           MachinePointerInfo(SV),
8159                                           /*Align=*/0,
8160                                           /*Volatile=*/false,
8161                                           /*ReadMem=*/true,
8162                                           /*WriteMem=*/true);
8163   Chain = VAARG.getValue(1);
8164
8165   // Load the next argument and return it
8166   return DAG.getLoad(ArgVT, dl,
8167                      Chain,
8168                      VAARG,
8169                      MachinePointerInfo(),
8170                      false, false, 0);
8171 }
8172
8173 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8174   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8175   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8176   SDValue Chain = Op.getOperand(0);
8177   SDValue DstPtr = Op.getOperand(1);
8178   SDValue SrcPtr = Op.getOperand(2);
8179   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8180   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8181   DebugLoc DL = Op.getDebugLoc();
8182
8183   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8184                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8185                        false,
8186                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8187 }
8188
8189 SDValue
8190 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8191   DebugLoc dl = Op.getDebugLoc();
8192   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8193   switch (IntNo) {
8194   default: return SDValue();    // Don't custom lower most intrinsics.
8195   // Comparison intrinsics.
8196   case Intrinsic::x86_sse_comieq_ss:
8197   case Intrinsic::x86_sse_comilt_ss:
8198   case Intrinsic::x86_sse_comile_ss:
8199   case Intrinsic::x86_sse_comigt_ss:
8200   case Intrinsic::x86_sse_comige_ss:
8201   case Intrinsic::x86_sse_comineq_ss:
8202   case Intrinsic::x86_sse_ucomieq_ss:
8203   case Intrinsic::x86_sse_ucomilt_ss:
8204   case Intrinsic::x86_sse_ucomile_ss:
8205   case Intrinsic::x86_sse_ucomigt_ss:
8206   case Intrinsic::x86_sse_ucomige_ss:
8207   case Intrinsic::x86_sse_ucomineq_ss:
8208   case Intrinsic::x86_sse2_comieq_sd:
8209   case Intrinsic::x86_sse2_comilt_sd:
8210   case Intrinsic::x86_sse2_comile_sd:
8211   case Intrinsic::x86_sse2_comigt_sd:
8212   case Intrinsic::x86_sse2_comige_sd:
8213   case Intrinsic::x86_sse2_comineq_sd:
8214   case Intrinsic::x86_sse2_ucomieq_sd:
8215   case Intrinsic::x86_sse2_ucomilt_sd:
8216   case Intrinsic::x86_sse2_ucomile_sd:
8217   case Intrinsic::x86_sse2_ucomigt_sd:
8218   case Intrinsic::x86_sse2_ucomige_sd:
8219   case Intrinsic::x86_sse2_ucomineq_sd: {
8220     unsigned Opc = 0;
8221     ISD::CondCode CC = ISD::SETCC_INVALID;
8222     switch (IntNo) {
8223     default: break;
8224     case Intrinsic::x86_sse_comieq_ss:
8225     case Intrinsic::x86_sse2_comieq_sd:
8226       Opc = X86ISD::COMI;
8227       CC = ISD::SETEQ;
8228       break;
8229     case Intrinsic::x86_sse_comilt_ss:
8230     case Intrinsic::x86_sse2_comilt_sd:
8231       Opc = X86ISD::COMI;
8232       CC = ISD::SETLT;
8233       break;
8234     case Intrinsic::x86_sse_comile_ss:
8235     case Intrinsic::x86_sse2_comile_sd:
8236       Opc = X86ISD::COMI;
8237       CC = ISD::SETLE;
8238       break;
8239     case Intrinsic::x86_sse_comigt_ss:
8240     case Intrinsic::x86_sse2_comigt_sd:
8241       Opc = X86ISD::COMI;
8242       CC = ISD::SETGT;
8243       break;
8244     case Intrinsic::x86_sse_comige_ss:
8245     case Intrinsic::x86_sse2_comige_sd:
8246       Opc = X86ISD::COMI;
8247       CC = ISD::SETGE;
8248       break;
8249     case Intrinsic::x86_sse_comineq_ss:
8250     case Intrinsic::x86_sse2_comineq_sd:
8251       Opc = X86ISD::COMI;
8252       CC = ISD::SETNE;
8253       break;
8254     case Intrinsic::x86_sse_ucomieq_ss:
8255     case Intrinsic::x86_sse2_ucomieq_sd:
8256       Opc = X86ISD::UCOMI;
8257       CC = ISD::SETEQ;
8258       break;
8259     case Intrinsic::x86_sse_ucomilt_ss:
8260     case Intrinsic::x86_sse2_ucomilt_sd:
8261       Opc = X86ISD::UCOMI;
8262       CC = ISD::SETLT;
8263       break;
8264     case Intrinsic::x86_sse_ucomile_ss:
8265     case Intrinsic::x86_sse2_ucomile_sd:
8266       Opc = X86ISD::UCOMI;
8267       CC = ISD::SETLE;
8268       break;
8269     case Intrinsic::x86_sse_ucomigt_ss:
8270     case Intrinsic::x86_sse2_ucomigt_sd:
8271       Opc = X86ISD::UCOMI;
8272       CC = ISD::SETGT;
8273       break;
8274     case Intrinsic::x86_sse_ucomige_ss:
8275     case Intrinsic::x86_sse2_ucomige_sd:
8276       Opc = X86ISD::UCOMI;
8277       CC = ISD::SETGE;
8278       break;
8279     case Intrinsic::x86_sse_ucomineq_ss:
8280     case Intrinsic::x86_sse2_ucomineq_sd:
8281       Opc = X86ISD::UCOMI;
8282       CC = ISD::SETNE;
8283       break;
8284     }
8285
8286     SDValue LHS = Op.getOperand(1);
8287     SDValue RHS = Op.getOperand(2);
8288     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8289     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8290     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8291     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8292                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8293     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8294   }
8295   // ptest and testp intrinsics. The intrinsic these come from are designed to
8296   // return an integer value, not just an instruction so lower it to the ptest
8297   // or testp pattern and a setcc for the result.
8298   case Intrinsic::x86_sse41_ptestz:
8299   case Intrinsic::x86_sse41_ptestc:
8300   case Intrinsic::x86_sse41_ptestnzc:
8301   case Intrinsic::x86_avx_ptestz_256:
8302   case Intrinsic::x86_avx_ptestc_256:
8303   case Intrinsic::x86_avx_ptestnzc_256:
8304   case Intrinsic::x86_avx_vtestz_ps:
8305   case Intrinsic::x86_avx_vtestc_ps:
8306   case Intrinsic::x86_avx_vtestnzc_ps:
8307   case Intrinsic::x86_avx_vtestz_pd:
8308   case Intrinsic::x86_avx_vtestc_pd:
8309   case Intrinsic::x86_avx_vtestnzc_pd:
8310   case Intrinsic::x86_avx_vtestz_ps_256:
8311   case Intrinsic::x86_avx_vtestc_ps_256:
8312   case Intrinsic::x86_avx_vtestnzc_ps_256:
8313   case Intrinsic::x86_avx_vtestz_pd_256:
8314   case Intrinsic::x86_avx_vtestc_pd_256:
8315   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8316     bool IsTestPacked = false;
8317     unsigned X86CC = 0;
8318     switch (IntNo) {
8319     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8320     case Intrinsic::x86_avx_vtestz_ps:
8321     case Intrinsic::x86_avx_vtestz_pd:
8322     case Intrinsic::x86_avx_vtestz_ps_256:
8323     case Intrinsic::x86_avx_vtestz_pd_256:
8324       IsTestPacked = true; // Fallthrough
8325     case Intrinsic::x86_sse41_ptestz:
8326     case Intrinsic::x86_avx_ptestz_256:
8327       // ZF = 1
8328       X86CC = X86::COND_E;
8329       break;
8330     case Intrinsic::x86_avx_vtestc_ps:
8331     case Intrinsic::x86_avx_vtestc_pd:
8332     case Intrinsic::x86_avx_vtestc_ps_256:
8333     case Intrinsic::x86_avx_vtestc_pd_256:
8334       IsTestPacked = true; // Fallthrough
8335     case Intrinsic::x86_sse41_ptestc:
8336     case Intrinsic::x86_avx_ptestc_256:
8337       // CF = 1
8338       X86CC = X86::COND_B;
8339       break;
8340     case Intrinsic::x86_avx_vtestnzc_ps:
8341     case Intrinsic::x86_avx_vtestnzc_pd:
8342     case Intrinsic::x86_avx_vtestnzc_ps_256:
8343     case Intrinsic::x86_avx_vtestnzc_pd_256:
8344       IsTestPacked = true; // Fallthrough
8345     case Intrinsic::x86_sse41_ptestnzc:
8346     case Intrinsic::x86_avx_ptestnzc_256:
8347       // ZF and CF = 0
8348       X86CC = X86::COND_A;
8349       break;
8350     }
8351
8352     SDValue LHS = Op.getOperand(1);
8353     SDValue RHS = Op.getOperand(2);
8354     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8355     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8356     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8357     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8358     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8359   }
8360
8361   // Fix vector shift instructions where the last operand is a non-immediate
8362   // i32 value.
8363   case Intrinsic::x86_sse2_pslli_w:
8364   case Intrinsic::x86_sse2_pslli_d:
8365   case Intrinsic::x86_sse2_pslli_q:
8366   case Intrinsic::x86_sse2_psrli_w:
8367   case Intrinsic::x86_sse2_psrli_d:
8368   case Intrinsic::x86_sse2_psrli_q:
8369   case Intrinsic::x86_sse2_psrai_w:
8370   case Intrinsic::x86_sse2_psrai_d:
8371   case Intrinsic::x86_mmx_pslli_w:
8372   case Intrinsic::x86_mmx_pslli_d:
8373   case Intrinsic::x86_mmx_pslli_q:
8374   case Intrinsic::x86_mmx_psrli_w:
8375   case Intrinsic::x86_mmx_psrli_d:
8376   case Intrinsic::x86_mmx_psrli_q:
8377   case Intrinsic::x86_mmx_psrai_w:
8378   case Intrinsic::x86_mmx_psrai_d: {
8379     SDValue ShAmt = Op.getOperand(2);
8380     if (isa<ConstantSDNode>(ShAmt))
8381       return SDValue();
8382
8383     unsigned NewIntNo = 0;
8384     EVT ShAmtVT = MVT::v4i32;
8385     switch (IntNo) {
8386     case Intrinsic::x86_sse2_pslli_w:
8387       NewIntNo = Intrinsic::x86_sse2_psll_w;
8388       break;
8389     case Intrinsic::x86_sse2_pslli_d:
8390       NewIntNo = Intrinsic::x86_sse2_psll_d;
8391       break;
8392     case Intrinsic::x86_sse2_pslli_q:
8393       NewIntNo = Intrinsic::x86_sse2_psll_q;
8394       break;
8395     case Intrinsic::x86_sse2_psrli_w:
8396       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8397       break;
8398     case Intrinsic::x86_sse2_psrli_d:
8399       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8400       break;
8401     case Intrinsic::x86_sse2_psrli_q:
8402       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8403       break;
8404     case Intrinsic::x86_sse2_psrai_w:
8405       NewIntNo = Intrinsic::x86_sse2_psra_w;
8406       break;
8407     case Intrinsic::x86_sse2_psrai_d:
8408       NewIntNo = Intrinsic::x86_sse2_psra_d;
8409       break;
8410     default: {
8411       ShAmtVT = MVT::v2i32;
8412       switch (IntNo) {
8413       case Intrinsic::x86_mmx_pslli_w:
8414         NewIntNo = Intrinsic::x86_mmx_psll_w;
8415         break;
8416       case Intrinsic::x86_mmx_pslli_d:
8417         NewIntNo = Intrinsic::x86_mmx_psll_d;
8418         break;
8419       case Intrinsic::x86_mmx_pslli_q:
8420         NewIntNo = Intrinsic::x86_mmx_psll_q;
8421         break;
8422       case Intrinsic::x86_mmx_psrli_w:
8423         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8424         break;
8425       case Intrinsic::x86_mmx_psrli_d:
8426         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8427         break;
8428       case Intrinsic::x86_mmx_psrli_q:
8429         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8430         break;
8431       case Intrinsic::x86_mmx_psrai_w:
8432         NewIntNo = Intrinsic::x86_mmx_psra_w;
8433         break;
8434       case Intrinsic::x86_mmx_psrai_d:
8435         NewIntNo = Intrinsic::x86_mmx_psra_d;
8436         break;
8437       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8438       }
8439       break;
8440     }
8441     }
8442
8443     // The vector shift intrinsics with scalars uses 32b shift amounts but
8444     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8445     // to be zero.
8446     SDValue ShOps[4];
8447     ShOps[0] = ShAmt;
8448     ShOps[1] = DAG.getConstant(0, MVT::i32);
8449     if (ShAmtVT == MVT::v4i32) {
8450       ShOps[2] = DAG.getUNDEF(MVT::i32);
8451       ShOps[3] = DAG.getUNDEF(MVT::i32);
8452       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8453     } else {
8454       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8455 // FIXME this must be lowered to get rid of the invalid type.
8456     }
8457
8458     EVT VT = Op.getValueType();
8459     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8460     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8461                        DAG.getConstant(NewIntNo, MVT::i32),
8462                        Op.getOperand(1), ShAmt);
8463   }
8464   }
8465 }
8466
8467 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8468                                            SelectionDAG &DAG) const {
8469   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8470   MFI->setReturnAddressIsTaken(true);
8471
8472   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8473   DebugLoc dl = Op.getDebugLoc();
8474
8475   if (Depth > 0) {
8476     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8477     SDValue Offset =
8478       DAG.getConstant(TD->getPointerSize(),
8479                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8480     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8481                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8482                                    FrameAddr, Offset),
8483                        MachinePointerInfo(), false, false, 0);
8484   }
8485
8486   // Just load the return address.
8487   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8488   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8489                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8490 }
8491
8492 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8493   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8494   MFI->setFrameAddressIsTaken(true);
8495
8496   EVT VT = Op.getValueType();
8497   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8498   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8499   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8500   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8501   while (Depth--)
8502     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8503                             MachinePointerInfo(),
8504                             false, false, 0);
8505   return FrameAddr;
8506 }
8507
8508 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8509                                                      SelectionDAG &DAG) const {
8510   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8511 }
8512
8513 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8514   MachineFunction &MF = DAG.getMachineFunction();
8515   SDValue Chain     = Op.getOperand(0);
8516   SDValue Offset    = Op.getOperand(1);
8517   SDValue Handler   = Op.getOperand(2);
8518   DebugLoc dl       = Op.getDebugLoc();
8519
8520   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8521                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8522                                      getPointerTy());
8523   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8524
8525   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8526                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8527   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8528   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8529                        false, false, 0);
8530   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8531   MF.getRegInfo().addLiveOut(StoreAddrReg);
8532
8533   return DAG.getNode(X86ISD::EH_RETURN, dl,
8534                      MVT::Other,
8535                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8536 }
8537
8538 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8539                                              SelectionDAG &DAG) const {
8540   SDValue Root = Op.getOperand(0);
8541   SDValue Trmp = Op.getOperand(1); // trampoline
8542   SDValue FPtr = Op.getOperand(2); // nested function
8543   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8544   DebugLoc dl  = Op.getDebugLoc();
8545
8546   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8547
8548   if (Subtarget->is64Bit()) {
8549     SDValue OutChains[6];
8550
8551     // Large code-model.
8552     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8553     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8554
8555     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8556     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8557
8558     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8559
8560     // Load the pointer to the nested function into R11.
8561     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8562     SDValue Addr = Trmp;
8563     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8564                                 Addr, MachinePointerInfo(TrmpAddr),
8565                                 false, false, 0);
8566
8567     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8568                        DAG.getConstant(2, MVT::i64));
8569     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8570                                 MachinePointerInfo(TrmpAddr, 2),
8571                                 false, false, 2);
8572
8573     // Load the 'nest' parameter value into R10.
8574     // R10 is specified in X86CallingConv.td
8575     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8577                        DAG.getConstant(10, MVT::i64));
8578     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8579                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8580                                 false, false, 0);
8581
8582     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8583                        DAG.getConstant(12, MVT::i64));
8584     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8585                                 MachinePointerInfo(TrmpAddr, 12),
8586                                 false, false, 2);
8587
8588     // Jump to the nested function.
8589     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8590     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8591                        DAG.getConstant(20, MVT::i64));
8592     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8593                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8594                                 false, false, 0);
8595
8596     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8597     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8598                        DAG.getConstant(22, MVT::i64));
8599     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8600                                 MachinePointerInfo(TrmpAddr, 22),
8601                                 false, false, 0);
8602
8603     SDValue Ops[] =
8604       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8605     return DAG.getMergeValues(Ops, 2, dl);
8606   } else {
8607     const Function *Func =
8608       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8609     CallingConv::ID CC = Func->getCallingConv();
8610     unsigned NestReg;
8611
8612     switch (CC) {
8613     default:
8614       llvm_unreachable("Unsupported calling convention");
8615     case CallingConv::C:
8616     case CallingConv::X86_StdCall: {
8617       // Pass 'nest' parameter in ECX.
8618       // Must be kept in sync with X86CallingConv.td
8619       NestReg = X86::ECX;
8620
8621       // Check that ECX wasn't needed by an 'inreg' parameter.
8622       const FunctionType *FTy = Func->getFunctionType();
8623       const AttrListPtr &Attrs = Func->getAttributes();
8624
8625       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8626         unsigned InRegCount = 0;
8627         unsigned Idx = 1;
8628
8629         for (FunctionType::param_iterator I = FTy->param_begin(),
8630              E = FTy->param_end(); I != E; ++I, ++Idx)
8631           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8632             // FIXME: should only count parameters that are lowered to integers.
8633             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8634
8635         if (InRegCount > 2) {
8636           report_fatal_error("Nest register in use - reduce number of inreg"
8637                              " parameters!");
8638         }
8639       }
8640       break;
8641     }
8642     case CallingConv::X86_FastCall:
8643     case CallingConv::X86_ThisCall:
8644     case CallingConv::Fast:
8645       // Pass 'nest' parameter in EAX.
8646       // Must be kept in sync with X86CallingConv.td
8647       NestReg = X86::EAX;
8648       break;
8649     }
8650
8651     SDValue OutChains[4];
8652     SDValue Addr, Disp;
8653
8654     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8655                        DAG.getConstant(10, MVT::i32));
8656     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8657
8658     // This is storing the opcode for MOV32ri.
8659     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8660     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8661     OutChains[0] = DAG.getStore(Root, dl,
8662                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8663                                 Trmp, MachinePointerInfo(TrmpAddr),
8664                                 false, false, 0);
8665
8666     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8667                        DAG.getConstant(1, MVT::i32));
8668     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8669                                 MachinePointerInfo(TrmpAddr, 1),
8670                                 false, false, 1);
8671
8672     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8673     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8674                        DAG.getConstant(5, MVT::i32));
8675     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8676                                 MachinePointerInfo(TrmpAddr, 5),
8677                                 false, false, 1);
8678
8679     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8680                        DAG.getConstant(6, MVT::i32));
8681     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8682                                 MachinePointerInfo(TrmpAddr, 6),
8683                                 false, false, 1);
8684
8685     SDValue Ops[] =
8686       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8687     return DAG.getMergeValues(Ops, 2, dl);
8688   }
8689 }
8690
8691 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8692                                             SelectionDAG &DAG) const {
8693   /*
8694    The rounding mode is in bits 11:10 of FPSR, and has the following
8695    settings:
8696      00 Round to nearest
8697      01 Round to -inf
8698      10 Round to +inf
8699      11 Round to 0
8700
8701   FLT_ROUNDS, on the other hand, expects the following:
8702     -1 Undefined
8703      0 Round to 0
8704      1 Round to nearest
8705      2 Round to +inf
8706      3 Round to -inf
8707
8708   To perform the conversion, we do:
8709     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8710   */
8711
8712   MachineFunction &MF = DAG.getMachineFunction();
8713   const TargetMachine &TM = MF.getTarget();
8714   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8715   unsigned StackAlignment = TFI.getStackAlignment();
8716   EVT VT = Op.getValueType();
8717   DebugLoc DL = Op.getDebugLoc();
8718
8719   // Save FP Control Word to stack slot
8720   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8721   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8722
8723
8724   MachineMemOperand *MMO =
8725    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8726                            MachineMemOperand::MOStore, 2, 2);
8727
8728   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8729   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8730                                           DAG.getVTList(MVT::Other),
8731                                           Ops, 2, MVT::i16, MMO);
8732
8733   // Load FP Control Word from stack slot
8734   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8735                             MachinePointerInfo(), false, false, 0);
8736
8737   // Transform as necessary
8738   SDValue CWD1 =
8739     DAG.getNode(ISD::SRL, DL, MVT::i16,
8740                 DAG.getNode(ISD::AND, DL, MVT::i16,
8741                             CWD, DAG.getConstant(0x800, MVT::i16)),
8742                 DAG.getConstant(11, MVT::i8));
8743   SDValue CWD2 =
8744     DAG.getNode(ISD::SRL, DL, MVT::i16,
8745                 DAG.getNode(ISD::AND, DL, MVT::i16,
8746                             CWD, DAG.getConstant(0x400, MVT::i16)),
8747                 DAG.getConstant(9, MVT::i8));
8748
8749   SDValue RetVal =
8750     DAG.getNode(ISD::AND, DL, MVT::i16,
8751                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8752                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8753                             DAG.getConstant(1, MVT::i16)),
8754                 DAG.getConstant(3, MVT::i16));
8755
8756
8757   return DAG.getNode((VT.getSizeInBits() < 16 ?
8758                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8759 }
8760
8761 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8762   EVT VT = Op.getValueType();
8763   EVT OpVT = VT;
8764   unsigned NumBits = VT.getSizeInBits();
8765   DebugLoc dl = Op.getDebugLoc();
8766
8767   Op = Op.getOperand(0);
8768   if (VT == MVT::i8) {
8769     // Zero extend to i32 since there is not an i8 bsr.
8770     OpVT = MVT::i32;
8771     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8772   }
8773
8774   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8775   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8776   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8777
8778   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8779   SDValue Ops[] = {
8780     Op,
8781     DAG.getConstant(NumBits+NumBits-1, OpVT),
8782     DAG.getConstant(X86::COND_E, MVT::i8),
8783     Op.getValue(1)
8784   };
8785   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8786
8787   // Finally xor with NumBits-1.
8788   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8789
8790   if (VT == MVT::i8)
8791     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8792   return Op;
8793 }
8794
8795 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8796   EVT VT = Op.getValueType();
8797   EVT OpVT = VT;
8798   unsigned NumBits = VT.getSizeInBits();
8799   DebugLoc dl = Op.getDebugLoc();
8800
8801   Op = Op.getOperand(0);
8802   if (VT == MVT::i8) {
8803     OpVT = MVT::i32;
8804     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8805   }
8806
8807   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8808   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8809   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8810
8811   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8812   SDValue Ops[] = {
8813     Op,
8814     DAG.getConstant(NumBits, OpVT),
8815     DAG.getConstant(X86::COND_E, MVT::i8),
8816     Op.getValue(1)
8817   };
8818   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8819
8820   if (VT == MVT::i8)
8821     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8822   return Op;
8823 }
8824
8825 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8826   EVT VT = Op.getValueType();
8827   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8828   DebugLoc dl = Op.getDebugLoc();
8829
8830   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8831   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8832   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8833   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8834   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8835   //
8836   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8837   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8838   //  return AloBlo + AloBhi + AhiBlo;
8839
8840   SDValue A = Op.getOperand(0);
8841   SDValue B = Op.getOperand(1);
8842
8843   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8844                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8845                        A, DAG.getConstant(32, MVT::i32));
8846   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8847                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8848                        B, DAG.getConstant(32, MVT::i32));
8849   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8850                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8851                        A, B);
8852   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8853                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8854                        A, Bhi);
8855   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8856                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8857                        Ahi, B);
8858   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8859                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8860                        AloBhi, DAG.getConstant(32, MVT::i32));
8861   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8862                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8863                        AhiBlo, DAG.getConstant(32, MVT::i32));
8864   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8865   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8866   return Res;
8867 }
8868
8869 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8870
8871   EVT VT = Op.getValueType();
8872   DebugLoc dl = Op.getDebugLoc();
8873   SDValue R = Op.getOperand(0);
8874   SDValue Amt = Op.getOperand(1);
8875
8876   LLVMContext *Context = DAG.getContext();
8877
8878   // Must have SSE2.
8879   if (!Subtarget->hasSSE2()) return SDValue();
8880
8881   // Optimize shl/srl/sra with constant shift amount.
8882   if (isSplatVector(Amt.getNode())) {
8883     SDValue SclrAmt = Amt->getOperand(0);
8884     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8885       uint64_t ShiftAmt = C->getZExtValue();
8886
8887       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8888        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8889                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8890                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8891
8892       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8893        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8894                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8895                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8896
8897       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8898        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8899                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8900                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8901
8902       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8903        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8904                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8905                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8906
8907       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8908        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8909                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8910                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8911
8912       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8913        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8914                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8915                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8916
8917       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8918        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8919                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8920                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8921
8922       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8923        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8924                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8925                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8926     }
8927   }
8928
8929   // Lower SHL with variable shift amount.
8930   // Cannot lower SHL without SSE2 or later.
8931   if (!Subtarget->hasSSE2()) return SDValue();
8932
8933   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8934     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8935                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8936                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8937
8938     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8939
8940     std::vector<Constant*> CV(4, CI);
8941     Constant *C = ConstantVector::get(CV);
8942     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8943     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8944                                  MachinePointerInfo::getConstantPool(),
8945                                  false, false, 16);
8946
8947     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8948     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8949     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8950     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8951   }
8952   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8953     // a = a << 5;
8954     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8955                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8956                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8957
8958     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8959     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8960
8961     std::vector<Constant*> CVM1(16, CM1);
8962     std::vector<Constant*> CVM2(16, CM2);
8963     Constant *C = ConstantVector::get(CVM1);
8964     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8965     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8966                             MachinePointerInfo::getConstantPool(),
8967                             false, false, 16);
8968
8969     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8970     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8971     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8972                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8973                     DAG.getConstant(4, MVT::i32));
8974     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8975     // a += a
8976     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8977
8978     C = ConstantVector::get(CVM2);
8979     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8980     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8981                     MachinePointerInfo::getConstantPool(),
8982                     false, false, 16);
8983
8984     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8985     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8986     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8987                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8988                     DAG.getConstant(2, MVT::i32));
8989     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8990     // a += a
8991     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8992
8993     // return pblendv(r, r+r, a);
8994     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8995                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8996     return R;
8997   }
8998   return SDValue();
8999 }
9000
9001 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9002   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9003   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9004   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9005   // has only one use.
9006   SDNode *N = Op.getNode();
9007   SDValue LHS = N->getOperand(0);
9008   SDValue RHS = N->getOperand(1);
9009   unsigned BaseOp = 0;
9010   unsigned Cond = 0;
9011   DebugLoc DL = Op.getDebugLoc();
9012   switch (Op.getOpcode()) {
9013   default: llvm_unreachable("Unknown ovf instruction!");
9014   case ISD::SADDO:
9015     // A subtract of one will be selected as a INC. Note that INC doesn't
9016     // set CF, so we can't do this for UADDO.
9017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9018       if (C->isOne()) {
9019         BaseOp = X86ISD::INC;
9020         Cond = X86::COND_O;
9021         break;
9022       }
9023     BaseOp = X86ISD::ADD;
9024     Cond = X86::COND_O;
9025     break;
9026   case ISD::UADDO:
9027     BaseOp = X86ISD::ADD;
9028     Cond = X86::COND_B;
9029     break;
9030   case ISD::SSUBO:
9031     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9032     // set CF, so we can't do this for USUBO.
9033     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9034       if (C->isOne()) {
9035         BaseOp = X86ISD::DEC;
9036         Cond = X86::COND_O;
9037         break;
9038       }
9039     BaseOp = X86ISD::SUB;
9040     Cond = X86::COND_O;
9041     break;
9042   case ISD::USUBO:
9043     BaseOp = X86ISD::SUB;
9044     Cond = X86::COND_B;
9045     break;
9046   case ISD::SMULO:
9047     BaseOp = X86ISD::SMUL;
9048     Cond = X86::COND_O;
9049     break;
9050   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9051     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9052                                  MVT::i32);
9053     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9054
9055     SDValue SetCC =
9056       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9057                   DAG.getConstant(X86::COND_O, MVT::i32),
9058                   SDValue(Sum.getNode(), 2));
9059
9060     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9061     return Sum;
9062   }
9063   }
9064
9065   // Also sets EFLAGS.
9066   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9067   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9068
9069   SDValue SetCC =
9070     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9071                 DAG.getConstant(Cond, MVT::i32),
9072                 SDValue(Sum.getNode(), 1));
9073
9074   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9075   return Sum;
9076 }
9077
9078 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9079   DebugLoc dl = Op.getDebugLoc();
9080   SDNode* Node = Op.getNode();
9081   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9082   EVT VT = Node->getValueType(0);
9083
9084   if (Subtarget->hasSSE2() && VT.isVector()) {
9085     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9086                         ExtraVT.getScalarType().getSizeInBits();
9087     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9088
9089     unsigned SHLIntrinsicsID = 0;
9090     unsigned SRAIntrinsicsID = 0;
9091     switch (VT.getSimpleVT().SimpleTy) {
9092       default:
9093         return SDValue();
9094       case MVT::v2i64: {
9095         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9096         SRAIntrinsicsID = 0;
9097         break;
9098       }
9099       case MVT::v4i32: {
9100         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9101         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9102         break;
9103       }
9104       case MVT::v8i16: {
9105         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9106         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9107         break;
9108       }
9109     }
9110
9111     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9112                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9113                          Node->getOperand(0), ShAmt);
9114
9115     // In case of 1 bit sext, no need to shr
9116     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9117
9118     if (SRAIntrinsicsID) {
9119       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9120                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9121                          Tmp1, ShAmt);
9122     }
9123     return Tmp1;
9124   }
9125
9126   return SDValue();
9127 }
9128
9129
9130 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9131   DebugLoc dl = Op.getDebugLoc();
9132
9133   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9134   // There isn't any reason to disable it if the target processor supports it.
9135   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9136     SDValue Chain = Op.getOperand(0);
9137     SDValue Zero = DAG.getConstant(0, MVT::i32);
9138     SDValue Ops[] = {
9139       DAG.getRegister(X86::ESP, MVT::i32), // Base
9140       DAG.getTargetConstant(1, MVT::i8),   // Scale
9141       DAG.getRegister(0, MVT::i32),        // Index
9142       DAG.getTargetConstant(0, MVT::i32),  // Disp
9143       DAG.getRegister(0, MVT::i32),        // Segment.
9144       Zero,
9145       Chain
9146     };
9147     SDNode *Res =
9148       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9149                           array_lengthof(Ops));
9150     return SDValue(Res, 0);
9151   }
9152
9153   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9154   if (!isDev)
9155     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9156
9157   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9158   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9159   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9160   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9161
9162   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9163   if (!Op1 && !Op2 && !Op3 && Op4)
9164     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9165
9166   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9167   if (Op1 && !Op2 && !Op3 && !Op4)
9168     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9169
9170   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9171   //           (MFENCE)>;
9172   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9173 }
9174
9175 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9176   EVT T = Op.getValueType();
9177   DebugLoc DL = Op.getDebugLoc();
9178   unsigned Reg = 0;
9179   unsigned size = 0;
9180   switch(T.getSimpleVT().SimpleTy) {
9181   default:
9182     assert(false && "Invalid value type!");
9183   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9184   case MVT::i16: Reg = X86::AX;  size = 2; break;
9185   case MVT::i32: Reg = X86::EAX; size = 4; break;
9186   case MVT::i64:
9187     assert(Subtarget->is64Bit() && "Node not type legal!");
9188     Reg = X86::RAX; size = 8;
9189     break;
9190   }
9191   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9192                                     Op.getOperand(2), SDValue());
9193   SDValue Ops[] = { cpIn.getValue(0),
9194                     Op.getOperand(1),
9195                     Op.getOperand(3),
9196                     DAG.getTargetConstant(size, MVT::i8),
9197                     cpIn.getValue(1) };
9198   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9199   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9200   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9201                                            Ops, 5, T, MMO);
9202   SDValue cpOut =
9203     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9204   return cpOut;
9205 }
9206
9207 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9208                                                  SelectionDAG &DAG) const {
9209   assert(Subtarget->is64Bit() && "Result not type legalized?");
9210   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9211   SDValue TheChain = Op.getOperand(0);
9212   DebugLoc dl = Op.getDebugLoc();
9213   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9214   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9215   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9216                                    rax.getValue(2));
9217   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9218                             DAG.getConstant(32, MVT::i8));
9219   SDValue Ops[] = {
9220     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9221     rdx.getValue(1)
9222   };
9223   return DAG.getMergeValues(Ops, 2, dl);
9224 }
9225
9226 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9227                                             SelectionDAG &DAG) const {
9228   EVT SrcVT = Op.getOperand(0).getValueType();
9229   EVT DstVT = Op.getValueType();
9230   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9231          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9232   assert((DstVT == MVT::i64 ||
9233           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9234          "Unexpected custom BITCAST");
9235   // i64 <=> MMX conversions are Legal.
9236   if (SrcVT==MVT::i64 && DstVT.isVector())
9237     return Op;
9238   if (DstVT==MVT::i64 && SrcVT.isVector())
9239     return Op;
9240   // MMX <=> MMX conversions are Legal.
9241   if (SrcVT.isVector() && DstVT.isVector())
9242     return Op;
9243   // All other conversions need to be expanded.
9244   return SDValue();
9245 }
9246
9247 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9248   SDNode *Node = Op.getNode();
9249   DebugLoc dl = Node->getDebugLoc();
9250   EVT T = Node->getValueType(0);
9251   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9252                               DAG.getConstant(0, T), Node->getOperand(2));
9253   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9254                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9255                        Node->getOperand(0),
9256                        Node->getOperand(1), negOp,
9257                        cast<AtomicSDNode>(Node)->getSrcValue(),
9258                        cast<AtomicSDNode>(Node)->getAlignment());
9259 }
9260
9261 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9262   EVT VT = Op.getNode()->getValueType(0);
9263
9264   // Let legalize expand this if it isn't a legal type yet.
9265   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9266     return SDValue();
9267
9268   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9269
9270   unsigned Opc;
9271   bool ExtraOp = false;
9272   switch (Op.getOpcode()) {
9273   default: assert(0 && "Invalid code");
9274   case ISD::ADDC: Opc = X86ISD::ADD; break;
9275   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9276   case ISD::SUBC: Opc = X86ISD::SUB; break;
9277   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9278   }
9279
9280   if (!ExtraOp)
9281     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9282                        Op.getOperand(1));
9283   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9284                      Op.getOperand(1), Op.getOperand(2));
9285 }
9286
9287 /// LowerOperation - Provide custom lowering hooks for some operations.
9288 ///
9289 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9290   switch (Op.getOpcode()) {
9291   default: llvm_unreachable("Should not custom lower this!");
9292   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
9293   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9294   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9295   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9296   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9297   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9298   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9299   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9300   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9301   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9302   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9303   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9304   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9305   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9306   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9307   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9308   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9309   case ISD::SHL_PARTS:
9310   case ISD::SRA_PARTS:
9311   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9312   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9313   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9314   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9315   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9316   case ISD::FABS:               return LowerFABS(Op, DAG);
9317   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9318   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9319   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9320   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9321   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9322   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9323   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9324   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9325   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9326   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9327   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9328   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9329   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9330   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9331   case ISD::FRAME_TO_ARGS_OFFSET:
9332                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9333   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9334   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9335   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9336   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9337   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9338   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9339   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9340   case ISD::SRA:
9341   case ISD::SRL:
9342   case ISD::SHL:                return LowerShift(Op, DAG);
9343   case ISD::SADDO:
9344   case ISD::UADDO:
9345   case ISD::SSUBO:
9346   case ISD::USUBO:
9347   case ISD::SMULO:
9348   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9349   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9350   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9351   case ISD::ADDC:
9352   case ISD::ADDE:
9353   case ISD::SUBC:
9354   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9355   }
9356 }
9357
9358 void X86TargetLowering::
9359 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9360                         SelectionDAG &DAG, unsigned NewOp) const {
9361   EVT T = Node->getValueType(0);
9362   DebugLoc dl = Node->getDebugLoc();
9363   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9364
9365   SDValue Chain = Node->getOperand(0);
9366   SDValue In1 = Node->getOperand(1);
9367   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9368                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9369   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9370                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9371   SDValue Ops[] = { Chain, In1, In2L, In2H };
9372   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9373   SDValue Result =
9374     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9375                             cast<MemSDNode>(Node)->getMemOperand());
9376   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9377   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9378   Results.push_back(Result.getValue(2));
9379 }
9380
9381 /// ReplaceNodeResults - Replace a node with an illegal result type
9382 /// with a new node built out of custom code.
9383 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9384                                            SmallVectorImpl<SDValue>&Results,
9385                                            SelectionDAG &DAG) const {
9386   DebugLoc dl = N->getDebugLoc();
9387   switch (N->getOpcode()) {
9388   default:
9389     assert(false && "Do not know how to custom type legalize this operation!");
9390     return;
9391   case ISD::SIGN_EXTEND_INREG:
9392   case ISD::ADDC:
9393   case ISD::ADDE:
9394   case ISD::SUBC:
9395   case ISD::SUBE:
9396     // We don't want to expand or promote these.
9397     return;
9398   case ISD::FP_TO_SINT: {
9399     std::pair<SDValue,SDValue> Vals =
9400         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9401     SDValue FIST = Vals.first, StackSlot = Vals.second;
9402     if (FIST.getNode() != 0) {
9403       EVT VT = N->getValueType(0);
9404       // Return a load from the stack slot.
9405       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9406                                     MachinePointerInfo(), false, false, 0));
9407     }
9408     return;
9409   }
9410   case ISD::READCYCLECOUNTER: {
9411     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9412     SDValue TheChain = N->getOperand(0);
9413     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9414     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9415                                      rd.getValue(1));
9416     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9417                                      eax.getValue(2));
9418     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9419     SDValue Ops[] = { eax, edx };
9420     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9421     Results.push_back(edx.getValue(1));
9422     return;
9423   }
9424   case ISD::ATOMIC_CMP_SWAP: {
9425     EVT T = N->getValueType(0);
9426     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9427     SDValue cpInL, cpInH;
9428     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9429                         DAG.getConstant(0, MVT::i32));
9430     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9431                         DAG.getConstant(1, MVT::i32));
9432     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9433     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9434                              cpInL.getValue(1));
9435     SDValue swapInL, swapInH;
9436     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9437                           DAG.getConstant(0, MVT::i32));
9438     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9439                           DAG.getConstant(1, MVT::i32));
9440     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9441                                cpInH.getValue(1));
9442     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9443                                swapInL.getValue(1));
9444     SDValue Ops[] = { swapInH.getValue(0),
9445                       N->getOperand(1),
9446                       swapInH.getValue(1) };
9447     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9448     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9449     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9450                                              Ops, 3, T, MMO);
9451     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9452                                         MVT::i32, Result.getValue(1));
9453     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9454                                         MVT::i32, cpOutL.getValue(2));
9455     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9456     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9457     Results.push_back(cpOutH.getValue(1));
9458     return;
9459   }
9460   case ISD::ATOMIC_LOAD_ADD:
9461     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9462     return;
9463   case ISD::ATOMIC_LOAD_AND:
9464     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9465     return;
9466   case ISD::ATOMIC_LOAD_NAND:
9467     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9468     return;
9469   case ISD::ATOMIC_LOAD_OR:
9470     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9471     return;
9472   case ISD::ATOMIC_LOAD_SUB:
9473     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9474     return;
9475   case ISD::ATOMIC_LOAD_XOR:
9476     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9477     return;
9478   case ISD::ATOMIC_SWAP:
9479     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9480     return;
9481   }
9482 }
9483
9484 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9485   switch (Opcode) {
9486   default: return NULL;
9487   case X86ISD::BSF:                return "X86ISD::BSF";
9488   case X86ISD::BSR:                return "X86ISD::BSR";
9489   case X86ISD::SHLD:               return "X86ISD::SHLD";
9490   case X86ISD::SHRD:               return "X86ISD::SHRD";
9491   case X86ISD::FAND:               return "X86ISD::FAND";
9492   case X86ISD::FOR:                return "X86ISD::FOR";
9493   case X86ISD::FXOR:               return "X86ISD::FXOR";
9494   case X86ISD::FSRL:               return "X86ISD::FSRL";
9495   case X86ISD::FILD:               return "X86ISD::FILD";
9496   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9497   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9498   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9499   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9500   case X86ISD::FLD:                return "X86ISD::FLD";
9501   case X86ISD::FST:                return "X86ISD::FST";
9502   case X86ISD::CALL:               return "X86ISD::CALL";
9503   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9504   case X86ISD::BT:                 return "X86ISD::BT";
9505   case X86ISD::CMP:                return "X86ISD::CMP";
9506   case X86ISD::COMI:               return "X86ISD::COMI";
9507   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9508   case X86ISD::SETCC:              return "X86ISD::SETCC";
9509   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9510   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9511   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9512   case X86ISD::CMOV:               return "X86ISD::CMOV";
9513   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9514   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9515   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9516   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9517   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9518   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9519   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9520   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9521   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9522   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9523   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9524   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9525   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9526   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9527   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9528   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9529   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9530   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9531   case X86ISD::FMAX:               return "X86ISD::FMAX";
9532   case X86ISD::FMIN:               return "X86ISD::FMIN";
9533   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9534   case X86ISD::FRCP:               return "X86ISD::FRCP";
9535   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9536   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9537   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9538   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9539   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9540   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9541   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9542   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9543   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9544   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9545   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9546   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9547   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9548   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9549   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9550   case X86ISD::VSHL:               return "X86ISD::VSHL";
9551   case X86ISD::VSRL:               return "X86ISD::VSRL";
9552   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9553   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9554   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9555   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9556   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9557   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9558   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9559   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9560   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9561   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9562   case X86ISD::ADD:                return "X86ISD::ADD";
9563   case X86ISD::SUB:                return "X86ISD::SUB";
9564   case X86ISD::ADC:                return "X86ISD::ADC";
9565   case X86ISD::SBB:                return "X86ISD::SBB";
9566   case X86ISD::SMUL:               return "X86ISD::SMUL";
9567   case X86ISD::UMUL:               return "X86ISD::UMUL";
9568   case X86ISD::INC:                return "X86ISD::INC";
9569   case X86ISD::DEC:                return "X86ISD::DEC";
9570   case X86ISD::OR:                 return "X86ISD::OR";
9571   case X86ISD::XOR:                return "X86ISD::XOR";
9572   case X86ISD::AND:                return "X86ISD::AND";
9573   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9574   case X86ISD::PTEST:              return "X86ISD::PTEST";
9575   case X86ISD::TESTP:              return "X86ISD::TESTP";
9576   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9577   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9578   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9579   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9580   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9581   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9582   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9583   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9584   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9585   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9586   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9587   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9588   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9589   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9590   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9591   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9592   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9593   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9594   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9595   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9596   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9597   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9598   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9599   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9600   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9601   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9602   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9603   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9604   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9605   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9606   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9607   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9608   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9609   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9610   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9611   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9612   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9613   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9614   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9615   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9616   }
9617 }
9618
9619 // isLegalAddressingMode - Return true if the addressing mode represented
9620 // by AM is legal for this target, for a load/store of the specified type.
9621 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9622                                               const Type *Ty) const {
9623   // X86 supports extremely general addressing modes.
9624   CodeModel::Model M = getTargetMachine().getCodeModel();
9625   Reloc::Model R = getTargetMachine().getRelocationModel();
9626
9627   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9628   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9629     return false;
9630
9631   if (AM.BaseGV) {
9632     unsigned GVFlags =
9633       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9634
9635     // If a reference to this global requires an extra load, we can't fold it.
9636     if (isGlobalStubReference(GVFlags))
9637       return false;
9638
9639     // If BaseGV requires a register for the PIC base, we cannot also have a
9640     // BaseReg specified.
9641     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9642       return false;
9643
9644     // If lower 4G is not available, then we must use rip-relative addressing.
9645     if ((M != CodeModel::Small || R != Reloc::Static) &&
9646         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9647       return false;
9648   }
9649
9650   switch (AM.Scale) {
9651   case 0:
9652   case 1:
9653   case 2:
9654   case 4:
9655   case 8:
9656     // These scales always work.
9657     break;
9658   case 3:
9659   case 5:
9660   case 9:
9661     // These scales are formed with basereg+scalereg.  Only accept if there is
9662     // no basereg yet.
9663     if (AM.HasBaseReg)
9664       return false;
9665     break;
9666   default:  // Other stuff never works.
9667     return false;
9668   }
9669
9670   return true;
9671 }
9672
9673
9674 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9675   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9676     return false;
9677   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9678   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9679   if (NumBits1 <= NumBits2)
9680     return false;
9681   return true;
9682 }
9683
9684 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9685   if (!VT1.isInteger() || !VT2.isInteger())
9686     return false;
9687   unsigned NumBits1 = VT1.getSizeInBits();
9688   unsigned NumBits2 = VT2.getSizeInBits();
9689   if (NumBits1 <= NumBits2)
9690     return false;
9691   return true;
9692 }
9693
9694 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9695   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9696   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9697 }
9698
9699 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9700   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9701   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9702 }
9703
9704 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9705   // i16 instructions are longer (0x66 prefix) and potentially slower.
9706   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9707 }
9708
9709 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9710 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9711 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9712 /// are assumed to be legal.
9713 bool
9714 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9715                                       EVT VT) const {
9716   // Very little shuffling can be done for 64-bit vectors right now.
9717   if (VT.getSizeInBits() == 64)
9718     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9719
9720   // FIXME: pshufb, blends, shifts.
9721   return (VT.getVectorNumElements() == 2 ||
9722           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9723           isMOVLMask(M, VT) ||
9724           isSHUFPMask(M, VT) ||
9725           isPSHUFDMask(M, VT) ||
9726           isPSHUFHWMask(M, VT) ||
9727           isPSHUFLWMask(M, VT) ||
9728           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9729           isUNPCKLMask(M, VT) ||
9730           isUNPCKHMask(M, VT) ||
9731           isUNPCKL_v_undef_Mask(M, VT) ||
9732           isUNPCKH_v_undef_Mask(M, VT));
9733 }
9734
9735 bool
9736 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9737                                           EVT VT) const {
9738   unsigned NumElts = VT.getVectorNumElements();
9739   // FIXME: This collection of masks seems suspect.
9740   if (NumElts == 2)
9741     return true;
9742   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9743     return (isMOVLMask(Mask, VT)  ||
9744             isCommutedMOVLMask(Mask, VT, true) ||
9745             isSHUFPMask(Mask, VT) ||
9746             isCommutedSHUFPMask(Mask, VT));
9747   }
9748   return false;
9749 }
9750
9751 //===----------------------------------------------------------------------===//
9752 //                           X86 Scheduler Hooks
9753 //===----------------------------------------------------------------------===//
9754
9755 // private utility function
9756 MachineBasicBlock *
9757 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9758                                                        MachineBasicBlock *MBB,
9759                                                        unsigned regOpc,
9760                                                        unsigned immOpc,
9761                                                        unsigned LoadOpc,
9762                                                        unsigned CXchgOpc,
9763                                                        unsigned notOpc,
9764                                                        unsigned EAXreg,
9765                                                        TargetRegisterClass *RC,
9766                                                        bool invSrc) const {
9767   // For the atomic bitwise operator, we generate
9768   //   thisMBB:
9769   //   newMBB:
9770   //     ld  t1 = [bitinstr.addr]
9771   //     op  t2 = t1, [bitinstr.val]
9772   //     mov EAX = t1
9773   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9774   //     bz  newMBB
9775   //     fallthrough -->nextMBB
9776   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9777   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9778   MachineFunction::iterator MBBIter = MBB;
9779   ++MBBIter;
9780
9781   /// First build the CFG
9782   MachineFunction *F = MBB->getParent();
9783   MachineBasicBlock *thisMBB = MBB;
9784   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9785   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9786   F->insert(MBBIter, newMBB);
9787   F->insert(MBBIter, nextMBB);
9788
9789   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9790   nextMBB->splice(nextMBB->begin(), thisMBB,
9791                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9792                   thisMBB->end());
9793   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9794
9795   // Update thisMBB to fall through to newMBB
9796   thisMBB->addSuccessor(newMBB);
9797
9798   // newMBB jumps to itself and fall through to nextMBB
9799   newMBB->addSuccessor(nextMBB);
9800   newMBB->addSuccessor(newMBB);
9801
9802   // Insert instructions into newMBB based on incoming instruction
9803   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9804          "unexpected number of operands");
9805   DebugLoc dl = bInstr->getDebugLoc();
9806   MachineOperand& destOper = bInstr->getOperand(0);
9807   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9808   int numArgs = bInstr->getNumOperands() - 1;
9809   for (int i=0; i < numArgs; ++i)
9810     argOpers[i] = &bInstr->getOperand(i+1);
9811
9812   // x86 address has 4 operands: base, index, scale, and displacement
9813   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9814   int valArgIndx = lastAddrIndx + 1;
9815
9816   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9817   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9818   for (int i=0; i <= lastAddrIndx; ++i)
9819     (*MIB).addOperand(*argOpers[i]);
9820
9821   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9822   if (invSrc) {
9823     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9824   }
9825   else
9826     tt = t1;
9827
9828   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9829   assert((argOpers[valArgIndx]->isReg() ||
9830           argOpers[valArgIndx]->isImm()) &&
9831          "invalid operand");
9832   if (argOpers[valArgIndx]->isReg())
9833     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9834   else
9835     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9836   MIB.addReg(tt);
9837   (*MIB).addOperand(*argOpers[valArgIndx]);
9838
9839   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9840   MIB.addReg(t1);
9841
9842   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9843   for (int i=0; i <= lastAddrIndx; ++i)
9844     (*MIB).addOperand(*argOpers[i]);
9845   MIB.addReg(t2);
9846   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9847   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9848                     bInstr->memoperands_end());
9849
9850   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9851   MIB.addReg(EAXreg);
9852
9853   // insert branch
9854   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9855
9856   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9857   return nextMBB;
9858 }
9859
9860 // private utility function:  64 bit atomics on 32 bit host.
9861 MachineBasicBlock *
9862 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9863                                                        MachineBasicBlock *MBB,
9864                                                        unsigned regOpcL,
9865                                                        unsigned regOpcH,
9866                                                        unsigned immOpcL,
9867                                                        unsigned immOpcH,
9868                                                        bool invSrc) const {
9869   // For the atomic bitwise operator, we generate
9870   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9871   //     ld t1,t2 = [bitinstr.addr]
9872   //   newMBB:
9873   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9874   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9875   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9876   //     mov ECX, EBX <- t5, t6
9877   //     mov EAX, EDX <- t1, t2
9878   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9879   //     mov t3, t4 <- EAX, EDX
9880   //     bz  newMBB
9881   //     result in out1, out2
9882   //     fallthrough -->nextMBB
9883
9884   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9885   const unsigned LoadOpc = X86::MOV32rm;
9886   const unsigned NotOpc = X86::NOT32r;
9887   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9888   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9889   MachineFunction::iterator MBBIter = MBB;
9890   ++MBBIter;
9891
9892   /// First build the CFG
9893   MachineFunction *F = MBB->getParent();
9894   MachineBasicBlock *thisMBB = MBB;
9895   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9896   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9897   F->insert(MBBIter, newMBB);
9898   F->insert(MBBIter, nextMBB);
9899
9900   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9901   nextMBB->splice(nextMBB->begin(), thisMBB,
9902                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9903                   thisMBB->end());
9904   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9905
9906   // Update thisMBB to fall through to newMBB
9907   thisMBB->addSuccessor(newMBB);
9908
9909   // newMBB jumps to itself and fall through to nextMBB
9910   newMBB->addSuccessor(nextMBB);
9911   newMBB->addSuccessor(newMBB);
9912
9913   DebugLoc dl = bInstr->getDebugLoc();
9914   // Insert instructions into newMBB based on incoming instruction
9915   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9916   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9917          "unexpected number of operands");
9918   MachineOperand& dest1Oper = bInstr->getOperand(0);
9919   MachineOperand& dest2Oper = bInstr->getOperand(1);
9920   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9921   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9922     argOpers[i] = &bInstr->getOperand(i+2);
9923
9924     // We use some of the operands multiple times, so conservatively just
9925     // clear any kill flags that might be present.
9926     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9927       argOpers[i]->setIsKill(false);
9928   }
9929
9930   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9931   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9932
9933   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9934   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9935   for (int i=0; i <= lastAddrIndx; ++i)
9936     (*MIB).addOperand(*argOpers[i]);
9937   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9938   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9939   // add 4 to displacement.
9940   for (int i=0; i <= lastAddrIndx-2; ++i)
9941     (*MIB).addOperand(*argOpers[i]);
9942   MachineOperand newOp3 = *(argOpers[3]);
9943   if (newOp3.isImm())
9944     newOp3.setImm(newOp3.getImm()+4);
9945   else
9946     newOp3.setOffset(newOp3.getOffset()+4);
9947   (*MIB).addOperand(newOp3);
9948   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9949
9950   // t3/4 are defined later, at the bottom of the loop
9951   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9952   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9953   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9954     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9955   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9956     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9957
9958   // The subsequent operations should be using the destination registers of
9959   //the PHI instructions.
9960   if (invSrc) {
9961     t1 = F->getRegInfo().createVirtualRegister(RC);
9962     t2 = F->getRegInfo().createVirtualRegister(RC);
9963     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9964     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9965   } else {
9966     t1 = dest1Oper.getReg();
9967     t2 = dest2Oper.getReg();
9968   }
9969
9970   int valArgIndx = lastAddrIndx + 1;
9971   assert((argOpers[valArgIndx]->isReg() ||
9972           argOpers[valArgIndx]->isImm()) &&
9973          "invalid operand");
9974   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9975   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9976   if (argOpers[valArgIndx]->isReg())
9977     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9978   else
9979     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9980   if (regOpcL != X86::MOV32rr)
9981     MIB.addReg(t1);
9982   (*MIB).addOperand(*argOpers[valArgIndx]);
9983   assert(argOpers[valArgIndx + 1]->isReg() ==
9984          argOpers[valArgIndx]->isReg());
9985   assert(argOpers[valArgIndx + 1]->isImm() ==
9986          argOpers[valArgIndx]->isImm());
9987   if (argOpers[valArgIndx + 1]->isReg())
9988     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9989   else
9990     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9991   if (regOpcH != X86::MOV32rr)
9992     MIB.addReg(t2);
9993   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9994
9995   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9996   MIB.addReg(t1);
9997   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9998   MIB.addReg(t2);
9999
10000   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10001   MIB.addReg(t5);
10002   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10003   MIB.addReg(t6);
10004
10005   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10006   for (int i=0; i <= lastAddrIndx; ++i)
10007     (*MIB).addOperand(*argOpers[i]);
10008
10009   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10010   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10011                     bInstr->memoperands_end());
10012
10013   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10014   MIB.addReg(X86::EAX);
10015   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10016   MIB.addReg(X86::EDX);
10017
10018   // insert branch
10019   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10020
10021   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10022   return nextMBB;
10023 }
10024
10025 // private utility function
10026 MachineBasicBlock *
10027 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10028                                                       MachineBasicBlock *MBB,
10029                                                       unsigned cmovOpc) const {
10030   // For the atomic min/max operator, we generate
10031   //   thisMBB:
10032   //   newMBB:
10033   //     ld t1 = [min/max.addr]
10034   //     mov t2 = [min/max.val]
10035   //     cmp  t1, t2
10036   //     cmov[cond] t2 = t1
10037   //     mov EAX = t1
10038   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10039   //     bz   newMBB
10040   //     fallthrough -->nextMBB
10041   //
10042   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10043   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10044   MachineFunction::iterator MBBIter = MBB;
10045   ++MBBIter;
10046
10047   /// First build the CFG
10048   MachineFunction *F = MBB->getParent();
10049   MachineBasicBlock *thisMBB = MBB;
10050   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10051   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10052   F->insert(MBBIter, newMBB);
10053   F->insert(MBBIter, nextMBB);
10054
10055   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10056   nextMBB->splice(nextMBB->begin(), thisMBB,
10057                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10058                   thisMBB->end());
10059   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10060
10061   // Update thisMBB to fall through to newMBB
10062   thisMBB->addSuccessor(newMBB);
10063
10064   // newMBB jumps to newMBB and fall through to nextMBB
10065   newMBB->addSuccessor(nextMBB);
10066   newMBB->addSuccessor(newMBB);
10067
10068   DebugLoc dl = mInstr->getDebugLoc();
10069   // Insert instructions into newMBB based on incoming instruction
10070   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10071          "unexpected number of operands");
10072   MachineOperand& destOper = mInstr->getOperand(0);
10073   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10074   int numArgs = mInstr->getNumOperands() - 1;
10075   for (int i=0; i < numArgs; ++i)
10076     argOpers[i] = &mInstr->getOperand(i+1);
10077
10078   // x86 address has 4 operands: base, index, scale, and displacement
10079   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10080   int valArgIndx = lastAddrIndx + 1;
10081
10082   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10083   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10084   for (int i=0; i <= lastAddrIndx; ++i)
10085     (*MIB).addOperand(*argOpers[i]);
10086
10087   // We only support register and immediate values
10088   assert((argOpers[valArgIndx]->isReg() ||
10089           argOpers[valArgIndx]->isImm()) &&
10090          "invalid operand");
10091
10092   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10093   if (argOpers[valArgIndx]->isReg())
10094     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10095   else
10096     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10097   (*MIB).addOperand(*argOpers[valArgIndx]);
10098
10099   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10100   MIB.addReg(t1);
10101
10102   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10103   MIB.addReg(t1);
10104   MIB.addReg(t2);
10105
10106   // Generate movc
10107   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10108   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10109   MIB.addReg(t2);
10110   MIB.addReg(t1);
10111
10112   // Cmp and exchange if none has modified the memory location
10113   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10114   for (int i=0; i <= lastAddrIndx; ++i)
10115     (*MIB).addOperand(*argOpers[i]);
10116   MIB.addReg(t3);
10117   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10118   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10119                     mInstr->memoperands_end());
10120
10121   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10122   MIB.addReg(X86::EAX);
10123
10124   // insert branch
10125   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10126
10127   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10128   return nextMBB;
10129 }
10130
10131 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10132 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10133 // in the .td file.
10134 MachineBasicBlock *
10135 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10136                             unsigned numArgs, bool memArg) const {
10137   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10138          "Target must have SSE4.2 or AVX features enabled");
10139
10140   DebugLoc dl = MI->getDebugLoc();
10141   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10142   unsigned Opc;
10143   if (!Subtarget->hasAVX()) {
10144     if (memArg)
10145       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10146     else
10147       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10148   } else {
10149     if (memArg)
10150       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10151     else
10152       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10153   }
10154
10155   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10156   for (unsigned i = 0; i < numArgs; ++i) {
10157     MachineOperand &Op = MI->getOperand(i+1);
10158     if (!(Op.isReg() && Op.isImplicit()))
10159       MIB.addOperand(Op);
10160   }
10161   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10162     .addReg(X86::XMM0);
10163
10164   MI->eraseFromParent();
10165   return BB;
10166 }
10167
10168 MachineBasicBlock *
10169 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10170   DebugLoc dl = MI->getDebugLoc();
10171   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10172
10173   // Address into RAX/EAX, other two args into ECX, EDX.
10174   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10175   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10176   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10177   for (int i = 0; i < X86::AddrNumOperands; ++i)
10178     MIB.addOperand(MI->getOperand(i));
10179
10180   unsigned ValOps = X86::AddrNumOperands;
10181   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10182     .addReg(MI->getOperand(ValOps).getReg());
10183   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10184     .addReg(MI->getOperand(ValOps+1).getReg());
10185
10186   // The instruction doesn't actually take any operands though.
10187   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10188
10189   MI->eraseFromParent(); // The pseudo is gone now.
10190   return BB;
10191 }
10192
10193 MachineBasicBlock *
10194 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10195   DebugLoc dl = MI->getDebugLoc();
10196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10197
10198   // First arg in ECX, the second in EAX.
10199   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10200     .addReg(MI->getOperand(0).getReg());
10201   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10202     .addReg(MI->getOperand(1).getReg());
10203
10204   // The instruction doesn't actually take any operands though.
10205   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10206
10207   MI->eraseFromParent(); // The pseudo is gone now.
10208   return BB;
10209 }
10210
10211 MachineBasicBlock *
10212 X86TargetLowering::EmitVAARG64WithCustomInserter(
10213                    MachineInstr *MI,
10214                    MachineBasicBlock *MBB) const {
10215   // Emit va_arg instruction on X86-64.
10216
10217   // Operands to this pseudo-instruction:
10218   // 0  ) Output        : destination address (reg)
10219   // 1-5) Input         : va_list address (addr, i64mem)
10220   // 6  ) ArgSize       : Size (in bytes) of vararg type
10221   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10222   // 8  ) Align         : Alignment of type
10223   // 9  ) EFLAGS (implicit-def)
10224
10225   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10226   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10227
10228   unsigned DestReg = MI->getOperand(0).getReg();
10229   MachineOperand &Base = MI->getOperand(1);
10230   MachineOperand &Scale = MI->getOperand(2);
10231   MachineOperand &Index = MI->getOperand(3);
10232   MachineOperand &Disp = MI->getOperand(4);
10233   MachineOperand &Segment = MI->getOperand(5);
10234   unsigned ArgSize = MI->getOperand(6).getImm();
10235   unsigned ArgMode = MI->getOperand(7).getImm();
10236   unsigned Align = MI->getOperand(8).getImm();
10237
10238   // Memory Reference
10239   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10240   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10241   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10242
10243   // Machine Information
10244   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10245   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10246   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10247   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10248   DebugLoc DL = MI->getDebugLoc();
10249
10250   // struct va_list {
10251   //   i32   gp_offset
10252   //   i32   fp_offset
10253   //   i64   overflow_area (address)
10254   //   i64   reg_save_area (address)
10255   // }
10256   // sizeof(va_list) = 24
10257   // alignment(va_list) = 8
10258
10259   unsigned TotalNumIntRegs = 6;
10260   unsigned TotalNumXMMRegs = 8;
10261   bool UseGPOffset = (ArgMode == 1);
10262   bool UseFPOffset = (ArgMode == 2);
10263   unsigned MaxOffset = TotalNumIntRegs * 8 +
10264                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10265
10266   /* Align ArgSize to a multiple of 8 */
10267   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10268   bool NeedsAlign = (Align > 8);
10269
10270   MachineBasicBlock *thisMBB = MBB;
10271   MachineBasicBlock *overflowMBB;
10272   MachineBasicBlock *offsetMBB;
10273   MachineBasicBlock *endMBB;
10274
10275   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10276   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10277   unsigned OffsetReg = 0;
10278
10279   if (!UseGPOffset && !UseFPOffset) {
10280     // If we only pull from the overflow region, we don't create a branch.
10281     // We don't need to alter control flow.
10282     OffsetDestReg = 0; // unused
10283     OverflowDestReg = DestReg;
10284
10285     offsetMBB = NULL;
10286     overflowMBB = thisMBB;
10287     endMBB = thisMBB;
10288   } else {
10289     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10290     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10291     // If not, pull from overflow_area. (branch to overflowMBB)
10292     //
10293     //       thisMBB
10294     //         |     .
10295     //         |        .
10296     //     offsetMBB   overflowMBB
10297     //         |        .
10298     //         |     .
10299     //        endMBB
10300
10301     // Registers for the PHI in endMBB
10302     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10303     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10304
10305     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10306     MachineFunction *MF = MBB->getParent();
10307     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10308     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10309     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10310
10311     MachineFunction::iterator MBBIter = MBB;
10312     ++MBBIter;
10313
10314     // Insert the new basic blocks
10315     MF->insert(MBBIter, offsetMBB);
10316     MF->insert(MBBIter, overflowMBB);
10317     MF->insert(MBBIter, endMBB);
10318
10319     // Transfer the remainder of MBB and its successor edges to endMBB.
10320     endMBB->splice(endMBB->begin(), thisMBB,
10321                     llvm::next(MachineBasicBlock::iterator(MI)),
10322                     thisMBB->end());
10323     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10324
10325     // Make offsetMBB and overflowMBB successors of thisMBB
10326     thisMBB->addSuccessor(offsetMBB);
10327     thisMBB->addSuccessor(overflowMBB);
10328
10329     // endMBB is a successor of both offsetMBB and overflowMBB
10330     offsetMBB->addSuccessor(endMBB);
10331     overflowMBB->addSuccessor(endMBB);
10332
10333     // Load the offset value into a register
10334     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10335     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10336       .addOperand(Base)
10337       .addOperand(Scale)
10338       .addOperand(Index)
10339       .addDisp(Disp, UseFPOffset ? 4 : 0)
10340       .addOperand(Segment)
10341       .setMemRefs(MMOBegin, MMOEnd);
10342
10343     // Check if there is enough room left to pull this argument.
10344     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10345       .addReg(OffsetReg)
10346       .addImm(MaxOffset + 8 - ArgSizeA8);
10347
10348     // Branch to "overflowMBB" if offset >= max
10349     // Fall through to "offsetMBB" otherwise
10350     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10351       .addMBB(overflowMBB);
10352   }
10353
10354   // In offsetMBB, emit code to use the reg_save_area.
10355   if (offsetMBB) {
10356     assert(OffsetReg != 0);
10357
10358     // Read the reg_save_area address.
10359     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10360     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10361       .addOperand(Base)
10362       .addOperand(Scale)
10363       .addOperand(Index)
10364       .addDisp(Disp, 16)
10365       .addOperand(Segment)
10366       .setMemRefs(MMOBegin, MMOEnd);
10367
10368     // Zero-extend the offset
10369     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10370       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10371         .addImm(0)
10372         .addReg(OffsetReg)
10373         .addImm(X86::sub_32bit);
10374
10375     // Add the offset to the reg_save_area to get the final address.
10376     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10377       .addReg(OffsetReg64)
10378       .addReg(RegSaveReg);
10379
10380     // Compute the offset for the next argument
10381     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10382     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10383       .addReg(OffsetReg)
10384       .addImm(UseFPOffset ? 16 : 8);
10385
10386     // Store it back into the va_list.
10387     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10388       .addOperand(Base)
10389       .addOperand(Scale)
10390       .addOperand(Index)
10391       .addDisp(Disp, UseFPOffset ? 4 : 0)
10392       .addOperand(Segment)
10393       .addReg(NextOffsetReg)
10394       .setMemRefs(MMOBegin, MMOEnd);
10395
10396     // Jump to endMBB
10397     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10398       .addMBB(endMBB);
10399   }
10400
10401   //
10402   // Emit code to use overflow area
10403   //
10404
10405   // Load the overflow_area address into a register.
10406   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10407   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10408     .addOperand(Base)
10409     .addOperand(Scale)
10410     .addOperand(Index)
10411     .addDisp(Disp, 8)
10412     .addOperand(Segment)
10413     .setMemRefs(MMOBegin, MMOEnd);
10414
10415   // If we need to align it, do so. Otherwise, just copy the address
10416   // to OverflowDestReg.
10417   if (NeedsAlign) {
10418     // Align the overflow address
10419     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10420     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10421
10422     // aligned_addr = (addr + (align-1)) & ~(align-1)
10423     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10424       .addReg(OverflowAddrReg)
10425       .addImm(Align-1);
10426
10427     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10428       .addReg(TmpReg)
10429       .addImm(~(uint64_t)(Align-1));
10430   } else {
10431     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10432       .addReg(OverflowAddrReg);
10433   }
10434
10435   // Compute the next overflow address after this argument.
10436   // (the overflow address should be kept 8-byte aligned)
10437   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10438   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10439     .addReg(OverflowDestReg)
10440     .addImm(ArgSizeA8);
10441
10442   // Store the new overflow address.
10443   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10444     .addOperand(Base)
10445     .addOperand(Scale)
10446     .addOperand(Index)
10447     .addDisp(Disp, 8)
10448     .addOperand(Segment)
10449     .addReg(NextAddrReg)
10450     .setMemRefs(MMOBegin, MMOEnd);
10451
10452   // If we branched, emit the PHI to the front of endMBB.
10453   if (offsetMBB) {
10454     BuildMI(*endMBB, endMBB->begin(), DL,
10455             TII->get(X86::PHI), DestReg)
10456       .addReg(OffsetDestReg).addMBB(offsetMBB)
10457       .addReg(OverflowDestReg).addMBB(overflowMBB);
10458   }
10459
10460   // Erase the pseudo instruction
10461   MI->eraseFromParent();
10462
10463   return endMBB;
10464 }
10465
10466 MachineBasicBlock *
10467 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10468                                                  MachineInstr *MI,
10469                                                  MachineBasicBlock *MBB) const {
10470   // Emit code to save XMM registers to the stack. The ABI says that the
10471   // number of registers to save is given in %al, so it's theoretically
10472   // possible to do an indirect jump trick to avoid saving all of them,
10473   // however this code takes a simpler approach and just executes all
10474   // of the stores if %al is non-zero. It's less code, and it's probably
10475   // easier on the hardware branch predictor, and stores aren't all that
10476   // expensive anyway.
10477
10478   // Create the new basic blocks. One block contains all the XMM stores,
10479   // and one block is the final destination regardless of whether any
10480   // stores were performed.
10481   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10482   MachineFunction *F = MBB->getParent();
10483   MachineFunction::iterator MBBIter = MBB;
10484   ++MBBIter;
10485   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10486   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10487   F->insert(MBBIter, XMMSaveMBB);
10488   F->insert(MBBIter, EndMBB);
10489
10490   // Transfer the remainder of MBB and its successor edges to EndMBB.
10491   EndMBB->splice(EndMBB->begin(), MBB,
10492                  llvm::next(MachineBasicBlock::iterator(MI)),
10493                  MBB->end());
10494   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10495
10496   // The original block will now fall through to the XMM save block.
10497   MBB->addSuccessor(XMMSaveMBB);
10498   // The XMMSaveMBB will fall through to the end block.
10499   XMMSaveMBB->addSuccessor(EndMBB);
10500
10501   // Now add the instructions.
10502   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10503   DebugLoc DL = MI->getDebugLoc();
10504
10505   unsigned CountReg = MI->getOperand(0).getReg();
10506   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10507   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10508
10509   if (!Subtarget->isTargetWin64()) {
10510     // If %al is 0, branch around the XMM save block.
10511     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10512     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10513     MBB->addSuccessor(EndMBB);
10514   }
10515
10516   // In the XMM save block, save all the XMM argument registers.
10517   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10518     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10519     MachineMemOperand *MMO =
10520       F->getMachineMemOperand(
10521           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10522         MachineMemOperand::MOStore,
10523         /*Size=*/16, /*Align=*/16);
10524     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10525       .addFrameIndex(RegSaveFrameIndex)
10526       .addImm(/*Scale=*/1)
10527       .addReg(/*IndexReg=*/0)
10528       .addImm(/*Disp=*/Offset)
10529       .addReg(/*Segment=*/0)
10530       .addReg(MI->getOperand(i).getReg())
10531       .addMemOperand(MMO);
10532   }
10533
10534   MI->eraseFromParent();   // The pseudo instruction is gone now.
10535
10536   return EndMBB;
10537 }
10538
10539 MachineBasicBlock *
10540 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10541                                      MachineBasicBlock *BB) const {
10542   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10543   DebugLoc DL = MI->getDebugLoc();
10544
10545   // To "insert" a SELECT_CC instruction, we actually have to insert the
10546   // diamond control-flow pattern.  The incoming instruction knows the
10547   // destination vreg to set, the condition code register to branch on, the
10548   // true/false values to select between, and a branch opcode to use.
10549   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10550   MachineFunction::iterator It = BB;
10551   ++It;
10552
10553   //  thisMBB:
10554   //  ...
10555   //   TrueVal = ...
10556   //   cmpTY ccX, r1, r2
10557   //   bCC copy1MBB
10558   //   fallthrough --> copy0MBB
10559   MachineBasicBlock *thisMBB = BB;
10560   MachineFunction *F = BB->getParent();
10561   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10562   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10563   F->insert(It, copy0MBB);
10564   F->insert(It, sinkMBB);
10565
10566   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10567   // live into the sink and copy blocks.
10568   const MachineFunction *MF = BB->getParent();
10569   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10570   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10571
10572   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10573     const MachineOperand &MO = MI->getOperand(I);
10574     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10575     unsigned Reg = MO.getReg();
10576     if (Reg != X86::EFLAGS) continue;
10577     copy0MBB->addLiveIn(Reg);
10578     sinkMBB->addLiveIn(Reg);
10579   }
10580
10581   // Transfer the remainder of BB and its successor edges to sinkMBB.
10582   sinkMBB->splice(sinkMBB->begin(), BB,
10583                   llvm::next(MachineBasicBlock::iterator(MI)),
10584                   BB->end());
10585   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10586
10587   // Add the true and fallthrough blocks as its successors.
10588   BB->addSuccessor(copy0MBB);
10589   BB->addSuccessor(sinkMBB);
10590
10591   // Create the conditional branch instruction.
10592   unsigned Opc =
10593     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10594   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10595
10596   //  copy0MBB:
10597   //   %FalseValue = ...
10598   //   # fallthrough to sinkMBB
10599   copy0MBB->addSuccessor(sinkMBB);
10600
10601   //  sinkMBB:
10602   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10603   //  ...
10604   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10605           TII->get(X86::PHI), MI->getOperand(0).getReg())
10606     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10607     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10608
10609   MI->eraseFromParent();   // The pseudo instruction is gone now.
10610   return sinkMBB;
10611 }
10612
10613 MachineBasicBlock *
10614 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10615                                           MachineBasicBlock *BB) const {
10616   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10617   DebugLoc DL = MI->getDebugLoc();
10618
10619   assert(!Subtarget->isTargetEnvMacho());
10620
10621   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10622   // non-trivial part is impdef of ESP.
10623
10624   if (Subtarget->isTargetWin64()) {
10625     if (Subtarget->isTargetCygMing()) {
10626       // ___chkstk(Mingw64):
10627       // Clobbers R10, R11, RAX and EFLAGS.
10628       // Updates RSP.
10629       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10630         .addExternalSymbol("___chkstk")
10631         .addReg(X86::RAX, RegState::Implicit)
10632         .addReg(X86::RSP, RegState::Implicit)
10633         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10634         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10635         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10636     } else {
10637       // __chkstk(MSVCRT): does not update stack pointer.
10638       // Clobbers R10, R11 and EFLAGS.
10639       // FIXME: RAX(allocated size) might be reused and not killed.
10640       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10641         .addExternalSymbol("__chkstk")
10642         .addReg(X86::RAX, RegState::Implicit)
10643         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10644       // RAX has the offset to subtracted from RSP.
10645       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10646         .addReg(X86::RSP)
10647         .addReg(X86::RAX);
10648     }
10649   } else {
10650     const char *StackProbeSymbol =
10651       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10652
10653     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10654       .addExternalSymbol(StackProbeSymbol)
10655       .addReg(X86::EAX, RegState::Implicit)
10656       .addReg(X86::ESP, RegState::Implicit)
10657       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10658       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10659       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10660   }
10661
10662   MI->eraseFromParent();   // The pseudo instruction is gone now.
10663   return BB;
10664 }
10665
10666 MachineBasicBlock *
10667 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10668                                       MachineBasicBlock *BB) const {
10669   // This is pretty easy.  We're taking the value that we received from
10670   // our load from the relocation, sticking it in either RDI (x86-64)
10671   // or EAX and doing an indirect call.  The return value will then
10672   // be in the normal return register.
10673   const X86InstrInfo *TII
10674     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10675   DebugLoc DL = MI->getDebugLoc();
10676   MachineFunction *F = BB->getParent();
10677
10678   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10679   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10680
10681   if (Subtarget->is64Bit()) {
10682     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10683                                       TII->get(X86::MOV64rm), X86::RDI)
10684     .addReg(X86::RIP)
10685     .addImm(0).addReg(0)
10686     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10687                       MI->getOperand(3).getTargetFlags())
10688     .addReg(0);
10689     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10690     addDirectMem(MIB, X86::RDI);
10691   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10692     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10693                                       TII->get(X86::MOV32rm), X86::EAX)
10694     .addReg(0)
10695     .addImm(0).addReg(0)
10696     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10697                       MI->getOperand(3).getTargetFlags())
10698     .addReg(0);
10699     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10700     addDirectMem(MIB, X86::EAX);
10701   } else {
10702     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10703                                       TII->get(X86::MOV32rm), X86::EAX)
10704     .addReg(TII->getGlobalBaseReg(F))
10705     .addImm(0).addReg(0)
10706     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10707                       MI->getOperand(3).getTargetFlags())
10708     .addReg(0);
10709     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10710     addDirectMem(MIB, X86::EAX);
10711   }
10712
10713   MI->eraseFromParent(); // The pseudo instruction is gone now.
10714   return BB;
10715 }
10716
10717 MachineBasicBlock *
10718 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10719                                                MachineBasicBlock *BB) const {
10720   switch (MI->getOpcode()) {
10721   default: assert(false && "Unexpected instr type to insert");
10722   case X86::TAILJMPd64:
10723   case X86::TAILJMPr64:
10724   case X86::TAILJMPm64:
10725     assert(!"TAILJMP64 would not be touched here.");
10726   case X86::TCRETURNdi64:
10727   case X86::TCRETURNri64:
10728   case X86::TCRETURNmi64:
10729     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10730     // On AMD64, additional defs should be added before register allocation.
10731     if (!Subtarget->isTargetWin64()) {
10732       MI->addRegisterDefined(X86::RSI);
10733       MI->addRegisterDefined(X86::RDI);
10734       MI->addRegisterDefined(X86::XMM6);
10735       MI->addRegisterDefined(X86::XMM7);
10736       MI->addRegisterDefined(X86::XMM8);
10737       MI->addRegisterDefined(X86::XMM9);
10738       MI->addRegisterDefined(X86::XMM10);
10739       MI->addRegisterDefined(X86::XMM11);
10740       MI->addRegisterDefined(X86::XMM12);
10741       MI->addRegisterDefined(X86::XMM13);
10742       MI->addRegisterDefined(X86::XMM14);
10743       MI->addRegisterDefined(X86::XMM15);
10744     }
10745     return BB;
10746   case X86::WIN_ALLOCA:
10747     return EmitLoweredWinAlloca(MI, BB);
10748   case X86::TLSCall_32:
10749   case X86::TLSCall_64:
10750     return EmitLoweredTLSCall(MI, BB);
10751   case X86::CMOV_GR8:
10752   case X86::CMOV_FR32:
10753   case X86::CMOV_FR64:
10754   case X86::CMOV_V4F32:
10755   case X86::CMOV_V2F64:
10756   case X86::CMOV_V2I64:
10757   case X86::CMOV_GR16:
10758   case X86::CMOV_GR32:
10759   case X86::CMOV_RFP32:
10760   case X86::CMOV_RFP64:
10761   case X86::CMOV_RFP80:
10762     return EmitLoweredSelect(MI, BB);
10763
10764   case X86::FP32_TO_INT16_IN_MEM:
10765   case X86::FP32_TO_INT32_IN_MEM:
10766   case X86::FP32_TO_INT64_IN_MEM:
10767   case X86::FP64_TO_INT16_IN_MEM:
10768   case X86::FP64_TO_INT32_IN_MEM:
10769   case X86::FP64_TO_INT64_IN_MEM:
10770   case X86::FP80_TO_INT16_IN_MEM:
10771   case X86::FP80_TO_INT32_IN_MEM:
10772   case X86::FP80_TO_INT64_IN_MEM: {
10773     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10774     DebugLoc DL = MI->getDebugLoc();
10775
10776     // Change the floating point control register to use "round towards zero"
10777     // mode when truncating to an integer value.
10778     MachineFunction *F = BB->getParent();
10779     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10780     addFrameReference(BuildMI(*BB, MI, DL,
10781                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10782
10783     // Load the old value of the high byte of the control word...
10784     unsigned OldCW =
10785       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10786     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10787                       CWFrameIdx);
10788
10789     // Set the high part to be round to zero...
10790     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10791       .addImm(0xC7F);
10792
10793     // Reload the modified control word now...
10794     addFrameReference(BuildMI(*BB, MI, DL,
10795                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10796
10797     // Restore the memory image of control word to original value
10798     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10799       .addReg(OldCW);
10800
10801     // Get the X86 opcode to use.
10802     unsigned Opc;
10803     switch (MI->getOpcode()) {
10804     default: llvm_unreachable("illegal opcode!");
10805     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10806     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10807     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10808     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10809     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10810     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10811     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10812     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10813     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10814     }
10815
10816     X86AddressMode AM;
10817     MachineOperand &Op = MI->getOperand(0);
10818     if (Op.isReg()) {
10819       AM.BaseType = X86AddressMode::RegBase;
10820       AM.Base.Reg = Op.getReg();
10821     } else {
10822       AM.BaseType = X86AddressMode::FrameIndexBase;
10823       AM.Base.FrameIndex = Op.getIndex();
10824     }
10825     Op = MI->getOperand(1);
10826     if (Op.isImm())
10827       AM.Scale = Op.getImm();
10828     Op = MI->getOperand(2);
10829     if (Op.isImm())
10830       AM.IndexReg = Op.getImm();
10831     Op = MI->getOperand(3);
10832     if (Op.isGlobal()) {
10833       AM.GV = Op.getGlobal();
10834     } else {
10835       AM.Disp = Op.getImm();
10836     }
10837     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10838                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10839
10840     // Reload the original control word now.
10841     addFrameReference(BuildMI(*BB, MI, DL,
10842                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10843
10844     MI->eraseFromParent();   // The pseudo instruction is gone now.
10845     return BB;
10846   }
10847     // String/text processing lowering.
10848   case X86::PCMPISTRM128REG:
10849   case X86::VPCMPISTRM128REG:
10850     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10851   case X86::PCMPISTRM128MEM:
10852   case X86::VPCMPISTRM128MEM:
10853     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10854   case X86::PCMPESTRM128REG:
10855   case X86::VPCMPESTRM128REG:
10856     return EmitPCMP(MI, BB, 5, false /* in mem */);
10857   case X86::PCMPESTRM128MEM:
10858   case X86::VPCMPESTRM128MEM:
10859     return EmitPCMP(MI, BB, 5, true /* in mem */);
10860
10861     // Thread synchronization.
10862   case X86::MONITOR:
10863     return EmitMonitor(MI, BB);
10864   case X86::MWAIT:
10865     return EmitMwait(MI, BB);
10866
10867     // Atomic Lowering.
10868   case X86::ATOMAND32:
10869     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10870                                                X86::AND32ri, X86::MOV32rm,
10871                                                X86::LCMPXCHG32,
10872                                                X86::NOT32r, X86::EAX,
10873                                                X86::GR32RegisterClass);
10874   case X86::ATOMOR32:
10875     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10876                                                X86::OR32ri, X86::MOV32rm,
10877                                                X86::LCMPXCHG32,
10878                                                X86::NOT32r, X86::EAX,
10879                                                X86::GR32RegisterClass);
10880   case X86::ATOMXOR32:
10881     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10882                                                X86::XOR32ri, X86::MOV32rm,
10883                                                X86::LCMPXCHG32,
10884                                                X86::NOT32r, X86::EAX,
10885                                                X86::GR32RegisterClass);
10886   case X86::ATOMNAND32:
10887     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10888                                                X86::AND32ri, X86::MOV32rm,
10889                                                X86::LCMPXCHG32,
10890                                                X86::NOT32r, X86::EAX,
10891                                                X86::GR32RegisterClass, true);
10892   case X86::ATOMMIN32:
10893     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10894   case X86::ATOMMAX32:
10895     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10896   case X86::ATOMUMIN32:
10897     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10898   case X86::ATOMUMAX32:
10899     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10900
10901   case X86::ATOMAND16:
10902     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10903                                                X86::AND16ri, X86::MOV16rm,
10904                                                X86::LCMPXCHG16,
10905                                                X86::NOT16r, X86::AX,
10906                                                X86::GR16RegisterClass);
10907   case X86::ATOMOR16:
10908     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10909                                                X86::OR16ri, X86::MOV16rm,
10910                                                X86::LCMPXCHG16,
10911                                                X86::NOT16r, X86::AX,
10912                                                X86::GR16RegisterClass);
10913   case X86::ATOMXOR16:
10914     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10915                                                X86::XOR16ri, X86::MOV16rm,
10916                                                X86::LCMPXCHG16,
10917                                                X86::NOT16r, X86::AX,
10918                                                X86::GR16RegisterClass);
10919   case X86::ATOMNAND16:
10920     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10921                                                X86::AND16ri, X86::MOV16rm,
10922                                                X86::LCMPXCHG16,
10923                                                X86::NOT16r, X86::AX,
10924                                                X86::GR16RegisterClass, true);
10925   case X86::ATOMMIN16:
10926     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10927   case X86::ATOMMAX16:
10928     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10929   case X86::ATOMUMIN16:
10930     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10931   case X86::ATOMUMAX16:
10932     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10933
10934   case X86::ATOMAND8:
10935     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10936                                                X86::AND8ri, X86::MOV8rm,
10937                                                X86::LCMPXCHG8,
10938                                                X86::NOT8r, X86::AL,
10939                                                X86::GR8RegisterClass);
10940   case X86::ATOMOR8:
10941     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10942                                                X86::OR8ri, X86::MOV8rm,
10943                                                X86::LCMPXCHG8,
10944                                                X86::NOT8r, X86::AL,
10945                                                X86::GR8RegisterClass);
10946   case X86::ATOMXOR8:
10947     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10948                                                X86::XOR8ri, X86::MOV8rm,
10949                                                X86::LCMPXCHG8,
10950                                                X86::NOT8r, X86::AL,
10951                                                X86::GR8RegisterClass);
10952   case X86::ATOMNAND8:
10953     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10954                                                X86::AND8ri, X86::MOV8rm,
10955                                                X86::LCMPXCHG8,
10956                                                X86::NOT8r, X86::AL,
10957                                                X86::GR8RegisterClass, true);
10958   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10959   // This group is for 64-bit host.
10960   case X86::ATOMAND64:
10961     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10962                                                X86::AND64ri32, X86::MOV64rm,
10963                                                X86::LCMPXCHG64,
10964                                                X86::NOT64r, X86::RAX,
10965                                                X86::GR64RegisterClass);
10966   case X86::ATOMOR64:
10967     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10968                                                X86::OR64ri32, X86::MOV64rm,
10969                                                X86::LCMPXCHG64,
10970                                                X86::NOT64r, X86::RAX,
10971                                                X86::GR64RegisterClass);
10972   case X86::ATOMXOR64:
10973     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10974                                                X86::XOR64ri32, X86::MOV64rm,
10975                                                X86::LCMPXCHG64,
10976                                                X86::NOT64r, X86::RAX,
10977                                                X86::GR64RegisterClass);
10978   case X86::ATOMNAND64:
10979     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10980                                                X86::AND64ri32, X86::MOV64rm,
10981                                                X86::LCMPXCHG64,
10982                                                X86::NOT64r, X86::RAX,
10983                                                X86::GR64RegisterClass, true);
10984   case X86::ATOMMIN64:
10985     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10986   case X86::ATOMMAX64:
10987     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10988   case X86::ATOMUMIN64:
10989     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10990   case X86::ATOMUMAX64:
10991     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10992
10993   // This group does 64-bit operations on a 32-bit host.
10994   case X86::ATOMAND6432:
10995     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10996                                                X86::AND32rr, X86::AND32rr,
10997                                                X86::AND32ri, X86::AND32ri,
10998                                                false);
10999   case X86::ATOMOR6432:
11000     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11001                                                X86::OR32rr, X86::OR32rr,
11002                                                X86::OR32ri, X86::OR32ri,
11003                                                false);
11004   case X86::ATOMXOR6432:
11005     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11006                                                X86::XOR32rr, X86::XOR32rr,
11007                                                X86::XOR32ri, X86::XOR32ri,
11008                                                false);
11009   case X86::ATOMNAND6432:
11010     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11011                                                X86::AND32rr, X86::AND32rr,
11012                                                X86::AND32ri, X86::AND32ri,
11013                                                true);
11014   case X86::ATOMADD6432:
11015     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11016                                                X86::ADD32rr, X86::ADC32rr,
11017                                                X86::ADD32ri, X86::ADC32ri,
11018                                                false);
11019   case X86::ATOMSUB6432:
11020     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11021                                                X86::SUB32rr, X86::SBB32rr,
11022                                                X86::SUB32ri, X86::SBB32ri,
11023                                                false);
11024   case X86::ATOMSWAP6432:
11025     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11026                                                X86::MOV32rr, X86::MOV32rr,
11027                                                X86::MOV32ri, X86::MOV32ri,
11028                                                false);
11029   case X86::VASTART_SAVE_XMM_REGS:
11030     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11031
11032   case X86::VAARG_64:
11033     return EmitVAARG64WithCustomInserter(MI, BB);
11034   }
11035 }
11036
11037 //===----------------------------------------------------------------------===//
11038 //                           X86 Optimization Hooks
11039 //===----------------------------------------------------------------------===//
11040
11041 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11042                                                        const APInt &Mask,
11043                                                        APInt &KnownZero,
11044                                                        APInt &KnownOne,
11045                                                        const SelectionDAG &DAG,
11046                                                        unsigned Depth) const {
11047   unsigned Opc = Op.getOpcode();
11048   assert((Opc >= ISD::BUILTIN_OP_END ||
11049           Opc == ISD::INTRINSIC_WO_CHAIN ||
11050           Opc == ISD::INTRINSIC_W_CHAIN ||
11051           Opc == ISD::INTRINSIC_VOID) &&
11052          "Should use MaskedValueIsZero if you don't know whether Op"
11053          " is a target node!");
11054
11055   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11056   switch (Opc) {
11057   default: break;
11058   case X86ISD::ADD:
11059   case X86ISD::SUB:
11060   case X86ISD::ADC:
11061   case X86ISD::SBB:
11062   case X86ISD::SMUL:
11063   case X86ISD::UMUL:
11064   case X86ISD::INC:
11065   case X86ISD::DEC:
11066   case X86ISD::OR:
11067   case X86ISD::XOR:
11068   case X86ISD::AND:
11069     // These nodes' second result is a boolean.
11070     if (Op.getResNo() == 0)
11071       break;
11072     // Fallthrough
11073   case X86ISD::SETCC:
11074     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11075                                        Mask.getBitWidth() - 1);
11076     break;
11077   }
11078 }
11079
11080 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11081                                                          unsigned Depth) const {
11082   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11083   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11084     return Op.getValueType().getScalarType().getSizeInBits();
11085
11086   // Fallback case.
11087   return 1;
11088 }
11089
11090 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11091 /// node is a GlobalAddress + offset.
11092 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11093                                        const GlobalValue* &GA,
11094                                        int64_t &Offset) const {
11095   if (N->getOpcode() == X86ISD::Wrapper) {
11096     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11097       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11098       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11099       return true;
11100     }
11101   }
11102   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11103 }
11104
11105 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11106 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11107 /// if the load addresses are consecutive, non-overlapping, and in the right
11108 /// order.
11109 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11110                                      TargetLowering::DAGCombinerInfo &DCI) {
11111   DebugLoc dl = N->getDebugLoc();
11112   EVT VT = N->getValueType(0);
11113
11114   if (VT.getSizeInBits() != 128)
11115     return SDValue();
11116
11117   // Don't create instructions with illegal types after legalize types has run.
11118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11119   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11120     return SDValue();
11121
11122   SmallVector<SDValue, 16> Elts;
11123   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11124     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11125
11126   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11127 }
11128
11129 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11130 /// generation and convert it from being a bunch of shuffles and extracts
11131 /// to a simple store and scalar loads to extract the elements.
11132 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11133                                                 const TargetLowering &TLI) {
11134   SDValue InputVector = N->getOperand(0);
11135
11136   // Only operate on vectors of 4 elements, where the alternative shuffling
11137   // gets to be more expensive.
11138   if (InputVector.getValueType() != MVT::v4i32)
11139     return SDValue();
11140
11141   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11142   // single use which is a sign-extend or zero-extend, and all elements are
11143   // used.
11144   SmallVector<SDNode *, 4> Uses;
11145   unsigned ExtractedElements = 0;
11146   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11147        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11148     if (UI.getUse().getResNo() != InputVector.getResNo())
11149       return SDValue();
11150
11151     SDNode *Extract = *UI;
11152     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11153       return SDValue();
11154
11155     if (Extract->getValueType(0) != MVT::i32)
11156       return SDValue();
11157     if (!Extract->hasOneUse())
11158       return SDValue();
11159     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11160         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11161       return SDValue();
11162     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11163       return SDValue();
11164
11165     // Record which element was extracted.
11166     ExtractedElements |=
11167       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11168
11169     Uses.push_back(Extract);
11170   }
11171
11172   // If not all the elements were used, this may not be worthwhile.
11173   if (ExtractedElements != 15)
11174     return SDValue();
11175
11176   // Ok, we've now decided to do the transformation.
11177   DebugLoc dl = InputVector.getDebugLoc();
11178
11179   // Store the value to a temporary stack slot.
11180   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11181   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11182                             MachinePointerInfo(), false, false, 0);
11183
11184   // Replace each use (extract) with a load of the appropriate element.
11185   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11186        UE = Uses.end(); UI != UE; ++UI) {
11187     SDNode *Extract = *UI;
11188
11189     // cOMpute the element's address.
11190     SDValue Idx = Extract->getOperand(1);
11191     unsigned EltSize =
11192         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11193     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11194     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11195
11196     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11197                                      StackPtr, OffsetVal);
11198
11199     // Load the scalar.
11200     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11201                                      ScalarAddr, MachinePointerInfo(),
11202                                      false, false, 0);
11203
11204     // Replace the exact with the load.
11205     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11206   }
11207
11208   // The replacement was made in place; don't return anything.
11209   return SDValue();
11210 }
11211
11212 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11213 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11214                                     const X86Subtarget *Subtarget) {
11215   DebugLoc DL = N->getDebugLoc();
11216   SDValue Cond = N->getOperand(0);
11217   // Get the LHS/RHS of the select.
11218   SDValue LHS = N->getOperand(1);
11219   SDValue RHS = N->getOperand(2);
11220
11221   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11222   // instructions match the semantics of the common C idiom x<y?x:y but not
11223   // x<=y?x:y, because of how they handle negative zero (which can be
11224   // ignored in unsafe-math mode).
11225   if (Subtarget->hasSSE2() &&
11226       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11227       Cond.getOpcode() == ISD::SETCC) {
11228     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11229
11230     unsigned Opcode = 0;
11231     // Check for x CC y ? x : y.
11232     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11233         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11234       switch (CC) {
11235       default: break;
11236       case ISD::SETULT:
11237         // Converting this to a min would handle NaNs incorrectly, and swapping
11238         // the operands would cause it to handle comparisons between positive
11239         // and negative zero incorrectly.
11240         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11241           if (!UnsafeFPMath &&
11242               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11243             break;
11244           std::swap(LHS, RHS);
11245         }
11246         Opcode = X86ISD::FMIN;
11247         break;
11248       case ISD::SETOLE:
11249         // Converting this to a min would handle comparisons between positive
11250         // and negative zero incorrectly.
11251         if (!UnsafeFPMath &&
11252             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11253           break;
11254         Opcode = X86ISD::FMIN;
11255         break;
11256       case ISD::SETULE:
11257         // Converting this to a min would handle both negative zeros and NaNs
11258         // incorrectly, but we can swap the operands to fix both.
11259         std::swap(LHS, RHS);
11260       case ISD::SETOLT:
11261       case ISD::SETLT:
11262       case ISD::SETLE:
11263         Opcode = X86ISD::FMIN;
11264         break;
11265
11266       case ISD::SETOGE:
11267         // Converting this to a max would handle comparisons between positive
11268         // and negative zero incorrectly.
11269         if (!UnsafeFPMath &&
11270             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11271           break;
11272         Opcode = X86ISD::FMAX;
11273         break;
11274       case ISD::SETUGT:
11275         // Converting this to a max would handle NaNs incorrectly, and swapping
11276         // the operands would cause it to handle comparisons between positive
11277         // and negative zero incorrectly.
11278         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11279           if (!UnsafeFPMath &&
11280               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11281             break;
11282           std::swap(LHS, RHS);
11283         }
11284         Opcode = X86ISD::FMAX;
11285         break;
11286       case ISD::SETUGE:
11287         // Converting this to a max would handle both negative zeros and NaNs
11288         // incorrectly, but we can swap the operands to fix both.
11289         std::swap(LHS, RHS);
11290       case ISD::SETOGT:
11291       case ISD::SETGT:
11292       case ISD::SETGE:
11293         Opcode = X86ISD::FMAX;
11294         break;
11295       }
11296     // Check for x CC y ? y : x -- a min/max with reversed arms.
11297     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11298                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11299       switch (CC) {
11300       default: break;
11301       case ISD::SETOGE:
11302         // Converting this to a min would handle comparisons between positive
11303         // and negative zero incorrectly, and swapping the operands would
11304         // cause it to handle NaNs incorrectly.
11305         if (!UnsafeFPMath &&
11306             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11307           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11308             break;
11309           std::swap(LHS, RHS);
11310         }
11311         Opcode = X86ISD::FMIN;
11312         break;
11313       case ISD::SETUGT:
11314         // Converting this to a min would handle NaNs incorrectly.
11315         if (!UnsafeFPMath &&
11316             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11317           break;
11318         Opcode = X86ISD::FMIN;
11319         break;
11320       case ISD::SETUGE:
11321         // Converting this to a min would handle both negative zeros and NaNs
11322         // incorrectly, but we can swap the operands to fix both.
11323         std::swap(LHS, RHS);
11324       case ISD::SETOGT:
11325       case ISD::SETGT:
11326       case ISD::SETGE:
11327         Opcode = X86ISD::FMIN;
11328         break;
11329
11330       case ISD::SETULT:
11331         // Converting this to a max would handle NaNs incorrectly.
11332         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11333           break;
11334         Opcode = X86ISD::FMAX;
11335         break;
11336       case ISD::SETOLE:
11337         // Converting this to a max would handle comparisons between positive
11338         // and negative zero incorrectly, and swapping the operands would
11339         // cause it to handle NaNs incorrectly.
11340         if (!UnsafeFPMath &&
11341             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11342           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11343             break;
11344           std::swap(LHS, RHS);
11345         }
11346         Opcode = X86ISD::FMAX;
11347         break;
11348       case ISD::SETULE:
11349         // Converting this to a max would handle both negative zeros and NaNs
11350         // incorrectly, but we can swap the operands to fix both.
11351         std::swap(LHS, RHS);
11352       case ISD::SETOLT:
11353       case ISD::SETLT:
11354       case ISD::SETLE:
11355         Opcode = X86ISD::FMAX;
11356         break;
11357       }
11358     }
11359
11360     if (Opcode)
11361       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11362   }
11363
11364   // If this is a select between two integer constants, try to do some
11365   // optimizations.
11366   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11367     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11368       // Don't do this for crazy integer types.
11369       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11370         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11371         // so that TrueC (the true value) is larger than FalseC.
11372         bool NeedsCondInvert = false;
11373
11374         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11375             // Efficiently invertible.
11376             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11377              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11378               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11379           NeedsCondInvert = true;
11380           std::swap(TrueC, FalseC);
11381         }
11382
11383         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11384         if (FalseC->getAPIntValue() == 0 &&
11385             TrueC->getAPIntValue().isPowerOf2()) {
11386           if (NeedsCondInvert) // Invert the condition if needed.
11387             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11388                                DAG.getConstant(1, Cond.getValueType()));
11389
11390           // Zero extend the condition if needed.
11391           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11392
11393           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11394           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11395                              DAG.getConstant(ShAmt, MVT::i8));
11396         }
11397
11398         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11399         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11400           if (NeedsCondInvert) // Invert the condition if needed.
11401             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11402                                DAG.getConstant(1, Cond.getValueType()));
11403
11404           // Zero extend the condition if needed.
11405           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11406                              FalseC->getValueType(0), Cond);
11407           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11408                              SDValue(FalseC, 0));
11409         }
11410
11411         // Optimize cases that will turn into an LEA instruction.  This requires
11412         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11413         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11414           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11415           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11416
11417           bool isFastMultiplier = false;
11418           if (Diff < 10) {
11419             switch ((unsigned char)Diff) {
11420               default: break;
11421               case 1:  // result = add base, cond
11422               case 2:  // result = lea base(    , cond*2)
11423               case 3:  // result = lea base(cond, cond*2)
11424               case 4:  // result = lea base(    , cond*4)
11425               case 5:  // result = lea base(cond, cond*4)
11426               case 8:  // result = lea base(    , cond*8)
11427               case 9:  // result = lea base(cond, cond*8)
11428                 isFastMultiplier = true;
11429                 break;
11430             }
11431           }
11432
11433           if (isFastMultiplier) {
11434             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11435             if (NeedsCondInvert) // Invert the condition if needed.
11436               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11437                                  DAG.getConstant(1, Cond.getValueType()));
11438
11439             // Zero extend the condition if needed.
11440             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11441                                Cond);
11442             // Scale the condition by the difference.
11443             if (Diff != 1)
11444               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11445                                  DAG.getConstant(Diff, Cond.getValueType()));
11446
11447             // Add the base if non-zero.
11448             if (FalseC->getAPIntValue() != 0)
11449               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11450                                  SDValue(FalseC, 0));
11451             return Cond;
11452           }
11453         }
11454       }
11455   }
11456
11457   return SDValue();
11458 }
11459
11460 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11461 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11462                                   TargetLowering::DAGCombinerInfo &DCI) {
11463   DebugLoc DL = N->getDebugLoc();
11464
11465   // If the flag operand isn't dead, don't touch this CMOV.
11466   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11467     return SDValue();
11468
11469   SDValue FalseOp = N->getOperand(0);
11470   SDValue TrueOp = N->getOperand(1);
11471   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11472   SDValue Cond = N->getOperand(3);
11473   if (CC == X86::COND_E || CC == X86::COND_NE) {
11474     switch (Cond.getOpcode()) {
11475     default: break;
11476     case X86ISD::BSR:
11477     case X86ISD::BSF:
11478       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11479       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11480         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11481     }
11482   }
11483
11484   // If this is a select between two integer constants, try to do some
11485   // optimizations.  Note that the operands are ordered the opposite of SELECT
11486   // operands.
11487   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11488     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11489       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11490       // larger than FalseC (the false value).
11491       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11492         CC = X86::GetOppositeBranchCondition(CC);
11493         std::swap(TrueC, FalseC);
11494       }
11495
11496       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11497       // This is efficient for any integer data type (including i8/i16) and
11498       // shift amount.
11499       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11500         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11501                            DAG.getConstant(CC, MVT::i8), Cond);
11502
11503         // Zero extend the condition if needed.
11504         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11505
11506         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11507         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11508                            DAG.getConstant(ShAmt, MVT::i8));
11509         if (N->getNumValues() == 2)  // Dead flag value?
11510           return DCI.CombineTo(N, Cond, SDValue());
11511         return Cond;
11512       }
11513
11514       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11515       // for any integer data type, including i8/i16.
11516       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11517         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11518                            DAG.getConstant(CC, MVT::i8), Cond);
11519
11520         // Zero extend the condition if needed.
11521         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11522                            FalseC->getValueType(0), Cond);
11523         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11524                            SDValue(FalseC, 0));
11525
11526         if (N->getNumValues() == 2)  // Dead flag value?
11527           return DCI.CombineTo(N, Cond, SDValue());
11528         return Cond;
11529       }
11530
11531       // Optimize cases that will turn into an LEA instruction.  This requires
11532       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11533       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11534         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11535         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11536
11537         bool isFastMultiplier = false;
11538         if (Diff < 10) {
11539           switch ((unsigned char)Diff) {
11540           default: break;
11541           case 1:  // result = add base, cond
11542           case 2:  // result = lea base(    , cond*2)
11543           case 3:  // result = lea base(cond, cond*2)
11544           case 4:  // result = lea base(    , cond*4)
11545           case 5:  // result = lea base(cond, cond*4)
11546           case 8:  // result = lea base(    , cond*8)
11547           case 9:  // result = lea base(cond, cond*8)
11548             isFastMultiplier = true;
11549             break;
11550           }
11551         }
11552
11553         if (isFastMultiplier) {
11554           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11555           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11556                              DAG.getConstant(CC, MVT::i8), Cond);
11557           // Zero extend the condition if needed.
11558           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11559                              Cond);
11560           // Scale the condition by the difference.
11561           if (Diff != 1)
11562             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11563                                DAG.getConstant(Diff, Cond.getValueType()));
11564
11565           // Add the base if non-zero.
11566           if (FalseC->getAPIntValue() != 0)
11567             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11568                                SDValue(FalseC, 0));
11569           if (N->getNumValues() == 2)  // Dead flag value?
11570             return DCI.CombineTo(N, Cond, SDValue());
11571           return Cond;
11572         }
11573       }
11574     }
11575   }
11576   return SDValue();
11577 }
11578
11579
11580 /// PerformMulCombine - Optimize a single multiply with constant into two
11581 /// in order to implement it with two cheaper instructions, e.g.
11582 /// LEA + SHL, LEA + LEA.
11583 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11584                                  TargetLowering::DAGCombinerInfo &DCI) {
11585   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11586     return SDValue();
11587
11588   EVT VT = N->getValueType(0);
11589   if (VT != MVT::i64)
11590     return SDValue();
11591
11592   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11593   if (!C)
11594     return SDValue();
11595   uint64_t MulAmt = C->getZExtValue();
11596   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11597     return SDValue();
11598
11599   uint64_t MulAmt1 = 0;
11600   uint64_t MulAmt2 = 0;
11601   if ((MulAmt % 9) == 0) {
11602     MulAmt1 = 9;
11603     MulAmt2 = MulAmt / 9;
11604   } else if ((MulAmt % 5) == 0) {
11605     MulAmt1 = 5;
11606     MulAmt2 = MulAmt / 5;
11607   } else if ((MulAmt % 3) == 0) {
11608     MulAmt1 = 3;
11609     MulAmt2 = MulAmt / 3;
11610   }
11611   if (MulAmt2 &&
11612       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11613     DebugLoc DL = N->getDebugLoc();
11614
11615     if (isPowerOf2_64(MulAmt2) &&
11616         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11617       // If second multiplifer is pow2, issue it first. We want the multiply by
11618       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11619       // is an add.
11620       std::swap(MulAmt1, MulAmt2);
11621
11622     SDValue NewMul;
11623     if (isPowerOf2_64(MulAmt1))
11624       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11625                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11626     else
11627       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11628                            DAG.getConstant(MulAmt1, VT));
11629
11630     if (isPowerOf2_64(MulAmt2))
11631       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11632                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11633     else
11634       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11635                            DAG.getConstant(MulAmt2, VT));
11636
11637     // Do not add new nodes to DAG combiner worklist.
11638     DCI.CombineTo(N, NewMul, false);
11639   }
11640   return SDValue();
11641 }
11642
11643 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11644   SDValue N0 = N->getOperand(0);
11645   SDValue N1 = N->getOperand(1);
11646   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11647   EVT VT = N0.getValueType();
11648
11649   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11650   // since the result of setcc_c is all zero's or all ones.
11651   if (N1C && N0.getOpcode() == ISD::AND &&
11652       N0.getOperand(1).getOpcode() == ISD::Constant) {
11653     SDValue N00 = N0.getOperand(0);
11654     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11655         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11656           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11657          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11658       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11659       APInt ShAmt = N1C->getAPIntValue();
11660       Mask = Mask.shl(ShAmt);
11661       if (Mask != 0)
11662         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11663                            N00, DAG.getConstant(Mask, VT));
11664     }
11665   }
11666
11667   return SDValue();
11668 }
11669
11670 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11671 ///                       when possible.
11672 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11673                                    const X86Subtarget *Subtarget) {
11674   EVT VT = N->getValueType(0);
11675   if (!VT.isVector() && VT.isInteger() &&
11676       N->getOpcode() == ISD::SHL)
11677     return PerformSHLCombine(N, DAG);
11678
11679   // On X86 with SSE2 support, we can transform this to a vector shift if
11680   // all elements are shifted by the same amount.  We can't do this in legalize
11681   // because the a constant vector is typically transformed to a constant pool
11682   // so we have no knowledge of the shift amount.
11683   if (!Subtarget->hasSSE2())
11684     return SDValue();
11685
11686   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11687     return SDValue();
11688
11689   SDValue ShAmtOp = N->getOperand(1);
11690   EVT EltVT = VT.getVectorElementType();
11691   DebugLoc DL = N->getDebugLoc();
11692   SDValue BaseShAmt = SDValue();
11693   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11694     unsigned NumElts = VT.getVectorNumElements();
11695     unsigned i = 0;
11696     for (; i != NumElts; ++i) {
11697       SDValue Arg = ShAmtOp.getOperand(i);
11698       if (Arg.getOpcode() == ISD::UNDEF) continue;
11699       BaseShAmt = Arg;
11700       break;
11701     }
11702     for (; i != NumElts; ++i) {
11703       SDValue Arg = ShAmtOp.getOperand(i);
11704       if (Arg.getOpcode() == ISD::UNDEF) continue;
11705       if (Arg != BaseShAmt) {
11706         return SDValue();
11707       }
11708     }
11709   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11710              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11711     SDValue InVec = ShAmtOp.getOperand(0);
11712     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11713       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11714       unsigned i = 0;
11715       for (; i != NumElts; ++i) {
11716         SDValue Arg = InVec.getOperand(i);
11717         if (Arg.getOpcode() == ISD::UNDEF) continue;
11718         BaseShAmt = Arg;
11719         break;
11720       }
11721     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11722        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11723          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11724          if (C->getZExtValue() == SplatIdx)
11725            BaseShAmt = InVec.getOperand(1);
11726        }
11727     }
11728     if (BaseShAmt.getNode() == 0)
11729       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11730                               DAG.getIntPtrConstant(0));
11731   } else
11732     return SDValue();
11733
11734   // The shift amount is an i32.
11735   if (EltVT.bitsGT(MVT::i32))
11736     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11737   else if (EltVT.bitsLT(MVT::i32))
11738     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11739
11740   // The shift amount is identical so we can do a vector shift.
11741   SDValue  ValOp = N->getOperand(0);
11742   switch (N->getOpcode()) {
11743   default:
11744     llvm_unreachable("Unknown shift opcode!");
11745     break;
11746   case ISD::SHL:
11747     if (VT == MVT::v2i64)
11748       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11749                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11750                          ValOp, BaseShAmt);
11751     if (VT == MVT::v4i32)
11752       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11753                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11754                          ValOp, BaseShAmt);
11755     if (VT == MVT::v8i16)
11756       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11757                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11758                          ValOp, BaseShAmt);
11759     break;
11760   case ISD::SRA:
11761     if (VT == MVT::v4i32)
11762       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11763                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11764                          ValOp, BaseShAmt);
11765     if (VT == MVT::v8i16)
11766       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11767                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11768                          ValOp, BaseShAmt);
11769     break;
11770   case ISD::SRL:
11771     if (VT == MVT::v2i64)
11772       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11773                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11774                          ValOp, BaseShAmt);
11775     if (VT == MVT::v4i32)
11776       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11777                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11778                          ValOp, BaseShAmt);
11779     if (VT ==  MVT::v8i16)
11780       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11781                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11782                          ValOp, BaseShAmt);
11783     break;
11784   }
11785   return SDValue();
11786 }
11787
11788
11789 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11790 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11791 // and friends.  Likewise for OR -> CMPNEQSS.
11792 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11793                             TargetLowering::DAGCombinerInfo &DCI,
11794                             const X86Subtarget *Subtarget) {
11795   unsigned opcode;
11796
11797   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11798   // we're requiring SSE2 for both.
11799   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11800     SDValue N0 = N->getOperand(0);
11801     SDValue N1 = N->getOperand(1);
11802     SDValue CMP0 = N0->getOperand(1);
11803     SDValue CMP1 = N1->getOperand(1);
11804     DebugLoc DL = N->getDebugLoc();
11805
11806     // The SETCCs should both refer to the same CMP.
11807     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11808       return SDValue();
11809
11810     SDValue CMP00 = CMP0->getOperand(0);
11811     SDValue CMP01 = CMP0->getOperand(1);
11812     EVT     VT    = CMP00.getValueType();
11813
11814     if (VT == MVT::f32 || VT == MVT::f64) {
11815       bool ExpectingFlags = false;
11816       // Check for any users that want flags:
11817       for (SDNode::use_iterator UI = N->use_begin(),
11818              UE = N->use_end();
11819            !ExpectingFlags && UI != UE; ++UI)
11820         switch (UI->getOpcode()) {
11821         default:
11822         case ISD::BR_CC:
11823         case ISD::BRCOND:
11824         case ISD::SELECT:
11825           ExpectingFlags = true;
11826           break;
11827         case ISD::CopyToReg:
11828         case ISD::SIGN_EXTEND:
11829         case ISD::ZERO_EXTEND:
11830         case ISD::ANY_EXTEND:
11831           break;
11832         }
11833
11834       if (!ExpectingFlags) {
11835         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11836         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11837
11838         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11839           X86::CondCode tmp = cc0;
11840           cc0 = cc1;
11841           cc1 = tmp;
11842         }
11843
11844         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11845             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11846           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11847           X86ISD::NodeType NTOperator = is64BitFP ?
11848             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11849           // FIXME: need symbolic constants for these magic numbers.
11850           // See X86ATTInstPrinter.cpp:printSSECC().
11851           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11852           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11853                                               DAG.getConstant(x86cc, MVT::i8));
11854           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11855                                               OnesOrZeroesF);
11856           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11857                                       DAG.getConstant(1, MVT::i32));
11858           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11859           return OneBitOfTruth;
11860         }
11861       }
11862     }
11863   }
11864   return SDValue();
11865 }
11866
11867 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11868                                  TargetLowering::DAGCombinerInfo &DCI,
11869                                  const X86Subtarget *Subtarget) {
11870   if (DCI.isBeforeLegalizeOps())
11871     return SDValue();
11872
11873   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11874   if (R.getNode())
11875     return R;
11876
11877   // Want to form ANDNP nodes:
11878   // 1) In the hopes of then easily combining them with OR and AND nodes
11879   //    to form PBLEND/PSIGN.
11880   // 2) To match ANDN packed intrinsics
11881   EVT VT = N->getValueType(0);
11882   if (VT != MVT::v2i64 && VT != MVT::v4i64)
11883     return SDValue();
11884
11885   SDValue N0 = N->getOperand(0);
11886   SDValue N1 = N->getOperand(1);
11887   DebugLoc DL = N->getDebugLoc();
11888
11889   // Check LHS for vnot
11890   if (N0.getOpcode() == ISD::XOR &&
11891       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11892     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
11893
11894   // Check RHS for vnot
11895   if (N1.getOpcode() == ISD::XOR &&
11896       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11897     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
11898
11899   return SDValue();
11900 }
11901
11902 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11903                                 TargetLowering::DAGCombinerInfo &DCI,
11904                                 const X86Subtarget *Subtarget) {
11905   if (DCI.isBeforeLegalizeOps())
11906     return SDValue();
11907
11908   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11909   if (R.getNode())
11910     return R;
11911
11912   EVT VT = N->getValueType(0);
11913   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11914     return SDValue();
11915
11916   SDValue N0 = N->getOperand(0);
11917   SDValue N1 = N->getOperand(1);
11918
11919   // look for psign/blend
11920   if (Subtarget->hasSSSE3()) {
11921     if (VT == MVT::v2i64) {
11922       // Canonicalize pandn to RHS
11923       if (N0.getOpcode() == X86ISD::ANDNP)
11924         std::swap(N0, N1);
11925       // or (and (m, x), (pandn m, y))
11926       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
11927         SDValue Mask = N1.getOperand(0);
11928         SDValue X    = N1.getOperand(1);
11929         SDValue Y;
11930         if (N0.getOperand(0) == Mask)
11931           Y = N0.getOperand(1);
11932         if (N0.getOperand(1) == Mask)
11933           Y = N0.getOperand(0);
11934
11935         // Check to see if the mask appeared in both the AND and ANDNP and
11936         if (!Y.getNode())
11937           return SDValue();
11938
11939         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11940         if (Mask.getOpcode() != ISD::BITCAST ||
11941             X.getOpcode() != ISD::BITCAST ||
11942             Y.getOpcode() != ISD::BITCAST)
11943           return SDValue();
11944
11945         // Look through mask bitcast.
11946         Mask = Mask.getOperand(0);
11947         EVT MaskVT = Mask.getValueType();
11948
11949         // Validate that the Mask operand is a vector sra node.  The sra node
11950         // will be an intrinsic.
11951         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11952           return SDValue();
11953
11954         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11955         // there is no psrai.b
11956         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11957         case Intrinsic::x86_sse2_psrai_w:
11958         case Intrinsic::x86_sse2_psrai_d:
11959           break;
11960         default: return SDValue();
11961         }
11962
11963         // Check that the SRA is all signbits.
11964         SDValue SraC = Mask.getOperand(2);
11965         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11966         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11967         if ((SraAmt + 1) != EltBits)
11968           return SDValue();
11969
11970         DebugLoc DL = N->getDebugLoc();
11971
11972         // Now we know we at least have a plendvb with the mask val.  See if
11973         // we can form a psignb/w/d.
11974         // psign = x.type == y.type == mask.type && y = sub(0, x);
11975         X = X.getOperand(0);
11976         Y = Y.getOperand(0);
11977         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11978             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11979             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11980           unsigned Opc = 0;
11981           switch (EltBits) {
11982           case 8: Opc = X86ISD::PSIGNB; break;
11983           case 16: Opc = X86ISD::PSIGNW; break;
11984           case 32: Opc = X86ISD::PSIGND; break;
11985           default: break;
11986           }
11987           if (Opc) {
11988             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11989             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11990           }
11991         }
11992         // PBLENDVB only available on SSE 4.1
11993         if (!Subtarget->hasSSE41())
11994           return SDValue();
11995
11996         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11997         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11998         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11999         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12000         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12001       }
12002     }
12003   }
12004
12005   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12006   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12007     std::swap(N0, N1);
12008   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12009     return SDValue();
12010   if (!N0.hasOneUse() || !N1.hasOneUse())
12011     return SDValue();
12012
12013   SDValue ShAmt0 = N0.getOperand(1);
12014   if (ShAmt0.getValueType() != MVT::i8)
12015     return SDValue();
12016   SDValue ShAmt1 = N1.getOperand(1);
12017   if (ShAmt1.getValueType() != MVT::i8)
12018     return SDValue();
12019   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12020     ShAmt0 = ShAmt0.getOperand(0);
12021   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12022     ShAmt1 = ShAmt1.getOperand(0);
12023
12024   DebugLoc DL = N->getDebugLoc();
12025   unsigned Opc = X86ISD::SHLD;
12026   SDValue Op0 = N0.getOperand(0);
12027   SDValue Op1 = N1.getOperand(0);
12028   if (ShAmt0.getOpcode() == ISD::SUB) {
12029     Opc = X86ISD::SHRD;
12030     std::swap(Op0, Op1);
12031     std::swap(ShAmt0, ShAmt1);
12032   }
12033
12034   unsigned Bits = VT.getSizeInBits();
12035   if (ShAmt1.getOpcode() == ISD::SUB) {
12036     SDValue Sum = ShAmt1.getOperand(0);
12037     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12038       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12039       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12040         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12041       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12042         return DAG.getNode(Opc, DL, VT,
12043                            Op0, Op1,
12044                            DAG.getNode(ISD::TRUNCATE, DL,
12045                                        MVT::i8, ShAmt0));
12046     }
12047   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12048     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12049     if (ShAmt0C &&
12050         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12051       return DAG.getNode(Opc, DL, VT,
12052                          N0.getOperand(0), N1.getOperand(0),
12053                          DAG.getNode(ISD::TRUNCATE, DL,
12054                                        MVT::i8, ShAmt0));
12055   }
12056
12057   return SDValue();
12058 }
12059
12060 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12061 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12062                                    const X86Subtarget *Subtarget) {
12063   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12064   // the FP state in cases where an emms may be missing.
12065   // A preferable solution to the general problem is to figure out the right
12066   // places to insert EMMS.  This qualifies as a quick hack.
12067
12068   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12069   StoreSDNode *St = cast<StoreSDNode>(N);
12070   EVT VT = St->getValue().getValueType();
12071   if (VT.getSizeInBits() != 64)
12072     return SDValue();
12073
12074   const Function *F = DAG.getMachineFunction().getFunction();
12075   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12076   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12077     && Subtarget->hasSSE2();
12078   if ((VT.isVector() ||
12079        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12080       isa<LoadSDNode>(St->getValue()) &&
12081       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12082       St->getChain().hasOneUse() && !St->isVolatile()) {
12083     SDNode* LdVal = St->getValue().getNode();
12084     LoadSDNode *Ld = 0;
12085     int TokenFactorIndex = -1;
12086     SmallVector<SDValue, 8> Ops;
12087     SDNode* ChainVal = St->getChain().getNode();
12088     // Must be a store of a load.  We currently handle two cases:  the load
12089     // is a direct child, and it's under an intervening TokenFactor.  It is
12090     // possible to dig deeper under nested TokenFactors.
12091     if (ChainVal == LdVal)
12092       Ld = cast<LoadSDNode>(St->getChain());
12093     else if (St->getValue().hasOneUse() &&
12094              ChainVal->getOpcode() == ISD::TokenFactor) {
12095       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12096         if (ChainVal->getOperand(i).getNode() == LdVal) {
12097           TokenFactorIndex = i;
12098           Ld = cast<LoadSDNode>(St->getValue());
12099         } else
12100           Ops.push_back(ChainVal->getOperand(i));
12101       }
12102     }
12103
12104     if (!Ld || !ISD::isNormalLoad(Ld))
12105       return SDValue();
12106
12107     // If this is not the MMX case, i.e. we are just turning i64 load/store
12108     // into f64 load/store, avoid the transformation if there are multiple
12109     // uses of the loaded value.
12110     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12111       return SDValue();
12112
12113     DebugLoc LdDL = Ld->getDebugLoc();
12114     DebugLoc StDL = N->getDebugLoc();
12115     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12116     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12117     // pair instead.
12118     if (Subtarget->is64Bit() || F64IsLegal) {
12119       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12120       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12121                                   Ld->getPointerInfo(), Ld->isVolatile(),
12122                                   Ld->isNonTemporal(), Ld->getAlignment());
12123       SDValue NewChain = NewLd.getValue(1);
12124       if (TokenFactorIndex != -1) {
12125         Ops.push_back(NewChain);
12126         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12127                                Ops.size());
12128       }
12129       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12130                           St->getPointerInfo(),
12131                           St->isVolatile(), St->isNonTemporal(),
12132                           St->getAlignment());
12133     }
12134
12135     // Otherwise, lower to two pairs of 32-bit loads / stores.
12136     SDValue LoAddr = Ld->getBasePtr();
12137     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12138                                  DAG.getConstant(4, MVT::i32));
12139
12140     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12141                                Ld->getPointerInfo(),
12142                                Ld->isVolatile(), Ld->isNonTemporal(),
12143                                Ld->getAlignment());
12144     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12145                                Ld->getPointerInfo().getWithOffset(4),
12146                                Ld->isVolatile(), Ld->isNonTemporal(),
12147                                MinAlign(Ld->getAlignment(), 4));
12148
12149     SDValue NewChain = LoLd.getValue(1);
12150     if (TokenFactorIndex != -1) {
12151       Ops.push_back(LoLd);
12152       Ops.push_back(HiLd);
12153       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12154                              Ops.size());
12155     }
12156
12157     LoAddr = St->getBasePtr();
12158     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12159                          DAG.getConstant(4, MVT::i32));
12160
12161     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12162                                 St->getPointerInfo(),
12163                                 St->isVolatile(), St->isNonTemporal(),
12164                                 St->getAlignment());
12165     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12166                                 St->getPointerInfo().getWithOffset(4),
12167                                 St->isVolatile(),
12168                                 St->isNonTemporal(),
12169                                 MinAlign(St->getAlignment(), 4));
12170     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12171   }
12172   return SDValue();
12173 }
12174
12175 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12176 /// X86ISD::FXOR nodes.
12177 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12178   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12179   // F[X]OR(0.0, x) -> x
12180   // F[X]OR(x, 0.0) -> x
12181   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12182     if (C->getValueAPF().isPosZero())
12183       return N->getOperand(1);
12184   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12185     if (C->getValueAPF().isPosZero())
12186       return N->getOperand(0);
12187   return SDValue();
12188 }
12189
12190 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12191 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12192   // FAND(0.0, x) -> 0.0
12193   // FAND(x, 0.0) -> 0.0
12194   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12195     if (C->getValueAPF().isPosZero())
12196       return N->getOperand(0);
12197   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12198     if (C->getValueAPF().isPosZero())
12199       return N->getOperand(1);
12200   return SDValue();
12201 }
12202
12203 static SDValue PerformBTCombine(SDNode *N,
12204                                 SelectionDAG &DAG,
12205                                 TargetLowering::DAGCombinerInfo &DCI) {
12206   // BT ignores high bits in the bit index operand.
12207   SDValue Op1 = N->getOperand(1);
12208   if (Op1.hasOneUse()) {
12209     unsigned BitWidth = Op1.getValueSizeInBits();
12210     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12211     APInt KnownZero, KnownOne;
12212     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12213                                           !DCI.isBeforeLegalizeOps());
12214     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12215     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12216         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12217       DCI.CommitTargetLoweringOpt(TLO);
12218   }
12219   return SDValue();
12220 }
12221
12222 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12223   SDValue Op = N->getOperand(0);
12224   if (Op.getOpcode() == ISD::BITCAST)
12225     Op = Op.getOperand(0);
12226   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12227   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12228       VT.getVectorElementType().getSizeInBits() ==
12229       OpVT.getVectorElementType().getSizeInBits()) {
12230     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12231   }
12232   return SDValue();
12233 }
12234
12235 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12236   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12237   //           (and (i32 x86isd::setcc_carry), 1)
12238   // This eliminates the zext. This transformation is necessary because
12239   // ISD::SETCC is always legalized to i8.
12240   DebugLoc dl = N->getDebugLoc();
12241   SDValue N0 = N->getOperand(0);
12242   EVT VT = N->getValueType(0);
12243   if (N0.getOpcode() == ISD::AND &&
12244       N0.hasOneUse() &&
12245       N0.getOperand(0).hasOneUse()) {
12246     SDValue N00 = N0.getOperand(0);
12247     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12248       return SDValue();
12249     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12250     if (!C || C->getZExtValue() != 1)
12251       return SDValue();
12252     return DAG.getNode(ISD::AND, dl, VT,
12253                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12254                                    N00.getOperand(0), N00.getOperand(1)),
12255                        DAG.getConstant(1, VT));
12256   }
12257
12258   return SDValue();
12259 }
12260
12261 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12262 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12263   unsigned X86CC = N->getConstantOperandVal(0);
12264   SDValue EFLAG = N->getOperand(1);
12265   DebugLoc DL = N->getDebugLoc();
12266
12267   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12268   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12269   // cases.
12270   if (X86CC == X86::COND_B)
12271     return DAG.getNode(ISD::AND, DL, MVT::i8,
12272                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12273                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12274                        DAG.getConstant(1, MVT::i8));
12275
12276   return SDValue();
12277 }
12278
12279 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12280                                         const X86TargetLowering *XTLI) {
12281   SDValue Op0 = N->getOperand(0);
12282   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12283   // a 32-bit target where SSE doesn't support i64->FP operations.
12284   if (Op0.getOpcode() == ISD::LOAD) {
12285     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12286     EVT VT = Ld->getValueType(0);
12287     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12288         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12289         !XTLI->getSubtarget()->is64Bit() &&
12290         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12291       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12292                                           Ld->getChain(), Op0, DAG);
12293       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12294       return FILDChain;
12295     }
12296   }
12297   return SDValue();
12298 }
12299
12300 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12301 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12302                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12303   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12304   // the result is either zero or one (depending on the input carry bit).
12305   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12306   if (X86::isZeroNode(N->getOperand(0)) &&
12307       X86::isZeroNode(N->getOperand(1)) &&
12308       // We don't have a good way to replace an EFLAGS use, so only do this when
12309       // dead right now.
12310       SDValue(N, 1).use_empty()) {
12311     DebugLoc DL = N->getDebugLoc();
12312     EVT VT = N->getValueType(0);
12313     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12314     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12315                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12316                                            DAG.getConstant(X86::COND_B,MVT::i8),
12317                                            N->getOperand(2)),
12318                                DAG.getConstant(1, VT));
12319     return DCI.CombineTo(N, Res1, CarryOut);
12320   }
12321
12322   return SDValue();
12323 }
12324
12325 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12326 //      (add Y, (setne X, 0)) -> sbb -1, Y
12327 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12328 //      (sub (setne X, 0), Y) -> adc -1, Y
12329 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12330   DebugLoc DL = N->getDebugLoc();
12331
12332   // Look through ZExts.
12333   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12334   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12335     return SDValue();
12336
12337   SDValue SetCC = Ext.getOperand(0);
12338   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12339     return SDValue();
12340
12341   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12342   if (CC != X86::COND_E && CC != X86::COND_NE)
12343     return SDValue();
12344
12345   SDValue Cmp = SetCC.getOperand(1);
12346   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12347       !X86::isZeroNode(Cmp.getOperand(1)) ||
12348       !Cmp.getOperand(0).getValueType().isInteger())
12349     return SDValue();
12350
12351   SDValue CmpOp0 = Cmp.getOperand(0);
12352   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12353                                DAG.getConstant(1, CmpOp0.getValueType()));
12354
12355   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12356   if (CC == X86::COND_NE)
12357     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12358                        DL, OtherVal.getValueType(), OtherVal,
12359                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12360   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12361                      DL, OtherVal.getValueType(), OtherVal,
12362                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12363 }
12364
12365 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12366                                              DAGCombinerInfo &DCI) const {
12367   SelectionDAG &DAG = DCI.DAG;
12368   switch (N->getOpcode()) {
12369   default: break;
12370   case ISD::EXTRACT_VECTOR_ELT:
12371     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12372   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12373   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12374   case ISD::ADD:
12375   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12376   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12377   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12378   case ISD::SHL:
12379   case ISD::SRA:
12380   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12381   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12382   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12383   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12384   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12385   case X86ISD::FXOR:
12386   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12387   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12388   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12389   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12390   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12391   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12392   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12393   case X86ISD::SHUFPD:
12394   case X86ISD::PALIGN:
12395   case X86ISD::PUNPCKHBW:
12396   case X86ISD::PUNPCKHWD:
12397   case X86ISD::PUNPCKHDQ:
12398   case X86ISD::PUNPCKHQDQ:
12399   case X86ISD::UNPCKHPS:
12400   case X86ISD::UNPCKHPD:
12401   case X86ISD::PUNPCKLBW:
12402   case X86ISD::PUNPCKLWD:
12403   case X86ISD::PUNPCKLDQ:
12404   case X86ISD::PUNPCKLQDQ:
12405   case X86ISD::UNPCKLPS:
12406   case X86ISD::UNPCKLPD:
12407   case X86ISD::VUNPCKLPS:
12408   case X86ISD::VUNPCKLPD:
12409   case X86ISD::VUNPCKLPSY:
12410   case X86ISD::VUNPCKLPDY:
12411   case X86ISD::MOVHLPS:
12412   case X86ISD::MOVLHPS:
12413   case X86ISD::PSHUFD:
12414   case X86ISD::PSHUFHW:
12415   case X86ISD::PSHUFLW:
12416   case X86ISD::MOVSS:
12417   case X86ISD::MOVSD:
12418   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12419   }
12420
12421   return SDValue();
12422 }
12423
12424 /// isTypeDesirableForOp - Return true if the target has native support for
12425 /// the specified value type and it is 'desirable' to use the type for the
12426 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12427 /// instruction encodings are longer and some i16 instructions are slow.
12428 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12429   if (!isTypeLegal(VT))
12430     return false;
12431   if (VT != MVT::i16)
12432     return true;
12433
12434   switch (Opc) {
12435   default:
12436     return true;
12437   case ISD::LOAD:
12438   case ISD::SIGN_EXTEND:
12439   case ISD::ZERO_EXTEND:
12440   case ISD::ANY_EXTEND:
12441   case ISD::SHL:
12442   case ISD::SRL:
12443   case ISD::SUB:
12444   case ISD::ADD:
12445   case ISD::MUL:
12446   case ISD::AND:
12447   case ISD::OR:
12448   case ISD::XOR:
12449     return false;
12450   }
12451 }
12452
12453 /// IsDesirableToPromoteOp - This method query the target whether it is
12454 /// beneficial for dag combiner to promote the specified node. If true, it
12455 /// should return the desired promotion type by reference.
12456 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12457   EVT VT = Op.getValueType();
12458   if (VT != MVT::i16)
12459     return false;
12460
12461   bool Promote = false;
12462   bool Commute = false;
12463   switch (Op.getOpcode()) {
12464   default: break;
12465   case ISD::LOAD: {
12466     LoadSDNode *LD = cast<LoadSDNode>(Op);
12467     // If the non-extending load has a single use and it's not live out, then it
12468     // might be folded.
12469     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12470                                                      Op.hasOneUse()*/) {
12471       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12472              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12473         // The only case where we'd want to promote LOAD (rather then it being
12474         // promoted as an operand is when it's only use is liveout.
12475         if (UI->getOpcode() != ISD::CopyToReg)
12476           return false;
12477       }
12478     }
12479     Promote = true;
12480     break;
12481   }
12482   case ISD::SIGN_EXTEND:
12483   case ISD::ZERO_EXTEND:
12484   case ISD::ANY_EXTEND:
12485     Promote = true;
12486     break;
12487   case ISD::SHL:
12488   case ISD::SRL: {
12489     SDValue N0 = Op.getOperand(0);
12490     // Look out for (store (shl (load), x)).
12491     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12492       return false;
12493     Promote = true;
12494     break;
12495   }
12496   case ISD::ADD:
12497   case ISD::MUL:
12498   case ISD::AND:
12499   case ISD::OR:
12500   case ISD::XOR:
12501     Commute = true;
12502     // fallthrough
12503   case ISD::SUB: {
12504     SDValue N0 = Op.getOperand(0);
12505     SDValue N1 = Op.getOperand(1);
12506     if (!Commute && MayFoldLoad(N1))
12507       return false;
12508     // Avoid disabling potential load folding opportunities.
12509     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12510       return false;
12511     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12512       return false;
12513     Promote = true;
12514   }
12515   }
12516
12517   PVT = MVT::i32;
12518   return Promote;
12519 }
12520
12521 //===----------------------------------------------------------------------===//
12522 //                           X86 Inline Assembly Support
12523 //===----------------------------------------------------------------------===//
12524
12525 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12526   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12527
12528   std::string AsmStr = IA->getAsmString();
12529
12530   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12531   SmallVector<StringRef, 4> AsmPieces;
12532   SplitString(AsmStr, AsmPieces, ";\n");
12533
12534   switch (AsmPieces.size()) {
12535   default: return false;
12536   case 1:
12537     AsmStr = AsmPieces[0];
12538     AsmPieces.clear();
12539     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12540
12541     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12542     // we will turn this bswap into something that will be lowered to logical ops
12543     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12544     // so don't worry about this.
12545     // bswap $0
12546     if (AsmPieces.size() == 2 &&
12547         (AsmPieces[0] == "bswap" ||
12548          AsmPieces[0] == "bswapq" ||
12549          AsmPieces[0] == "bswapl") &&
12550         (AsmPieces[1] == "$0" ||
12551          AsmPieces[1] == "${0:q}")) {
12552       // No need to check constraints, nothing other than the equivalent of
12553       // "=r,0" would be valid here.
12554       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12555       if (!Ty || Ty->getBitWidth() % 16 != 0)
12556         return false;
12557       return IntrinsicLowering::LowerToByteSwap(CI);
12558     }
12559     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12560     if (CI->getType()->isIntegerTy(16) &&
12561         AsmPieces.size() == 3 &&
12562         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12563         AsmPieces[1] == "$$8," &&
12564         AsmPieces[2] == "${0:w}" &&
12565         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12566       AsmPieces.clear();
12567       const std::string &ConstraintsStr = IA->getConstraintString();
12568       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12569       std::sort(AsmPieces.begin(), AsmPieces.end());
12570       if (AsmPieces.size() == 4 &&
12571           AsmPieces[0] == "~{cc}" &&
12572           AsmPieces[1] == "~{dirflag}" &&
12573           AsmPieces[2] == "~{flags}" &&
12574           AsmPieces[3] == "~{fpsr}") {
12575         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12576         if (!Ty || Ty->getBitWidth() % 16 != 0)
12577           return false;
12578         return IntrinsicLowering::LowerToByteSwap(CI);
12579       }
12580     }
12581     break;
12582   case 3:
12583     if (CI->getType()->isIntegerTy(32) &&
12584         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12585       SmallVector<StringRef, 4> Words;
12586       SplitString(AsmPieces[0], Words, " \t,");
12587       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12588           Words[2] == "${0:w}") {
12589         Words.clear();
12590         SplitString(AsmPieces[1], Words, " \t,");
12591         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12592             Words[2] == "$0") {
12593           Words.clear();
12594           SplitString(AsmPieces[2], Words, " \t,");
12595           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12596               Words[2] == "${0:w}") {
12597             AsmPieces.clear();
12598             const std::string &ConstraintsStr = IA->getConstraintString();
12599             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12600             std::sort(AsmPieces.begin(), AsmPieces.end());
12601             if (AsmPieces.size() == 4 &&
12602                 AsmPieces[0] == "~{cc}" &&
12603                 AsmPieces[1] == "~{dirflag}" &&
12604                 AsmPieces[2] == "~{flags}" &&
12605                 AsmPieces[3] == "~{fpsr}") {
12606               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12607               if (!Ty || Ty->getBitWidth() % 16 != 0)
12608                 return false;
12609               return IntrinsicLowering::LowerToByteSwap(CI);
12610             }
12611           }
12612         }
12613       }
12614     }
12615
12616     if (CI->getType()->isIntegerTy(64)) {
12617       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12618       if (Constraints.size() >= 2 &&
12619           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12620           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12621         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12622         SmallVector<StringRef, 4> Words;
12623         SplitString(AsmPieces[0], Words, " \t");
12624         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12625           Words.clear();
12626           SplitString(AsmPieces[1], Words, " \t");
12627           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12628             Words.clear();
12629             SplitString(AsmPieces[2], Words, " \t,");
12630             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12631                 Words[2] == "%edx") {
12632               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12633               if (!Ty || Ty->getBitWidth() % 16 != 0)
12634                 return false;
12635               return IntrinsicLowering::LowerToByteSwap(CI);
12636             }
12637           }
12638         }
12639       }
12640     }
12641     break;
12642   }
12643   return false;
12644 }
12645
12646
12647
12648 /// getConstraintType - Given a constraint letter, return the type of
12649 /// constraint it is for this target.
12650 X86TargetLowering::ConstraintType
12651 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12652   if (Constraint.size() == 1) {
12653     switch (Constraint[0]) {
12654     case 'R':
12655     case 'q':
12656     case 'Q':
12657     case 'f':
12658     case 't':
12659     case 'u':
12660     case 'y':
12661     case 'x':
12662     case 'Y':
12663     case 'l':
12664       return C_RegisterClass;
12665     case 'a':
12666     case 'b':
12667     case 'c':
12668     case 'd':
12669     case 'S':
12670     case 'D':
12671     case 'A':
12672       return C_Register;
12673     case 'I':
12674     case 'J':
12675     case 'K':
12676     case 'L':
12677     case 'M':
12678     case 'N':
12679     case 'G':
12680     case 'C':
12681     case 'e':
12682     case 'Z':
12683       return C_Other;
12684     default:
12685       break;
12686     }
12687   }
12688   return TargetLowering::getConstraintType(Constraint);
12689 }
12690
12691 /// Examine constraint type and operand type and determine a weight value.
12692 /// This object must already have been set up with the operand type
12693 /// and the current alternative constraint selected.
12694 TargetLowering::ConstraintWeight
12695   X86TargetLowering::getSingleConstraintMatchWeight(
12696     AsmOperandInfo &info, const char *constraint) const {
12697   ConstraintWeight weight = CW_Invalid;
12698   Value *CallOperandVal = info.CallOperandVal;
12699     // If we don't have a value, we can't do a match,
12700     // but allow it at the lowest weight.
12701   if (CallOperandVal == NULL)
12702     return CW_Default;
12703   const Type *type = CallOperandVal->getType();
12704   // Look at the constraint type.
12705   switch (*constraint) {
12706   default:
12707     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12708   case 'R':
12709   case 'q':
12710   case 'Q':
12711   case 'a':
12712   case 'b':
12713   case 'c':
12714   case 'd':
12715   case 'S':
12716   case 'D':
12717   case 'A':
12718     if (CallOperandVal->getType()->isIntegerTy())
12719       weight = CW_SpecificReg;
12720     break;
12721   case 'f':
12722   case 't':
12723   case 'u':
12724       if (type->isFloatingPointTy())
12725         weight = CW_SpecificReg;
12726       break;
12727   case 'y':
12728       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12729         weight = CW_SpecificReg;
12730       break;
12731   case 'x':
12732   case 'Y':
12733     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12734       weight = CW_Register;
12735     break;
12736   case 'I':
12737     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12738       if (C->getZExtValue() <= 31)
12739         weight = CW_Constant;
12740     }
12741     break;
12742   case 'J':
12743     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12744       if (C->getZExtValue() <= 63)
12745         weight = CW_Constant;
12746     }
12747     break;
12748   case 'K':
12749     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12750       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12751         weight = CW_Constant;
12752     }
12753     break;
12754   case 'L':
12755     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12756       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12757         weight = CW_Constant;
12758     }
12759     break;
12760   case 'M':
12761     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12762       if (C->getZExtValue() <= 3)
12763         weight = CW_Constant;
12764     }
12765     break;
12766   case 'N':
12767     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12768       if (C->getZExtValue() <= 0xff)
12769         weight = CW_Constant;
12770     }
12771     break;
12772   case 'G':
12773   case 'C':
12774     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12775       weight = CW_Constant;
12776     }
12777     break;
12778   case 'e':
12779     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12780       if ((C->getSExtValue() >= -0x80000000LL) &&
12781           (C->getSExtValue() <= 0x7fffffffLL))
12782         weight = CW_Constant;
12783     }
12784     break;
12785   case 'Z':
12786     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12787       if (C->getZExtValue() <= 0xffffffff)
12788         weight = CW_Constant;
12789     }
12790     break;
12791   }
12792   return weight;
12793 }
12794
12795 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12796 /// with another that has more specific requirements based on the type of the
12797 /// corresponding operand.
12798 const char *X86TargetLowering::
12799 LowerXConstraint(EVT ConstraintVT) const {
12800   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12801   // 'f' like normal targets.
12802   if (ConstraintVT.isFloatingPoint()) {
12803     if (Subtarget->hasXMMInt())
12804       return "Y";
12805     if (Subtarget->hasXMM())
12806       return "x";
12807   }
12808
12809   return TargetLowering::LowerXConstraint(ConstraintVT);
12810 }
12811
12812 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12813 /// vector.  If it is invalid, don't add anything to Ops.
12814 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12815                                                      std::string &Constraint,
12816                                                      std::vector<SDValue>&Ops,
12817                                                      SelectionDAG &DAG) const {
12818   SDValue Result(0, 0);
12819
12820   // Only support length 1 constraints for now.
12821   if (Constraint.length() > 1) return;
12822
12823   char ConstraintLetter = Constraint[0];
12824   switch (ConstraintLetter) {
12825   default: break;
12826   case 'I':
12827     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12828       if (C->getZExtValue() <= 31) {
12829         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12830         break;
12831       }
12832     }
12833     return;
12834   case 'J':
12835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12836       if (C->getZExtValue() <= 63) {
12837         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12838         break;
12839       }
12840     }
12841     return;
12842   case 'K':
12843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12844       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12845         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12846         break;
12847       }
12848     }
12849     return;
12850   case 'N':
12851     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12852       if (C->getZExtValue() <= 255) {
12853         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12854         break;
12855       }
12856     }
12857     return;
12858   case 'e': {
12859     // 32-bit signed value
12860     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12861       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12862                                            C->getSExtValue())) {
12863         // Widen to 64 bits here to get it sign extended.
12864         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12865         break;
12866       }
12867     // FIXME gcc accepts some relocatable values here too, but only in certain
12868     // memory models; it's complicated.
12869     }
12870     return;
12871   }
12872   case 'Z': {
12873     // 32-bit unsigned value
12874     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12875       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12876                                            C->getZExtValue())) {
12877         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12878         break;
12879       }
12880     }
12881     // FIXME gcc accepts some relocatable values here too, but only in certain
12882     // memory models; it's complicated.
12883     return;
12884   }
12885   case 'i': {
12886     // Literal immediates are always ok.
12887     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12888       // Widen to 64 bits here to get it sign extended.
12889       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12890       break;
12891     }
12892
12893     // In any sort of PIC mode addresses need to be computed at runtime by
12894     // adding in a register or some sort of table lookup.  These can't
12895     // be used as immediates.
12896     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12897       return;
12898
12899     // If we are in non-pic codegen mode, we allow the address of a global (with
12900     // an optional displacement) to be used with 'i'.
12901     GlobalAddressSDNode *GA = 0;
12902     int64_t Offset = 0;
12903
12904     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12905     while (1) {
12906       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12907         Offset += GA->getOffset();
12908         break;
12909       } else if (Op.getOpcode() == ISD::ADD) {
12910         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12911           Offset += C->getZExtValue();
12912           Op = Op.getOperand(0);
12913           continue;
12914         }
12915       } else if (Op.getOpcode() == ISD::SUB) {
12916         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12917           Offset += -C->getZExtValue();
12918           Op = Op.getOperand(0);
12919           continue;
12920         }
12921       }
12922
12923       // Otherwise, this isn't something we can handle, reject it.
12924       return;
12925     }
12926
12927     const GlobalValue *GV = GA->getGlobal();
12928     // If we require an extra load to get this address, as in PIC mode, we
12929     // can't accept it.
12930     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12931                                                         getTargetMachine())))
12932       return;
12933
12934     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12935                                         GA->getValueType(0), Offset);
12936     break;
12937   }
12938   }
12939
12940   if (Result.getNode()) {
12941     Ops.push_back(Result);
12942     return;
12943   }
12944   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12945 }
12946
12947 std::pair<unsigned, const TargetRegisterClass*>
12948 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12949                                                 EVT VT) const {
12950   // First, see if this is a constraint that directly corresponds to an LLVM
12951   // register class.
12952   if (Constraint.size() == 1) {
12953     // GCC Constraint Letters
12954     switch (Constraint[0]) {
12955     default: break;
12956       // TODO: Slight differences here in allocation order and leaving
12957       // RIP in the class. Do they matter any more here than they do
12958       // in the normal allocation?
12959     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12960       if (Subtarget->is64Bit()) {
12961         if (VT == MVT::i32 || VT == MVT::f32)
12962           return std::make_pair(0U, X86::GR32RegisterClass);
12963         else if (VT == MVT::i16)
12964           return std::make_pair(0U, X86::GR16RegisterClass);
12965         else if (VT == MVT::i8 || VT == MVT::i1)
12966           return std::make_pair(0U, X86::GR8RegisterClass);
12967         else if (VT == MVT::i64 || VT == MVT::f64)
12968           return std::make_pair(0U, X86::GR64RegisterClass);
12969         break;
12970       }
12971       // 32-bit fallthrough
12972     case 'Q':   // Q_REGS
12973       if (VT == MVT::i32 || VT == MVT::f32)
12974         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12975       else if (VT == MVT::i16)
12976         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12977       else if (VT == MVT::i8 || VT == MVT::i1)
12978         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12979       else if (VT == MVT::i64)
12980         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12981       break;
12982     case 'r':   // GENERAL_REGS
12983     case 'l':   // INDEX_REGS
12984       if (VT == MVT::i8 || VT == MVT::i1)
12985         return std::make_pair(0U, X86::GR8RegisterClass);
12986       if (VT == MVT::i16)
12987         return std::make_pair(0U, X86::GR16RegisterClass);
12988       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12989         return std::make_pair(0U, X86::GR32RegisterClass);
12990       return std::make_pair(0U, X86::GR64RegisterClass);
12991     case 'R':   // LEGACY_REGS
12992       if (VT == MVT::i8 || VT == MVT::i1)
12993         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12994       if (VT == MVT::i16)
12995         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12996       if (VT == MVT::i32 || !Subtarget->is64Bit())
12997         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12998       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12999     case 'f':  // FP Stack registers.
13000       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13001       // value to the correct fpstack register class.
13002       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13003         return std::make_pair(0U, X86::RFP32RegisterClass);
13004       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13005         return std::make_pair(0U, X86::RFP64RegisterClass);
13006       return std::make_pair(0U, X86::RFP80RegisterClass);
13007     case 'y':   // MMX_REGS if MMX allowed.
13008       if (!Subtarget->hasMMX()) break;
13009       return std::make_pair(0U, X86::VR64RegisterClass);
13010     case 'Y':   // SSE_REGS if SSE2 allowed
13011       if (!Subtarget->hasXMMInt()) break;
13012       // FALL THROUGH.
13013     case 'x':   // SSE_REGS if SSE1 allowed
13014       if (!Subtarget->hasXMM()) break;
13015
13016       switch (VT.getSimpleVT().SimpleTy) {
13017       default: break;
13018       // Scalar SSE types.
13019       case MVT::f32:
13020       case MVT::i32:
13021         return std::make_pair(0U, X86::FR32RegisterClass);
13022       case MVT::f64:
13023       case MVT::i64:
13024         return std::make_pair(0U, X86::FR64RegisterClass);
13025       // Vector types.
13026       case MVT::v16i8:
13027       case MVT::v8i16:
13028       case MVT::v4i32:
13029       case MVT::v2i64:
13030       case MVT::v4f32:
13031       case MVT::v2f64:
13032         return std::make_pair(0U, X86::VR128RegisterClass);
13033       }
13034       break;
13035     }
13036   }
13037
13038   // Use the default implementation in TargetLowering to convert the register
13039   // constraint into a member of a register class.
13040   std::pair<unsigned, const TargetRegisterClass*> Res;
13041   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13042
13043   // Not found as a standard register?
13044   if (Res.second == 0) {
13045     // Map st(0) -> st(7) -> ST0
13046     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13047         tolower(Constraint[1]) == 's' &&
13048         tolower(Constraint[2]) == 't' &&
13049         Constraint[3] == '(' &&
13050         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13051         Constraint[5] == ')' &&
13052         Constraint[6] == '}') {
13053
13054       Res.first = X86::ST0+Constraint[4]-'0';
13055       Res.second = X86::RFP80RegisterClass;
13056       return Res;
13057     }
13058
13059     // GCC allows "st(0)" to be called just plain "st".
13060     if (StringRef("{st}").equals_lower(Constraint)) {
13061       Res.first = X86::ST0;
13062       Res.second = X86::RFP80RegisterClass;
13063       return Res;
13064     }
13065
13066     // flags -> EFLAGS
13067     if (StringRef("{flags}").equals_lower(Constraint)) {
13068       Res.first = X86::EFLAGS;
13069       Res.second = X86::CCRRegisterClass;
13070       return Res;
13071     }
13072
13073     // 'A' means EAX + EDX.
13074     if (Constraint == "A") {
13075       Res.first = X86::EAX;
13076       Res.second = X86::GR32_ADRegisterClass;
13077       return Res;
13078     }
13079     return Res;
13080   }
13081
13082   // Otherwise, check to see if this is a register class of the wrong value
13083   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13084   // turn into {ax},{dx}.
13085   if (Res.second->hasType(VT))
13086     return Res;   // Correct type already, nothing to do.
13087
13088   // All of the single-register GCC register classes map their values onto
13089   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13090   // really want an 8-bit or 32-bit register, map to the appropriate register
13091   // class and return the appropriate register.
13092   if (Res.second == X86::GR16RegisterClass) {
13093     if (VT == MVT::i8) {
13094       unsigned DestReg = 0;
13095       switch (Res.first) {
13096       default: break;
13097       case X86::AX: DestReg = X86::AL; break;
13098       case X86::DX: DestReg = X86::DL; break;
13099       case X86::CX: DestReg = X86::CL; break;
13100       case X86::BX: DestReg = X86::BL; break;
13101       }
13102       if (DestReg) {
13103         Res.first = DestReg;
13104         Res.second = X86::GR8RegisterClass;
13105       }
13106     } else if (VT == MVT::i32) {
13107       unsigned DestReg = 0;
13108       switch (Res.first) {
13109       default: break;
13110       case X86::AX: DestReg = X86::EAX; break;
13111       case X86::DX: DestReg = X86::EDX; break;
13112       case X86::CX: DestReg = X86::ECX; break;
13113       case X86::BX: DestReg = X86::EBX; break;
13114       case X86::SI: DestReg = X86::ESI; break;
13115       case X86::DI: DestReg = X86::EDI; break;
13116       case X86::BP: DestReg = X86::EBP; break;
13117       case X86::SP: DestReg = X86::ESP; break;
13118       }
13119       if (DestReg) {
13120         Res.first = DestReg;
13121         Res.second = X86::GR32RegisterClass;
13122       }
13123     } else if (VT == MVT::i64) {
13124       unsigned DestReg = 0;
13125       switch (Res.first) {
13126       default: break;
13127       case X86::AX: DestReg = X86::RAX; break;
13128       case X86::DX: DestReg = X86::RDX; break;
13129       case X86::CX: DestReg = X86::RCX; break;
13130       case X86::BX: DestReg = X86::RBX; break;
13131       case X86::SI: DestReg = X86::RSI; break;
13132       case X86::DI: DestReg = X86::RDI; break;
13133       case X86::BP: DestReg = X86::RBP; break;
13134       case X86::SP: DestReg = X86::RSP; break;
13135       }
13136       if (DestReg) {
13137         Res.first = DestReg;
13138         Res.second = X86::GR64RegisterClass;
13139       }
13140     }
13141   } else if (Res.second == X86::FR32RegisterClass ||
13142              Res.second == X86::FR64RegisterClass ||
13143              Res.second == X86::VR128RegisterClass) {
13144     // Handle references to XMM physical registers that got mapped into the
13145     // wrong class.  This can happen with constraints like {xmm0} where the
13146     // target independent register mapper will just pick the first match it can
13147     // find, ignoring the required type.
13148     if (VT == MVT::f32)
13149       Res.second = X86::FR32RegisterClass;
13150     else if (VT == MVT::f64)
13151       Res.second = X86::FR64RegisterClass;
13152     else if (X86::VR128RegisterClass->hasType(VT))
13153       Res.second = X86::VR128RegisterClass;
13154   }
13155
13156   return Res;
13157 }