Remove TargetOptions.h dependency from X86Subtarget.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 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::FPTOUINT_F64_I64, "_ftol2");
239     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244   }
245
246   if (Subtarget->isTargetDarwin()) {
247     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248     setUseUnderscoreSetJmp(false);
249     setUseUnderscoreLongJmp(false);
250   } else if (Subtarget->isTargetMingw()) {
251     // MS runtime is weird: it exports _setjmp, but longjmp!
252     setUseUnderscoreSetJmp(true);
253     setUseUnderscoreLongJmp(false);
254   } else {
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(true);
257   }
258
259   // Set up the register classes.
260   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263   if (Subtarget->is64Bit())
264     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268   // We don't accept any truncstore of integer registers.
269   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276   // SETOEQ and SETUNE require checking two conditions.
277   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285   // operation.
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290   if (Subtarget->is64Bit()) {
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293   } else if (!UseSoftFloat) {
294     // We have an algorithm for SSE2->double, and we turn this into a
295     // 64-bit FILD followed by conditional FADD for other targets.
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297     // We have an algorithm for SSE2, and we turn this into a 64-bit
298     // FILD for other targets.
299     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300   }
301
302   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303   // this operation.
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307   if (!UseSoftFloat) {
308     // SSE has no i16 to fp conversion, only i32
309     if (X86ScalarSSEf32) {
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311       // f32 and f64 cases are Legal, f80 case is not
312       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313     } else {
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316     }
317   } else {
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320   }
321
322   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323   // are Legal, f80 is custom lowered.
324   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332   if (X86ScalarSSEf32) {
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334     // f32 and f64 cases are Legal, f80 case is not
335     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336   } else {
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339   }
340
341   // Handle FP_TO_UINT by promoting the destination to a larger signed
342   // conversion.
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350   } else if (!UseSoftFloat) {
351     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352       // Expand FP_TO_UINT into a select.
353       // FIXME: We would like to use a Custom expander here eventually to do
354       // the optimal thing for SSE vs. the default expansion in the legalizer.
355       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356     else
357       // With SSE3 we can use fisttpll to convert to a signed i64; without
358       // SSE, we're stuck with a fistpll.
359       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360   }
361
362   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363   if (!X86ScalarSSEf64) {
364     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366     if (Subtarget->is64Bit()) {
367       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368       // Without SSE, i64->f64 goes through memory.
369       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370     }
371   }
372
373   // Scalar integer divide and remainder are lowered to use operations that
374   // produce two results, to match the available instructions. This exposes
375   // the two-result form to trivial CSE, which is able to combine x/y and x%y
376   // into a single instruction.
377   //
378   // Scalar integer multiply-high is also lowered to use two-result
379   // operations, to match the available instructions. However, plain multiply
380   // (low) operations are left as Legal, as there are single-result
381   // instructions for this in x86. Using the two-result multiply instructions
382   // when both high and low results are needed must be arranged by dagcombine.
383   for (unsigned i = 0, e = 4; i != e; ++i) {
384     MVT VT = IntVTs[i];
385     setOperationAction(ISD::MULHS, VT, Expand);
386     setOperationAction(ISD::MULHU, VT, Expand);
387     setOperationAction(ISD::SDIV, VT, Expand);
388     setOperationAction(ISD::UDIV, VT, Expand);
389     setOperationAction(ISD::SREM, VT, Expand);
390     setOperationAction(ISD::UREM, VT, Expand);
391
392     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393     setOperationAction(ISD::ADDC, VT, Custom);
394     setOperationAction(ISD::ADDE, VT, Custom);
395     setOperationAction(ISD::SUBC, VT, Custom);
396     setOperationAction(ISD::SUBE, VT, Custom);
397   }
398
399   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423   }
424
425   if (Subtarget->hasPOPCNT()) {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427   } else {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433   }
434
435   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438   // These should be promoted to a larger select which is supported.
439   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440   // X86 wants to expand cmov itself.
441   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456   }
457   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459   // Darwin ABI issue.
460   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464   if (Subtarget->is64Bit())
465     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474   }
475   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479   if (Subtarget->is64Bit()) {
480     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483   }
484
485   if (Subtarget->hasXMM())
486     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488   // We may not have a libcall for MEMBARRIER so we should lower this.
489   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491   // On X86 and X86-64, atomic operations are lowered to locked instructions.
492   // Locked instructions, in turn, have implicit fence semantics (all memory
493   // operations are flushed before issuing the locked instruction, and they
494   // are not buffered), so we can fold away the common pattern of
495   // fence-atomic-fence.
496   setShouldFoldAtomicFences(true);
497
498   // Expand certain atomics
499   for (unsigned i = 0, e = 4; i != e; ++i) {
500     MVT VT = IntVTs[i];
501     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503   }
504
505   if (!Subtarget->is64Bit()) {
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   if (Subtarget->is64Bit()) {
544     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546   } else {
547     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549   }
550
551   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553   setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                      (Subtarget->isTargetCOFF()
556                       && !Subtarget->isTargetEnvMacho()
557                       ? Custom : Expand));
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // Lower this to FGETSIGNx86 plus an AND.
578     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
580
581     // We don't support sin/cos/fmod
582     setOperationAction(ISD::FSIN , MVT::f64, Expand);
583     setOperationAction(ISD::FCOS , MVT::f64, Expand);
584     setOperationAction(ISD::FSIN , MVT::f32, Expand);
585     setOperationAction(ISD::FCOS , MVT::f32, Expand);
586
587     // Expand FP immediates into loads from the stack, except for the special
588     // cases we handle.
589     addLegalFPImmediate(APFloat(+0.0)); // xorpd
590     addLegalFPImmediate(APFloat(+0.0f)); // xorps
591   } else if (!UseSoftFloat && X86ScalarSSEf32) {
592     // Use SSE for f32, x87 for f64.
593     // Set up the FP register classes.
594     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
596
597     // Use ANDPS to simulate FABS.
598     setOperationAction(ISD::FABS , MVT::f32, Custom);
599
600     // Use XORP to simulate FNEG.
601     setOperationAction(ISD::FNEG , MVT::f32, Custom);
602
603     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
604
605     // Use ANDPS and ORPS to simulate FCOPYSIGN.
606     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
608
609     // We don't support sin/cos/fmod
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Special cases we handle for FP constants.
614     addLegalFPImmediate(APFloat(+0.0f)); // xorps
615     addLegalFPImmediate(APFloat(+0.0)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619
620     if (!UnsafeFPMath) {
621       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623     }
624   } else if (!UseSoftFloat) {
625     // f32 and f64 in x87.
626     // Set up the FP register classes.
627     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
634
635     if (!UnsafeFPMath) {
636       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
637       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
638     }
639     addLegalFPImmediate(APFloat(+0.0)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
647   }
648
649   // Long double always uses X87.
650   if (!UseSoftFloat) {
651     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
653     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654     {
655       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656       addLegalFPImmediate(TmpFlt);  // FLD0
657       TmpFlt.changeSign();
658       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
659
660       bool ignored;
661       APFloat TmpFlt2(+1.0);
662       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663                       &ignored);
664       addLegalFPImmediate(TmpFlt2);  // FLD1
665       TmpFlt2.changeSign();
666       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
667     }
668
669     if (!UnsafeFPMath) {
670       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
671       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
672     }
673   }
674
675   // Always use a library call for pow.
676   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
677   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
679
680   setOperationAction(ISD::FLOG, MVT::f80, Expand);
681   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
683   setOperationAction(ISD::FEXP, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
685
686   // First set operation action for all vector types to either promote
687   // (for widening) or expand (for scalarization). Then we will selectively
688   // turn on ones that can be effectively codegen'd.
689   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
690        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
691     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
706     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
741     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747       setTruncStoreAction((MVT::SimpleValueType)VT,
748                           (MVT::SimpleValueType)InnerVT, Expand);
749     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
752   }
753
754   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755   // with -msoft-float, disable use of MMX as well.
756   if (!UseSoftFloat && Subtarget->hasMMX()) {
757     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758     // No operations on x86mmx supported, everything uses intrinsics.
759   }
760
761   // MMX-sized vectors (other than x86mmx) are expected to be expanded
762   // into smaller operations.
763   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
764   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
765   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
767   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
769   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
770   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
771   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
772   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
773   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
774   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
775   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
776   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
777   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
778   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
779   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
783   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
784   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
785   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
786   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
788   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
792
793   if (!UseSoftFloat && Subtarget->hasXMM()) {
794     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
795
796     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
801     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
802     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
803     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
804     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
805     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
807     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
808   }
809
810   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
811     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
812
813     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814     // registers cannot be used even for integer operations.
815     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
819
820     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
821     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
822     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
823     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
825     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
826     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
827     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
828     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
829     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
830     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
831     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
835     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
836
837     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
838     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
841
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
847
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
853
854     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856       EVT VT = (MVT::SimpleValueType)i;
857       // Do not attempt to custom lower non-power-of-2 vectors
858       if (!isPowerOf2_32(VT.getVectorNumElements()))
859         continue;
860       // Do not attempt to custom lower non-128-bit vectors
861       if (!VT.is128BitVector())
862         continue;
863       setOperationAction(ISD::BUILD_VECTOR,
864                          VT.getSimpleVT().SimpleTy, Custom);
865       setOperationAction(ISD::VECTOR_SHUFFLE,
866                          VT.getSimpleVT().SimpleTy, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868                          VT.getSimpleVT().SimpleTy, Custom);
869     }
870
871     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
873     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
876     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
877
878     if (Subtarget->is64Bit()) {
879       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
880       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
881     }
882
883     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
886       EVT VT = SVT;
887
888       // Do not attempt to promote non-128-bit vectors
889       if (!VT.is128BitVector())
890         continue;
891
892       setOperationAction(ISD::AND,    SVT, Promote);
893       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
894       setOperationAction(ISD::OR,     SVT, Promote);
895       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
896       setOperationAction(ISD::XOR,    SVT, Promote);
897       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
898       setOperationAction(ISD::LOAD,   SVT, Promote);
899       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
900       setOperationAction(ISD::SELECT, SVT, Promote);
901       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
902     }
903
904     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914   }
915
916   if (Subtarget->hasSSE41()) {
917     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
922     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
923     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
924     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
925     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
926     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
927
928     // FIXME: Do we need to handle scalar-to-vector here?
929     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
930
931     // Can turn SHL into an integer multiply.
932     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
933     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
934
935     // i8 and i16 vectors are custom , because the source register and source
936     // source memory operand types are not the same width.  f32 vectors are
937     // custom since the immediate controlling the insert encodes additional
938     // information.
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
943
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
948
949     if (Subtarget->is64Bit()) {
950       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
952     }
953   }
954
955   if (Subtarget->hasSSE2()) {
956     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
959
960     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
961     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
962     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
963
964     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
966   }
967
968   if (Subtarget->hasSSE42())
969     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
970
971   if (!UseSoftFloat && Subtarget->hasAVX()) {
972     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
973     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
977
978     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
998     // insert_vector_elt extract_subvector and extract_vector_elt for
999     // 256-bit types.
1000     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1002          ++i) {
1003       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004       // Do not attempt to custom lower non-256-bit vectors
1005       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1006           || (MVT(VT).getSizeInBits() < 256))
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1013     }
1014     // Custom-lower insert_subvector and extract_subvector based on
1015     // the result type.
1016     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1017          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1018          ++i) {
1019       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1020       // Do not attempt to custom lower non-256-bit vectors
1021       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1022         continue;
1023
1024       if (MVT(VT).getSizeInBits() == 128) {
1025         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1026       }
1027       else if (MVT(VT).getSizeInBits() == 256) {
1028         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1029       }
1030     }
1031
1032     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1033     // Don't promote loads because we need them for VPERM vector index versions.
1034
1035     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1036          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1037          VT++) {
1038       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1039           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1040         continue;
1041       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1044       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1047       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1048       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1049       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1050       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1051     }
1052   }
1053
1054   // We want to custom lower some of our intrinsics.
1055   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1056
1057
1058   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1059   // handle type legalization for these operations here.
1060   //
1061   // FIXME: We really should do custom legalization for addition and
1062   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1063   // than generic legalization for 64-bit multiplication-with-overflow, though.
1064   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1065     // Add/Sub/Mul with overflow operations are custom lowered.
1066     MVT VT = IntVTs[i];
1067     setOperationAction(ISD::SADDO, VT, Custom);
1068     setOperationAction(ISD::UADDO, VT, Custom);
1069     setOperationAction(ISD::SSUBO, VT, Custom);
1070     setOperationAction(ISD::USUBO, VT, Custom);
1071     setOperationAction(ISD::SMULO, VT, Custom);
1072     setOperationAction(ISD::UMULO, VT, Custom);
1073   }
1074
1075   // There are no 8-bit 3-address imul/mul instructions
1076   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1077   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1078
1079   if (!Subtarget->is64Bit()) {
1080     // These libcalls are not available in 32-bit.
1081     setLibcallName(RTLIB::SHL_I128, 0);
1082     setLibcallName(RTLIB::SRL_I128, 0);
1083     setLibcallName(RTLIB::SRA_I128, 0);
1084   }
1085
1086   // We have target-specific dag combine patterns for the following nodes:
1087   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1088   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1089   setTargetDAGCombine(ISD::BUILD_VECTOR);
1090   setTargetDAGCombine(ISD::SELECT);
1091   setTargetDAGCombine(ISD::SHL);
1092   setTargetDAGCombine(ISD::SRA);
1093   setTargetDAGCombine(ISD::SRL);
1094   setTargetDAGCombine(ISD::OR);
1095   setTargetDAGCombine(ISD::AND);
1096   setTargetDAGCombine(ISD::ADD);
1097   setTargetDAGCombine(ISD::SUB);
1098   setTargetDAGCombine(ISD::STORE);
1099   setTargetDAGCombine(ISD::ZERO_EXTEND);
1100   setTargetDAGCombine(ISD::SINT_TO_FP);
1101   if (Subtarget->is64Bit())
1102     setTargetDAGCombine(ISD::MUL);
1103
1104   computeRegisterProperties();
1105
1106   // On Darwin, -Os means optimize for size without hurting performance,
1107   // do not reduce the limit.
1108   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1109   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1110   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1111   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1112   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1113   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1114   setPrefLoopAlignment(16);
1115   benefitFromCodePlacementOpt = true;
1116
1117   setPrefFunctionAlignment(4);
1118 }
1119
1120
1121 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1122   return MVT::i8;
1123 }
1124
1125
1126 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1127 /// the desired ByVal argument alignment.
1128 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1129   if (MaxAlign == 16)
1130     return;
1131   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1132     if (VTy->getBitWidth() == 128)
1133       MaxAlign = 16;
1134   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1135     unsigned EltAlign = 0;
1136     getMaxByValAlign(ATy->getElementType(), EltAlign);
1137     if (EltAlign > MaxAlign)
1138       MaxAlign = EltAlign;
1139   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1140     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1141       unsigned EltAlign = 0;
1142       getMaxByValAlign(STy->getElementType(i), EltAlign);
1143       if (EltAlign > MaxAlign)
1144         MaxAlign = EltAlign;
1145       if (MaxAlign == 16)
1146         break;
1147     }
1148   }
1149   return;
1150 }
1151
1152 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1153 /// function arguments in the caller parameter area. For X86, aggregates
1154 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1155 /// are at 4-byte boundaries.
1156 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1157   if (Subtarget->is64Bit()) {
1158     // Max of 8 and alignment of type.
1159     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1160     if (TyAlign > 8)
1161       return TyAlign;
1162     return 8;
1163   }
1164
1165   unsigned Align = 4;
1166   if (Subtarget->hasXMM())
1167     getMaxByValAlign(Ty, Align);
1168   return Align;
1169 }
1170
1171 /// getOptimalMemOpType - Returns the target specific optimal type for load
1172 /// and store operations as a result of memset, memcpy, and memmove
1173 /// lowering. If DstAlign is zero that means it's safe to destination
1174 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1175 /// means there isn't a need to check it against alignment requirement,
1176 /// probably because the source does not need to be loaded. If
1177 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1178 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1179 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1180 /// constant so it does not need to be loaded.
1181 /// It returns EVT::Other if the type should be determined using generic
1182 /// target-independent logic.
1183 EVT
1184 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1185                                        unsigned DstAlign, unsigned SrcAlign,
1186                                        bool NonScalarIntSafe,
1187                                        bool MemcpyStrSrc,
1188                                        MachineFunction &MF) const {
1189   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1190   // linux.  This is because the stack realignment code can't handle certain
1191   // cases like PR2962.  This should be removed when PR2962 is fixed.
1192   const Function *F = MF.getFunction();
1193   if (NonScalarIntSafe &&
1194       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1195     if (Size >= 16 &&
1196         (Subtarget->isUnalignedMemAccessFast() ||
1197          ((DstAlign == 0 || DstAlign >= 16) &&
1198           (SrcAlign == 0 || SrcAlign >= 16))) &&
1199         Subtarget->getStackAlignment() >= 16) {
1200       if (Subtarget->hasSSE2())
1201         return MVT::v4i32;
1202       if (Subtarget->hasSSE1())
1203         return MVT::v4f32;
1204     } else if (!MemcpyStrSrc && Size >= 8 &&
1205                !Subtarget->is64Bit() &&
1206                Subtarget->getStackAlignment() >= 8 &&
1207                Subtarget->hasXMMInt()) {
1208       // Do not use f64 to lower memcpy if source is string constant. It's
1209       // better to use i32 to avoid the loads.
1210       return MVT::f64;
1211     }
1212   }
1213   if (Subtarget->is64Bit() && Size >= 8)
1214     return MVT::i64;
1215   return MVT::i32;
1216 }
1217
1218 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1219 /// current function.  The returned value is a member of the
1220 /// MachineJumpTableInfo::JTEntryKind enum.
1221 unsigned X86TargetLowering::getJumpTableEncoding() const {
1222   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1223   // symbol.
1224   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1225       Subtarget->isPICStyleGOT())
1226     return MachineJumpTableInfo::EK_Custom32;
1227
1228   // Otherwise, use the normal jump table encoding heuristics.
1229   return TargetLowering::getJumpTableEncoding();
1230 }
1231
1232 const MCExpr *
1233 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1234                                              const MachineBasicBlock *MBB,
1235                                              unsigned uid,MCContext &Ctx) const{
1236   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237          Subtarget->isPICStyleGOT());
1238   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1239   // entries.
1240   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1241                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1242 }
1243
1244 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1245 /// jumptable.
1246 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1247                                                     SelectionDAG &DAG) const {
1248   if (!Subtarget->is64Bit())
1249     // This doesn't have DebugLoc associated with it, but is not really the
1250     // same as a Register.
1251     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1252   return Table;
1253 }
1254
1255 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1256 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1257 /// MCExpr.
1258 const MCExpr *X86TargetLowering::
1259 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1260                              MCContext &Ctx) const {
1261   // X86-64 uses RIP relative addressing based on the jump table label.
1262   if (Subtarget->isPICStyleRIPRel())
1263     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1264
1265   // Otherwise, the reference is relative to the PIC base.
1266   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1267 }
1268
1269 // FIXME: Why this routine is here? Move to RegInfo!
1270 std::pair<const TargetRegisterClass*, uint8_t>
1271 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1272   const TargetRegisterClass *RRC = 0;
1273   uint8_t Cost = 1;
1274   switch (VT.getSimpleVT().SimpleTy) {
1275   default:
1276     return TargetLowering::findRepresentativeClass(VT);
1277   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1278     RRC = (Subtarget->is64Bit()
1279            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1280     break;
1281   case MVT::x86mmx:
1282     RRC = X86::VR64RegisterClass;
1283     break;
1284   case MVT::f32: case MVT::f64:
1285   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1286   case MVT::v4f32: case MVT::v2f64:
1287   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1288   case MVT::v4f64:
1289     RRC = X86::VR128RegisterClass;
1290     break;
1291   }
1292   return std::make_pair(RRC, Cost);
1293 }
1294
1295 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1296                                                unsigned &Offset) const {
1297   if (!Subtarget->isTargetLinux())
1298     return false;
1299
1300   if (Subtarget->is64Bit()) {
1301     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1302     Offset = 0x28;
1303     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1304       AddressSpace = 256;
1305     else
1306       AddressSpace = 257;
1307   } else {
1308     // %gs:0x14 on i386
1309     Offset = 0x14;
1310     AddressSpace = 256;
1311   }
1312   return true;
1313 }
1314
1315
1316 //===----------------------------------------------------------------------===//
1317 //               Return Value Calling Convention Implementation
1318 //===----------------------------------------------------------------------===//
1319
1320 #include "X86GenCallingConv.inc"
1321
1322 bool
1323 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1324                                   MachineFunction &MF, bool isVarArg,
1325                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1326                         LLVMContext &Context) const {
1327   SmallVector<CCValAssign, 16> RVLocs;
1328   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1329                  RVLocs, Context);
1330   return CCInfo.CheckReturn(Outs, RetCC_X86);
1331 }
1332
1333 SDValue
1334 X86TargetLowering::LowerReturn(SDValue Chain,
1335                                CallingConv::ID CallConv, bool isVarArg,
1336                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1337                                const SmallVectorImpl<SDValue> &OutVals,
1338                                DebugLoc dl, SelectionDAG &DAG) const {
1339   MachineFunction &MF = DAG.getMachineFunction();
1340   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1341
1342   SmallVector<CCValAssign, 16> RVLocs;
1343   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1344                  RVLocs, *DAG.getContext());
1345   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1346
1347   // Add the regs to the liveout set for the function.
1348   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1349   for (unsigned i = 0; i != RVLocs.size(); ++i)
1350     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1351       MRI.addLiveOut(RVLocs[i].getLocReg());
1352
1353   SDValue Flag;
1354
1355   SmallVector<SDValue, 6> RetOps;
1356   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1357   // Operand #1 = Bytes To Pop
1358   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1359                    MVT::i16));
1360
1361   // Copy the result values into the output registers.
1362   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1363     CCValAssign &VA = RVLocs[i];
1364     assert(VA.isRegLoc() && "Can only return in registers!");
1365     SDValue ValToCopy = OutVals[i];
1366     EVT ValVT = ValToCopy.getValueType();
1367
1368     // If this is x86-64, and we disabled SSE, we can't return FP values,
1369     // or SSE or MMX vectors.
1370     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1371          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1372           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1373       report_fatal_error("SSE register return with SSE disabled");
1374     }
1375     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1376     // llvm-gcc has never done it right and no one has noticed, so this
1377     // should be OK for now.
1378     if (ValVT == MVT::f64 &&
1379         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1380       report_fatal_error("SSE2 register return with SSE2 disabled");
1381
1382     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1383     // the RET instruction and handled by the FP Stackifier.
1384     if (VA.getLocReg() == X86::ST0 ||
1385         VA.getLocReg() == X86::ST1) {
1386       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1387       // change the value to the FP stack register class.
1388       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1389         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1390       RetOps.push_back(ValToCopy);
1391       // Don't emit a copytoreg.
1392       continue;
1393     }
1394
1395     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1396     // which is returned in RAX / RDX.
1397     if (Subtarget->is64Bit()) {
1398       if (ValVT == MVT::x86mmx) {
1399         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1400           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1401           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1402                                   ValToCopy);
1403           // If we don't have SSE2 available, convert to v4f32 so the generated
1404           // register is legal.
1405           if (!Subtarget->hasSSE2())
1406             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1407         }
1408       }
1409     }
1410
1411     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1412     Flag = Chain.getValue(1);
1413   }
1414
1415   // The x86-64 ABI for returning structs by value requires that we copy
1416   // the sret argument into %rax for the return. We saved the argument into
1417   // a virtual register in the entry block, so now we copy the value out
1418   // and into %rax.
1419   if (Subtarget->is64Bit() &&
1420       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1421     MachineFunction &MF = DAG.getMachineFunction();
1422     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1423     unsigned Reg = FuncInfo->getSRetReturnReg();
1424     assert(Reg &&
1425            "SRetReturnReg should have been set in LowerFormalArguments().");
1426     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1427
1428     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1429     Flag = Chain.getValue(1);
1430
1431     // RAX now acts like a return value.
1432     MRI.addLiveOut(X86::RAX);
1433   }
1434
1435   RetOps[0] = Chain;  // Update chain.
1436
1437   // Add the flag if we have it.
1438   if (Flag.getNode())
1439     RetOps.push_back(Flag);
1440
1441   return DAG.getNode(X86ISD::RET_FLAG, dl,
1442                      MVT::Other, &RetOps[0], RetOps.size());
1443 }
1444
1445 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1446   if (N->getNumValues() != 1)
1447     return false;
1448   if (!N->hasNUsesOfValue(1, 0))
1449     return false;
1450
1451   SDNode *Copy = *N->use_begin();
1452   if (Copy->getOpcode() != ISD::CopyToReg &&
1453       Copy->getOpcode() != ISD::FP_EXTEND)
1454     return false;
1455
1456   bool HasRet = false;
1457   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1458        UI != UE; ++UI) {
1459     if (UI->getOpcode() != X86ISD::RET_FLAG)
1460       return false;
1461     HasRet = true;
1462   }
1463
1464   return HasRet;
1465 }
1466
1467 EVT
1468 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1469                                             ISD::NodeType ExtendKind) const {
1470   MVT ReturnMVT;
1471   // TODO: Is this also valid on 32-bit?
1472   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1473     ReturnMVT = MVT::i8;
1474   else
1475     ReturnMVT = MVT::i32;
1476
1477   EVT MinVT = getRegisterType(Context, ReturnMVT);
1478   return VT.bitsLT(MinVT) ? MinVT : VT;
1479 }
1480
1481 /// LowerCallResult - Lower the result values of a call into the
1482 /// appropriate copies out of appropriate physical registers.
1483 ///
1484 SDValue
1485 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1486                                    CallingConv::ID CallConv, bool isVarArg,
1487                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1488                                    DebugLoc dl, SelectionDAG &DAG,
1489                                    SmallVectorImpl<SDValue> &InVals) const {
1490
1491   // Assign locations to each value returned by this call.
1492   SmallVector<CCValAssign, 16> RVLocs;
1493   bool Is64Bit = Subtarget->is64Bit();
1494   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1495                  getTargetMachine(), RVLocs, *DAG.getContext());
1496   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1497
1498   // Copy all of the result registers out of their specified physreg.
1499   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1500     CCValAssign &VA = RVLocs[i];
1501     EVT CopyVT = VA.getValVT();
1502
1503     // If this is x86-64, and we disabled SSE, we can't return FP values
1504     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1505         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1506       report_fatal_error("SSE register return with SSE disabled");
1507     }
1508
1509     SDValue Val;
1510
1511     // If this is a call to a function that returns an fp value on the floating
1512     // point stack, we must guarantee the the value is popped from the stack, so
1513     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1514     // if the return value is not used. We use the FpGET_ST0 instructions
1515     // instead.
1516     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1517       // If we prefer to use the value in xmm registers, copy it out as f80 and
1518       // use a truncate to move it from fp stack reg to xmm reg.
1519       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1520       bool isST0 = VA.getLocReg() == X86::ST0;
1521       unsigned Opc = 0;
1522       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1523       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1524       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1525       SDValue Ops[] = { Chain, InFlag };
1526       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1527                                          Ops, 2), 1);
1528       Val = Chain.getValue(0);
1529
1530       // Round the f80 to the right size, which also moves it to the appropriate
1531       // xmm register.
1532       if (CopyVT != VA.getValVT())
1533         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1534                           // This truncation won't change the value.
1535                           DAG.getIntPtrConstant(1));
1536     } else {
1537       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1538                                  CopyVT, InFlag).getValue(1);
1539       Val = Chain.getValue(0);
1540     }
1541     InFlag = Chain.getValue(2);
1542     InVals.push_back(Val);
1543   }
1544
1545   return Chain;
1546 }
1547
1548
1549 //===----------------------------------------------------------------------===//
1550 //                C & StdCall & Fast Calling Convention implementation
1551 //===----------------------------------------------------------------------===//
1552 //  StdCall calling convention seems to be standard for many Windows' API
1553 //  routines and around. It differs from C calling convention just a little:
1554 //  callee should clean up the stack, not caller. Symbols should be also
1555 //  decorated in some fancy way :) It doesn't support any vector arguments.
1556 //  For info on fast calling convention see Fast Calling Convention (tail call)
1557 //  implementation LowerX86_32FastCCCallTo.
1558
1559 /// CallIsStructReturn - Determines whether a call uses struct return
1560 /// semantics.
1561 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1562   if (Outs.empty())
1563     return false;
1564
1565   return Outs[0].Flags.isSRet();
1566 }
1567
1568 /// ArgsAreStructReturn - Determines whether a function uses struct
1569 /// return semantics.
1570 static bool
1571 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1572   if (Ins.empty())
1573     return false;
1574
1575   return Ins[0].Flags.isSRet();
1576 }
1577
1578 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1579 /// by "Src" to address "Dst" with size and alignment information specified by
1580 /// the specific parameter attribute. The copy will be passed as a byval
1581 /// function parameter.
1582 static SDValue
1583 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1584                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1585                           DebugLoc dl) {
1586   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1587
1588   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1589                        /*isVolatile*/false, /*AlwaysInline=*/true,
1590                        MachinePointerInfo(), MachinePointerInfo());
1591 }
1592
1593 /// IsTailCallConvention - Return true if the calling convention is one that
1594 /// supports tail call optimization.
1595 static bool IsTailCallConvention(CallingConv::ID CC) {
1596   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1597 }
1598
1599 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1600   if (!CI->isTailCall())
1601     return false;
1602
1603   CallSite CS(CI);
1604   CallingConv::ID CalleeCC = CS.getCallingConv();
1605   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1606     return false;
1607
1608   return true;
1609 }
1610
1611 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1612 /// a tailcall target by changing its ABI.
1613 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1614   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1615 }
1616
1617 SDValue
1618 X86TargetLowering::LowerMemArgument(SDValue Chain,
1619                                     CallingConv::ID CallConv,
1620                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1621                                     DebugLoc dl, SelectionDAG &DAG,
1622                                     const CCValAssign &VA,
1623                                     MachineFrameInfo *MFI,
1624                                     unsigned i) const {
1625   // Create the nodes corresponding to a load from this parameter slot.
1626   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1627   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1628   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1629   EVT ValVT;
1630
1631   // If value is passed by pointer we have address passed instead of the value
1632   // itself.
1633   if (VA.getLocInfo() == CCValAssign::Indirect)
1634     ValVT = VA.getLocVT();
1635   else
1636     ValVT = VA.getValVT();
1637
1638   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1639   // changed with more analysis.
1640   // In case of tail call optimization mark all arguments mutable. Since they
1641   // could be overwritten by lowering of arguments in case of a tail call.
1642   if (Flags.isByVal()) {
1643     unsigned Bytes = Flags.getByValSize();
1644     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1645     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1646     return DAG.getFrameIndex(FI, getPointerTy());
1647   } else {
1648     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1649                                     VA.getLocMemOffset(), isImmutable);
1650     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1651     return DAG.getLoad(ValVT, dl, Chain, FIN,
1652                        MachinePointerInfo::getFixedStack(FI),
1653                        false, false, 0);
1654   }
1655 }
1656
1657 SDValue
1658 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1659                                         CallingConv::ID CallConv,
1660                                         bool isVarArg,
1661                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1662                                         DebugLoc dl,
1663                                         SelectionDAG &DAG,
1664                                         SmallVectorImpl<SDValue> &InVals)
1665                                           const {
1666   MachineFunction &MF = DAG.getMachineFunction();
1667   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1668
1669   const Function* Fn = MF.getFunction();
1670   if (Fn->hasExternalLinkage() &&
1671       Subtarget->isTargetCygMing() &&
1672       Fn->getName() == "main")
1673     FuncInfo->setForceFramePointer(true);
1674
1675   MachineFrameInfo *MFI = MF.getFrameInfo();
1676   bool Is64Bit = Subtarget->is64Bit();
1677   bool IsWin64 = Subtarget->isTargetWin64();
1678
1679   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1680          "Var args not supported with calling convention fastcc or ghc");
1681
1682   // Assign locations to all of the incoming arguments.
1683   SmallVector<CCValAssign, 16> ArgLocs;
1684   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1685                  ArgLocs, *DAG.getContext());
1686
1687   // Allocate shadow area for Win64
1688   if (IsWin64) {
1689     CCInfo.AllocateStack(32, 8);
1690   }
1691
1692   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1693
1694   unsigned LastVal = ~0U;
1695   SDValue ArgValue;
1696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1697     CCValAssign &VA = ArgLocs[i];
1698     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1699     // places.
1700     assert(VA.getValNo() != LastVal &&
1701            "Don't support value assigned to multiple locs yet");
1702     LastVal = VA.getValNo();
1703
1704     if (VA.isRegLoc()) {
1705       EVT RegVT = VA.getLocVT();
1706       TargetRegisterClass *RC = NULL;
1707       if (RegVT == MVT::i32)
1708         RC = X86::GR32RegisterClass;
1709       else if (Is64Bit && RegVT == MVT::i64)
1710         RC = X86::GR64RegisterClass;
1711       else if (RegVT == MVT::f32)
1712         RC = X86::FR32RegisterClass;
1713       else if (RegVT == MVT::f64)
1714         RC = X86::FR64RegisterClass;
1715       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1716         RC = X86::VR256RegisterClass;
1717       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1718         RC = X86::VR128RegisterClass;
1719       else if (RegVT == MVT::x86mmx)
1720         RC = X86::VR64RegisterClass;
1721       else
1722         llvm_unreachable("Unknown argument type!");
1723
1724       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1725       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1726
1727       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1728       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1729       // right size.
1730       if (VA.getLocInfo() == CCValAssign::SExt)
1731         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1732                                DAG.getValueType(VA.getValVT()));
1733       else if (VA.getLocInfo() == CCValAssign::ZExt)
1734         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1735                                DAG.getValueType(VA.getValVT()));
1736       else if (VA.getLocInfo() == CCValAssign::BCvt)
1737         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1738
1739       if (VA.isExtInLoc()) {
1740         // Handle MMX values passed in XMM regs.
1741         if (RegVT.isVector()) {
1742           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1743                                  ArgValue);
1744         } else
1745           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1746       }
1747     } else {
1748       assert(VA.isMemLoc());
1749       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1750     }
1751
1752     // If value is passed via pointer - do a load.
1753     if (VA.getLocInfo() == CCValAssign::Indirect)
1754       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1755                              MachinePointerInfo(), false, false, 0);
1756
1757     InVals.push_back(ArgValue);
1758   }
1759
1760   // The x86-64 ABI for returning structs by value requires that we copy
1761   // the sret argument into %rax for the return. Save the argument into
1762   // a virtual register so that we can access it from the return points.
1763   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1764     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1765     unsigned Reg = FuncInfo->getSRetReturnReg();
1766     if (!Reg) {
1767       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1768       FuncInfo->setSRetReturnReg(Reg);
1769     }
1770     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1771     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1772   }
1773
1774   unsigned StackSize = CCInfo.getNextStackOffset();
1775   // Align stack specially for tail calls.
1776   if (FuncIsMadeTailCallSafe(CallConv))
1777     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1778
1779   // If the function takes variable number of arguments, make a frame index for
1780   // the start of the first vararg value... for expansion of llvm.va_start.
1781   if (isVarArg) {
1782     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1783                     CallConv != CallingConv::X86_ThisCall)) {
1784       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1785     }
1786     if (Is64Bit) {
1787       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1788
1789       // FIXME: We should really autogenerate these arrays
1790       static const unsigned GPR64ArgRegsWin64[] = {
1791         X86::RCX, X86::RDX, X86::R8,  X86::R9
1792       };
1793       static const unsigned GPR64ArgRegs64Bit[] = {
1794         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1795       };
1796       static const unsigned XMMArgRegs64Bit[] = {
1797         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1798         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1799       };
1800       const unsigned *GPR64ArgRegs;
1801       unsigned NumXMMRegs = 0;
1802
1803       if (IsWin64) {
1804         // The XMM registers which might contain var arg parameters are shadowed
1805         // in their paired GPR.  So we only need to save the GPR to their home
1806         // slots.
1807         TotalNumIntRegs = 4;
1808         GPR64ArgRegs = GPR64ArgRegsWin64;
1809       } else {
1810         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1811         GPR64ArgRegs = GPR64ArgRegs64Bit;
1812
1813         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1814       }
1815       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1816                                                        TotalNumIntRegs);
1817
1818       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1819       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1820              "SSE register cannot be used when SSE is disabled!");
1821       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1822              "SSE register cannot be used when SSE is disabled!");
1823       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1824         // Kernel mode asks for SSE to be disabled, so don't push them
1825         // on the stack.
1826         TotalNumXMMRegs = 0;
1827
1828       if (IsWin64) {
1829         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1830         // Get to the caller-allocated home save location.  Add 8 to account
1831         // for the return address.
1832         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1833         FuncInfo->setRegSaveFrameIndex(
1834           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1835         // Fixup to set vararg frame on shadow area (4 x i64).
1836         if (NumIntRegs < 4)
1837           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1838       } else {
1839         // For X86-64, if there are vararg parameters that are passed via
1840         // registers, then we must store them to their spots on the stack so they
1841         // may be loaded by deferencing the result of va_next.
1842         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1843         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1844         FuncInfo->setRegSaveFrameIndex(
1845           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1846                                false));
1847       }
1848
1849       // Store the integer parameter registers.
1850       SmallVector<SDValue, 8> MemOps;
1851       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1852                                         getPointerTy());
1853       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1854       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1855         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1856                                   DAG.getIntPtrConstant(Offset));
1857         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1858                                      X86::GR64RegisterClass);
1859         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1860         SDValue Store =
1861           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1862                        MachinePointerInfo::getFixedStack(
1863                          FuncInfo->getRegSaveFrameIndex(), Offset),
1864                        false, false, 0);
1865         MemOps.push_back(Store);
1866         Offset += 8;
1867       }
1868
1869       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1870         // Now store the XMM (fp + vector) parameter registers.
1871         SmallVector<SDValue, 11> SaveXMMOps;
1872         SaveXMMOps.push_back(Chain);
1873
1874         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1875         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1876         SaveXMMOps.push_back(ALVal);
1877
1878         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879                                FuncInfo->getRegSaveFrameIndex()));
1880         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1881                                FuncInfo->getVarArgsFPOffset()));
1882
1883         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1884           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1885                                        X86::VR128RegisterClass);
1886           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1887           SaveXMMOps.push_back(Val);
1888         }
1889         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1890                                      MVT::Other,
1891                                      &SaveXMMOps[0], SaveXMMOps.size()));
1892       }
1893
1894       if (!MemOps.empty())
1895         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1896                             &MemOps[0], MemOps.size());
1897     }
1898   }
1899
1900   // Some CCs need callee pop.
1901   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1902     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1903   } else {
1904     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1905     // If this is an sret function, the return should pop the hidden pointer.
1906     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1907       FuncInfo->setBytesToPopOnReturn(4);
1908   }
1909
1910   if (!Is64Bit) {
1911     // RegSaveFrameIndex is X86-64 only.
1912     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1913     if (CallConv == CallingConv::X86_FastCall ||
1914         CallConv == CallingConv::X86_ThisCall)
1915       // fastcc functions can't have varargs.
1916       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1917   }
1918
1919   return Chain;
1920 }
1921
1922 SDValue
1923 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1924                                     SDValue StackPtr, SDValue Arg,
1925                                     DebugLoc dl, SelectionDAG &DAG,
1926                                     const CCValAssign &VA,
1927                                     ISD::ArgFlagsTy Flags) const {
1928   unsigned LocMemOffset = VA.getLocMemOffset();
1929   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1930   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1931   if (Flags.isByVal())
1932     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1933
1934   return DAG.getStore(Chain, dl, Arg, PtrOff,
1935                       MachinePointerInfo::getStack(LocMemOffset),
1936                       false, false, 0);
1937 }
1938
1939 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1940 /// optimization is performed and it is required.
1941 SDValue
1942 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1943                                            SDValue &OutRetAddr, SDValue Chain,
1944                                            bool IsTailCall, bool Is64Bit,
1945                                            int FPDiff, DebugLoc dl) const {
1946   // Adjust the Return address stack slot.
1947   EVT VT = getPointerTy();
1948   OutRetAddr = getReturnAddressFrameIndex(DAG);
1949
1950   // Load the "old" Return address.
1951   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1952                            false, false, 0);
1953   return SDValue(OutRetAddr.getNode(), 1);
1954 }
1955
1956 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1957 /// optimization is performed and it is required (FPDiff!=0).
1958 static SDValue
1959 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1960                          SDValue Chain, SDValue RetAddrFrIdx,
1961                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1962   // Store the return address to the appropriate stack slot.
1963   if (!FPDiff) return Chain;
1964   // Calculate the new stack slot for the return address.
1965   int SlotSize = Is64Bit ? 8 : 4;
1966   int NewReturnAddrFI =
1967     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1968   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1969   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1970   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1971                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1972                        false, false, 0);
1973   return Chain;
1974 }
1975
1976 SDValue
1977 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1978                              CallingConv::ID CallConv, bool isVarArg,
1979                              bool &isTailCall,
1980                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                              const SmallVectorImpl<SDValue> &OutVals,
1982                              const SmallVectorImpl<ISD::InputArg> &Ins,
1983                              DebugLoc dl, SelectionDAG &DAG,
1984                              SmallVectorImpl<SDValue> &InVals) const {
1985   MachineFunction &MF = DAG.getMachineFunction();
1986   bool Is64Bit        = Subtarget->is64Bit();
1987   bool IsWin64        = Subtarget->isTargetWin64();
1988   bool IsStructRet    = CallIsStructReturn(Outs);
1989   bool IsSibcall      = false;
1990
1991   if (isTailCall) {
1992     // Check if it's really possible to do a tail call.
1993     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1994                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1995                                                    Outs, OutVals, Ins, DAG);
1996
1997     // Sibcalls are automatically detected tailcalls which do not require
1998     // ABI changes.
1999     if (!GuaranteedTailCallOpt && isTailCall)
2000       IsSibcall = true;
2001
2002     if (isTailCall)
2003       ++NumTailCalls;
2004   }
2005
2006   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2007          "Var args not supported with calling convention fastcc or ghc");
2008
2009   // Analyze operands of the call, assigning locations to each operand.
2010   SmallVector<CCValAssign, 16> ArgLocs;
2011   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2012                  ArgLocs, *DAG.getContext());
2013
2014   // Allocate shadow area for Win64
2015   if (IsWin64) {
2016     CCInfo.AllocateStack(32, 8);
2017   }
2018
2019   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2020
2021   // Get a count of how many bytes are to be pushed on the stack.
2022   unsigned NumBytes = CCInfo.getNextStackOffset();
2023   if (IsSibcall)
2024     // This is a sibcall. The memory operands are available in caller's
2025     // own caller's stack.
2026     NumBytes = 0;
2027   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2028     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2029
2030   int FPDiff = 0;
2031   if (isTailCall && !IsSibcall) {
2032     // Lower arguments at fp - stackoffset + fpdiff.
2033     unsigned NumBytesCallerPushed =
2034       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2035     FPDiff = NumBytesCallerPushed - NumBytes;
2036
2037     // Set the delta of movement of the returnaddr stackslot.
2038     // But only set if delta is greater than previous delta.
2039     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2040       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2041   }
2042
2043   if (!IsSibcall)
2044     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2045
2046   SDValue RetAddrFrIdx;
2047   // Load return address for tail calls.
2048   if (isTailCall && FPDiff)
2049     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2050                                     Is64Bit, FPDiff, dl);
2051
2052   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2053   SmallVector<SDValue, 8> MemOpChains;
2054   SDValue StackPtr;
2055
2056   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2057   // of tail call optimization arguments are handle later.
2058   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2059     CCValAssign &VA = ArgLocs[i];
2060     EVT RegVT = VA.getLocVT();
2061     SDValue Arg = OutVals[i];
2062     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2063     bool isByVal = Flags.isByVal();
2064
2065     // Promote the value if needed.
2066     switch (VA.getLocInfo()) {
2067     default: llvm_unreachable("Unknown loc info!");
2068     case CCValAssign::Full: break;
2069     case CCValAssign::SExt:
2070       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2071       break;
2072     case CCValAssign::ZExt:
2073       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2074       break;
2075     case CCValAssign::AExt:
2076       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2077         // Special case: passing MMX values in XMM registers.
2078         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2079         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2080         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2081       } else
2082         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2083       break;
2084     case CCValAssign::BCvt:
2085       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2086       break;
2087     case CCValAssign::Indirect: {
2088       // Store the argument.
2089       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2090       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2091       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2092                            MachinePointerInfo::getFixedStack(FI),
2093                            false, false, 0);
2094       Arg = SpillSlot;
2095       break;
2096     }
2097     }
2098
2099     if (VA.isRegLoc()) {
2100       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2101       if (isVarArg && IsWin64) {
2102         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2103         // shadow reg if callee is a varargs function.
2104         unsigned ShadowReg = 0;
2105         switch (VA.getLocReg()) {
2106         case X86::XMM0: ShadowReg = X86::RCX; break;
2107         case X86::XMM1: ShadowReg = X86::RDX; break;
2108         case X86::XMM2: ShadowReg = X86::R8; break;
2109         case X86::XMM3: ShadowReg = X86::R9; break;
2110         }
2111         if (ShadowReg)
2112           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2113       }
2114     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2115       assert(VA.isMemLoc());
2116       if (StackPtr.getNode() == 0)
2117         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2118       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2119                                              dl, DAG, VA, Flags));
2120     }
2121   }
2122
2123   if (!MemOpChains.empty())
2124     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2125                         &MemOpChains[0], MemOpChains.size());
2126
2127   // Build a sequence of copy-to-reg nodes chained together with token chain
2128   // and flag operands which copy the outgoing args into registers.
2129   SDValue InFlag;
2130   // Tail call byval lowering might overwrite argument registers so in case of
2131   // tail call optimization the copies to registers are lowered later.
2132   if (!isTailCall)
2133     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2134       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2135                                RegsToPass[i].second, InFlag);
2136       InFlag = Chain.getValue(1);
2137     }
2138
2139   if (Subtarget->isPICStyleGOT()) {
2140     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2141     // GOT pointer.
2142     if (!isTailCall) {
2143       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2144                                DAG.getNode(X86ISD::GlobalBaseReg,
2145                                            DebugLoc(), getPointerTy()),
2146                                InFlag);
2147       InFlag = Chain.getValue(1);
2148     } else {
2149       // If we are tail calling and generating PIC/GOT style code load the
2150       // address of the callee into ECX. The value in ecx is used as target of
2151       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2152       // for tail calls on PIC/GOT architectures. Normally we would just put the
2153       // address of GOT into ebx and then call target@PLT. But for tail calls
2154       // ebx would be restored (since ebx is callee saved) before jumping to the
2155       // target@PLT.
2156
2157       // Note: The actual moving to ECX is done further down.
2158       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2159       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2160           !G->getGlobal()->hasProtectedVisibility())
2161         Callee = LowerGlobalAddress(Callee, DAG);
2162       else if (isa<ExternalSymbolSDNode>(Callee))
2163         Callee = LowerExternalSymbol(Callee, DAG);
2164     }
2165   }
2166
2167   if (Is64Bit && isVarArg && !IsWin64) {
2168     // From AMD64 ABI document:
2169     // For calls that may call functions that use varargs or stdargs
2170     // (prototype-less calls or calls to functions containing ellipsis (...) in
2171     // the declaration) %al is used as hidden argument to specify the number
2172     // of SSE registers used. The contents of %al do not need to match exactly
2173     // the number of registers, but must be an ubound on the number of SSE
2174     // registers used and is in the range 0 - 8 inclusive.
2175
2176     // Count the number of XMM registers allocated.
2177     static const unsigned XMMArgRegs[] = {
2178       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2179       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2180     };
2181     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2182     assert((Subtarget->hasXMM() || !NumXMMRegs)
2183            && "SSE registers cannot be used when SSE is disabled");
2184
2185     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2186                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2187     InFlag = Chain.getValue(1);
2188   }
2189
2190
2191   // For tail calls lower the arguments to the 'real' stack slot.
2192   if (isTailCall) {
2193     // Force all the incoming stack arguments to be loaded from the stack
2194     // before any new outgoing arguments are stored to the stack, because the
2195     // outgoing stack slots may alias the incoming argument stack slots, and
2196     // the alias isn't otherwise explicit. This is slightly more conservative
2197     // than necessary, because it means that each store effectively depends
2198     // on every argument instead of just those arguments it would clobber.
2199     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2200
2201     SmallVector<SDValue, 8> MemOpChains2;
2202     SDValue FIN;
2203     int FI = 0;
2204     // Do not flag preceding copytoreg stuff together with the following stuff.
2205     InFlag = SDValue();
2206     if (GuaranteedTailCallOpt) {
2207       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2208         CCValAssign &VA = ArgLocs[i];
2209         if (VA.isRegLoc())
2210           continue;
2211         assert(VA.isMemLoc());
2212         SDValue Arg = OutVals[i];
2213         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2214         // Create frame index.
2215         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2216         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2217         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2218         FIN = DAG.getFrameIndex(FI, getPointerTy());
2219
2220         if (Flags.isByVal()) {
2221           // Copy relative to framepointer.
2222           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2223           if (StackPtr.getNode() == 0)
2224             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2225                                           getPointerTy());
2226           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2227
2228           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2229                                                            ArgChain,
2230                                                            Flags, DAG, dl));
2231         } else {
2232           // Store relative to framepointer.
2233           MemOpChains2.push_back(
2234             DAG.getStore(ArgChain, dl, Arg, FIN,
2235                          MachinePointerInfo::getFixedStack(FI),
2236                          false, false, 0));
2237         }
2238       }
2239     }
2240
2241     if (!MemOpChains2.empty())
2242       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2243                           &MemOpChains2[0], MemOpChains2.size());
2244
2245     // Copy arguments to their registers.
2246     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2247       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2248                                RegsToPass[i].second, InFlag);
2249       InFlag = Chain.getValue(1);
2250     }
2251     InFlag =SDValue();
2252
2253     // Store the return address to the appropriate stack slot.
2254     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2255                                      FPDiff, dl);
2256   }
2257
2258   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2259     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2260     // In the 64-bit large code model, we have to make all calls
2261     // through a register, since the call instruction's 32-bit
2262     // pc-relative offset may not be large enough to hold the whole
2263     // address.
2264   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2265     // If the callee is a GlobalAddress node (quite common, every direct call
2266     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2267     // it.
2268
2269     // We should use extra load for direct calls to dllimported functions in
2270     // non-JIT mode.
2271     const GlobalValue *GV = G->getGlobal();
2272     if (!GV->hasDLLImportLinkage()) {
2273       unsigned char OpFlags = 0;
2274       bool ExtraLoad = false;
2275       unsigned WrapperKind = ISD::DELETED_NODE;
2276
2277       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2278       // external symbols most go through the PLT in PIC mode.  If the symbol
2279       // has hidden or protected visibility, or if it is static or local, then
2280       // we don't need to use the PLT - we can directly call it.
2281       if (Subtarget->isTargetELF() &&
2282           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2283           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2284         OpFlags = X86II::MO_PLT;
2285       } else if (Subtarget->isPICStyleStubAny() &&
2286                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2287                  (!Subtarget->getTargetTriple().isMacOSX() ||
2288                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2289         // PC-relative references to external symbols should go through $stub,
2290         // unless we're building with the leopard linker or later, which
2291         // automatically synthesizes these stubs.
2292         OpFlags = X86II::MO_DARWIN_STUB;
2293       } else if (Subtarget->isPICStyleRIPRel() &&
2294                  isa<Function>(GV) &&
2295                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2296         // If the function is marked as non-lazy, generate an indirect call
2297         // which loads from the GOT directly. This avoids runtime overhead
2298         // at the cost of eager binding (and one extra byte of encoding).
2299         OpFlags = X86II::MO_GOTPCREL;
2300         WrapperKind = X86ISD::WrapperRIP;
2301         ExtraLoad = true;
2302       }
2303
2304       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2305                                           G->getOffset(), OpFlags);
2306
2307       // Add a wrapper if needed.
2308       if (WrapperKind != ISD::DELETED_NODE)
2309         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2310       // Add extra indirection if needed.
2311       if (ExtraLoad)
2312         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2313                              MachinePointerInfo::getGOT(),
2314                              false, false, 0);
2315     }
2316   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2317     unsigned char OpFlags = 0;
2318
2319     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2320     // external symbols should go through the PLT.
2321     if (Subtarget->isTargetELF() &&
2322         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2323       OpFlags = X86II::MO_PLT;
2324     } else if (Subtarget->isPICStyleStubAny() &&
2325                (!Subtarget->getTargetTriple().isMacOSX() ||
2326                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2327       // PC-relative references to external symbols should go through $stub,
2328       // unless we're building with the leopard linker or later, which
2329       // automatically synthesizes these stubs.
2330       OpFlags = X86II::MO_DARWIN_STUB;
2331     }
2332
2333     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2334                                          OpFlags);
2335   }
2336
2337   // Returns a chain & a flag for retval copy to use.
2338   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2339   SmallVector<SDValue, 8> Ops;
2340
2341   if (!IsSibcall && isTailCall) {
2342     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2343                            DAG.getIntPtrConstant(0, true), InFlag);
2344     InFlag = Chain.getValue(1);
2345   }
2346
2347   Ops.push_back(Chain);
2348   Ops.push_back(Callee);
2349
2350   if (isTailCall)
2351     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2352
2353   // Add argument registers to the end of the list so that they are known live
2354   // into the call.
2355   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2356     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2357                                   RegsToPass[i].second.getValueType()));
2358
2359   // Add an implicit use GOT pointer in EBX.
2360   if (!isTailCall && Subtarget->isPICStyleGOT())
2361     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2362
2363   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2364   if (Is64Bit && isVarArg && !IsWin64)
2365     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2366
2367   if (InFlag.getNode())
2368     Ops.push_back(InFlag);
2369
2370   if (isTailCall) {
2371     // We used to do:
2372     //// If this is the first return lowered for this function, add the regs
2373     //// to the liveout set for the function.
2374     // This isn't right, although it's probably harmless on x86; liveouts
2375     // should be computed from returns not tail calls.  Consider a void
2376     // function making a tail call to a function returning int.
2377     return DAG.getNode(X86ISD::TC_RETURN, dl,
2378                        NodeTys, &Ops[0], Ops.size());
2379   }
2380
2381   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2382   InFlag = Chain.getValue(1);
2383
2384   // Create the CALLSEQ_END node.
2385   unsigned NumBytesForCalleeToPush;
2386   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2387     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2388   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2389     // If this is a call to a struct-return function, the callee
2390     // pops the hidden struct pointer, so we have to push it back.
2391     // This is common for Darwin/X86, Linux & Mingw32 targets.
2392     NumBytesForCalleeToPush = 4;
2393   else
2394     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2395
2396   // Returns a flag for retval copy to use.
2397   if (!IsSibcall) {
2398     Chain = DAG.getCALLSEQ_END(Chain,
2399                                DAG.getIntPtrConstant(NumBytes, true),
2400                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2401                                                      true),
2402                                InFlag);
2403     InFlag = Chain.getValue(1);
2404   }
2405
2406   // Handle result values, copying them out of physregs into vregs that we
2407   // return.
2408   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2409                          Ins, dl, DAG, InVals);
2410 }
2411
2412
2413 //===----------------------------------------------------------------------===//
2414 //                Fast Calling Convention (tail call) implementation
2415 //===----------------------------------------------------------------------===//
2416
2417 //  Like std call, callee cleans arguments, convention except that ECX is
2418 //  reserved for storing the tail called function address. Only 2 registers are
2419 //  free for argument passing (inreg). Tail call optimization is performed
2420 //  provided:
2421 //                * tailcallopt is enabled
2422 //                * caller/callee are fastcc
2423 //  On X86_64 architecture with GOT-style position independent code only local
2424 //  (within module) calls are supported at the moment.
2425 //  To keep the stack aligned according to platform abi the function
2426 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2427 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2428 //  If a tail called function callee has more arguments than the caller the
2429 //  caller needs to make sure that there is room to move the RETADDR to. This is
2430 //  achieved by reserving an area the size of the argument delta right after the
2431 //  original REtADDR, but before the saved framepointer or the spilled registers
2432 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2433 //  stack layout:
2434 //    arg1
2435 //    arg2
2436 //    RETADDR
2437 //    [ new RETADDR
2438 //      move area ]
2439 //    (possible EBP)
2440 //    ESI
2441 //    EDI
2442 //    local1 ..
2443
2444 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2445 /// for a 16 byte align requirement.
2446 unsigned
2447 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2448                                                SelectionDAG& DAG) const {
2449   MachineFunction &MF = DAG.getMachineFunction();
2450   const TargetMachine &TM = MF.getTarget();
2451   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2452   unsigned StackAlignment = TFI.getStackAlignment();
2453   uint64_t AlignMask = StackAlignment - 1;
2454   int64_t Offset = StackSize;
2455   uint64_t SlotSize = TD->getPointerSize();
2456   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2457     // Number smaller than 12 so just add the difference.
2458     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2459   } else {
2460     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2461     Offset = ((~AlignMask) & Offset) + StackAlignment +
2462       (StackAlignment-SlotSize);
2463   }
2464   return Offset;
2465 }
2466
2467 /// MatchingStackOffset - Return true if the given stack call argument is
2468 /// already available in the same position (relatively) of the caller's
2469 /// incoming argument stack.
2470 static
2471 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2472                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2473                          const X86InstrInfo *TII) {
2474   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2475   int FI = INT_MAX;
2476   if (Arg.getOpcode() == ISD::CopyFromReg) {
2477     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2478     if (!TargetRegisterInfo::isVirtualRegister(VR))
2479       return false;
2480     MachineInstr *Def = MRI->getVRegDef(VR);
2481     if (!Def)
2482       return false;
2483     if (!Flags.isByVal()) {
2484       if (!TII->isLoadFromStackSlot(Def, FI))
2485         return false;
2486     } else {
2487       unsigned Opcode = Def->getOpcode();
2488       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2489           Def->getOperand(1).isFI()) {
2490         FI = Def->getOperand(1).getIndex();
2491         Bytes = Flags.getByValSize();
2492       } else
2493         return false;
2494     }
2495   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2496     if (Flags.isByVal())
2497       // ByVal argument is passed in as a pointer but it's now being
2498       // dereferenced. e.g.
2499       // define @foo(%struct.X* %A) {
2500       //   tail call @bar(%struct.X* byval %A)
2501       // }
2502       return false;
2503     SDValue Ptr = Ld->getBasePtr();
2504     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2505     if (!FINode)
2506       return false;
2507     FI = FINode->getIndex();
2508   } else
2509     return false;
2510
2511   assert(FI != INT_MAX);
2512   if (!MFI->isFixedObjectIndex(FI))
2513     return false;
2514   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2515 }
2516
2517 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2518 /// for tail call optimization. Targets which want to do tail call
2519 /// optimization should implement this function.
2520 bool
2521 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2522                                                      CallingConv::ID CalleeCC,
2523                                                      bool isVarArg,
2524                                                      bool isCalleeStructRet,
2525                                                      bool isCallerStructRet,
2526                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2527                                     const SmallVectorImpl<SDValue> &OutVals,
2528                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2529                                                      SelectionDAG& DAG) const {
2530   if (!IsTailCallConvention(CalleeCC) &&
2531       CalleeCC != CallingConv::C)
2532     return false;
2533
2534   // If -tailcallopt is specified, make fastcc functions tail-callable.
2535   const MachineFunction &MF = DAG.getMachineFunction();
2536   const Function *CallerF = DAG.getMachineFunction().getFunction();
2537   CallingConv::ID CallerCC = CallerF->getCallingConv();
2538   bool CCMatch = CallerCC == CalleeCC;
2539
2540   if (GuaranteedTailCallOpt) {
2541     if (IsTailCallConvention(CalleeCC) && CCMatch)
2542       return true;
2543     return false;
2544   }
2545
2546   // Look for obvious safe cases to perform tail call optimization that do not
2547   // require ABI changes. This is what gcc calls sibcall.
2548
2549   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2550   // emit a special epilogue.
2551   if (RegInfo->needsStackRealignment(MF))
2552     return false;
2553
2554   // Also avoid sibcall optimization if either caller or callee uses struct
2555   // return semantics.
2556   if (isCalleeStructRet || isCallerStructRet)
2557     return false;
2558
2559   // Do not sibcall optimize vararg calls unless all arguments are passed via
2560   // registers.
2561   if (isVarArg && !Outs.empty()) {
2562
2563     // Optimizing for varargs on Win64 is unlikely to be safe without
2564     // additional testing.
2565     if (Subtarget->isTargetWin64())
2566       return false;
2567
2568     SmallVector<CCValAssign, 16> ArgLocs;
2569     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2570                    getTargetMachine(), ArgLocs, *DAG.getContext());
2571
2572     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2574       if (!ArgLocs[i].isRegLoc())
2575         return false;
2576   }
2577
2578   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2579   // Therefore if it's not used by the call it is not safe to optimize this into
2580   // a sibcall.
2581   bool Unused = false;
2582   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2583     if (!Ins[i].Used) {
2584       Unused = true;
2585       break;
2586     }
2587   }
2588   if (Unused) {
2589     SmallVector<CCValAssign, 16> RVLocs;
2590     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2591                    getTargetMachine(), RVLocs, *DAG.getContext());
2592     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2593     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2594       CCValAssign &VA = RVLocs[i];
2595       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2596         return false;
2597     }
2598   }
2599
2600   // If the calling conventions do not match, then we'd better make sure the
2601   // results are returned in the same way as what the caller expects.
2602   if (!CCMatch) {
2603     SmallVector<CCValAssign, 16> RVLocs1;
2604     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2605                     getTargetMachine(), RVLocs1, *DAG.getContext());
2606     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2607
2608     SmallVector<CCValAssign, 16> RVLocs2;
2609     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2610                     getTargetMachine(), RVLocs2, *DAG.getContext());
2611     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2612
2613     if (RVLocs1.size() != RVLocs2.size())
2614       return false;
2615     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2616       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2617         return false;
2618       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2619         return false;
2620       if (RVLocs1[i].isRegLoc()) {
2621         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2622           return false;
2623       } else {
2624         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2625           return false;
2626       }
2627     }
2628   }
2629
2630   // If the callee takes no arguments then go on to check the results of the
2631   // call.
2632   if (!Outs.empty()) {
2633     // Check if stack adjustment is needed. For now, do not do this if any
2634     // argument is passed on the stack.
2635     SmallVector<CCValAssign, 16> ArgLocs;
2636     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2637                    getTargetMachine(), ArgLocs, *DAG.getContext());
2638
2639     // Allocate shadow area for Win64
2640     if (Subtarget->isTargetWin64()) {
2641       CCInfo.AllocateStack(32, 8);
2642     }
2643
2644     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2645     if (CCInfo.getNextStackOffset()) {
2646       MachineFunction &MF = DAG.getMachineFunction();
2647       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2648         return false;
2649
2650       // Check if the arguments are already laid out in the right way as
2651       // the caller's fixed stack objects.
2652       MachineFrameInfo *MFI = MF.getFrameInfo();
2653       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2654       const X86InstrInfo *TII =
2655         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2656       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2657         CCValAssign &VA = ArgLocs[i];
2658         SDValue Arg = OutVals[i];
2659         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2660         if (VA.getLocInfo() == CCValAssign::Indirect)
2661           return false;
2662         if (!VA.isRegLoc()) {
2663           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2664                                    MFI, MRI, TII))
2665             return false;
2666         }
2667       }
2668     }
2669
2670     // If the tailcall address may be in a register, then make sure it's
2671     // possible to register allocate for it. In 32-bit, the call address can
2672     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2673     // callee-saved registers are restored. These happen to be the same
2674     // registers used to pass 'inreg' arguments so watch out for those.
2675     if (!Subtarget->is64Bit() &&
2676         !isa<GlobalAddressSDNode>(Callee) &&
2677         !isa<ExternalSymbolSDNode>(Callee)) {
2678       unsigned NumInRegs = 0;
2679       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2680         CCValAssign &VA = ArgLocs[i];
2681         if (!VA.isRegLoc())
2682           continue;
2683         unsigned Reg = VA.getLocReg();
2684         switch (Reg) {
2685         default: break;
2686         case X86::EAX: case X86::EDX: case X86::ECX:
2687           if (++NumInRegs == 3)
2688             return false;
2689           break;
2690         }
2691       }
2692     }
2693   }
2694
2695   // An stdcall caller is expected to clean up its arguments; the callee
2696   // isn't going to do that.
2697   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2698     return false;
2699
2700   return true;
2701 }
2702
2703 FastISel *
2704 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2705   return X86::createFastISel(funcInfo);
2706 }
2707
2708
2709 //===----------------------------------------------------------------------===//
2710 //                           Other Lowering Hooks
2711 //===----------------------------------------------------------------------===//
2712
2713 static bool MayFoldLoad(SDValue Op) {
2714   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2715 }
2716
2717 static bool MayFoldIntoStore(SDValue Op) {
2718   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2719 }
2720
2721 static bool isTargetShuffle(unsigned Opcode) {
2722   switch(Opcode) {
2723   default: return false;
2724   case X86ISD::PSHUFD:
2725   case X86ISD::PSHUFHW:
2726   case X86ISD::PSHUFLW:
2727   case X86ISD::SHUFPD:
2728   case X86ISD::PALIGN:
2729   case X86ISD::SHUFPS:
2730   case X86ISD::MOVLHPS:
2731   case X86ISD::MOVLHPD:
2732   case X86ISD::MOVHLPS:
2733   case X86ISD::MOVLPS:
2734   case X86ISD::MOVLPD:
2735   case X86ISD::MOVSHDUP:
2736   case X86ISD::MOVSLDUP:
2737   case X86ISD::MOVDDUP:
2738   case X86ISD::MOVSS:
2739   case X86ISD::MOVSD:
2740   case X86ISD::UNPCKLPS:
2741   case X86ISD::UNPCKLPD:
2742   case X86ISD::VUNPCKLPS:
2743   case X86ISD::VUNPCKLPD:
2744   case X86ISD::VUNPCKLPSY:
2745   case X86ISD::VUNPCKLPDY:
2746   case X86ISD::PUNPCKLWD:
2747   case X86ISD::PUNPCKLBW:
2748   case X86ISD::PUNPCKLDQ:
2749   case X86ISD::PUNPCKLQDQ:
2750   case X86ISD::UNPCKHPS:
2751   case X86ISD::UNPCKHPD:
2752   case X86ISD::PUNPCKHWD:
2753   case X86ISD::PUNPCKHBW:
2754   case X86ISD::PUNPCKHDQ:
2755   case X86ISD::PUNPCKHQDQ:
2756     return true;
2757   }
2758   return false;
2759 }
2760
2761 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2762                                                SDValue V1, SelectionDAG &DAG) {
2763   switch(Opc) {
2764   default: llvm_unreachable("Unknown x86 shuffle node");
2765   case X86ISD::MOVSHDUP:
2766   case X86ISD::MOVSLDUP:
2767   case X86ISD::MOVDDUP:
2768     return DAG.getNode(Opc, dl, VT, V1);
2769   }
2770
2771   return SDValue();
2772 }
2773
2774 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2775                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2776   switch(Opc) {
2777   default: llvm_unreachable("Unknown x86 shuffle node");
2778   case X86ISD::PSHUFD:
2779   case X86ISD::PSHUFHW:
2780   case X86ISD::PSHUFLW:
2781     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2782   }
2783
2784   return SDValue();
2785 }
2786
2787 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2788                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2789   switch(Opc) {
2790   default: llvm_unreachable("Unknown x86 shuffle node");
2791   case X86ISD::PALIGN:
2792   case X86ISD::SHUFPD:
2793   case X86ISD::SHUFPS:
2794     return DAG.getNode(Opc, dl, VT, V1, V2,
2795                        DAG.getConstant(TargetMask, MVT::i8));
2796   }
2797   return SDValue();
2798 }
2799
2800 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2801                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2802   switch(Opc) {
2803   default: llvm_unreachable("Unknown x86 shuffle node");
2804   case X86ISD::MOVLHPS:
2805   case X86ISD::MOVLHPD:
2806   case X86ISD::MOVHLPS:
2807   case X86ISD::MOVLPS:
2808   case X86ISD::MOVLPD:
2809   case X86ISD::MOVSS:
2810   case X86ISD::MOVSD:
2811   case X86ISD::UNPCKLPS:
2812   case X86ISD::UNPCKLPD:
2813   case X86ISD::VUNPCKLPS:
2814   case X86ISD::VUNPCKLPD:
2815   case X86ISD::VUNPCKLPSY:
2816   case X86ISD::VUNPCKLPDY:
2817   case X86ISD::PUNPCKLWD:
2818   case X86ISD::PUNPCKLBW:
2819   case X86ISD::PUNPCKLDQ:
2820   case X86ISD::PUNPCKLQDQ:
2821   case X86ISD::UNPCKHPS:
2822   case X86ISD::UNPCKHPD:
2823   case X86ISD::PUNPCKHWD:
2824   case X86ISD::PUNPCKHBW:
2825   case X86ISD::PUNPCKHDQ:
2826   case X86ISD::PUNPCKHQDQ:
2827     return DAG.getNode(Opc, dl, VT, V1, V2);
2828   }
2829   return SDValue();
2830 }
2831
2832 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2833   MachineFunction &MF = DAG.getMachineFunction();
2834   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2835   int ReturnAddrIndex = FuncInfo->getRAIndex();
2836
2837   if (ReturnAddrIndex == 0) {
2838     // Set up a frame object for the return address.
2839     uint64_t SlotSize = TD->getPointerSize();
2840     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2841                                                            false);
2842     FuncInfo->setRAIndex(ReturnAddrIndex);
2843   }
2844
2845   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2846 }
2847
2848
2849 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2850                                        bool hasSymbolicDisplacement) {
2851   // Offset should fit into 32 bit immediate field.
2852   if (!isInt<32>(Offset))
2853     return false;
2854
2855   // If we don't have a symbolic displacement - we don't have any extra
2856   // restrictions.
2857   if (!hasSymbolicDisplacement)
2858     return true;
2859
2860   // FIXME: Some tweaks might be needed for medium code model.
2861   if (M != CodeModel::Small && M != CodeModel::Kernel)
2862     return false;
2863
2864   // For small code model we assume that latest object is 16MB before end of 31
2865   // bits boundary. We may also accept pretty large negative constants knowing
2866   // that all objects are in the positive half of address space.
2867   if (M == CodeModel::Small && Offset < 16*1024*1024)
2868     return true;
2869
2870   // For kernel code model we know that all object resist in the negative half
2871   // of 32bits address space. We may not accept negative offsets, since they may
2872   // be just off and we may accept pretty large positive ones.
2873   if (M == CodeModel::Kernel && Offset > 0)
2874     return true;
2875
2876   return false;
2877 }
2878
2879 /// isCalleePop - Determines whether the callee is required to pop its
2880 /// own arguments. Callee pop is necessary to support tail calls.
2881 bool X86::isCalleePop(CallingConv::ID CallingConv,
2882                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2883   if (IsVarArg)
2884     return false;
2885
2886   switch (CallingConv) {
2887   default:
2888     return false;
2889   case CallingConv::X86_StdCall:
2890     return !is64Bit;
2891   case CallingConv::X86_FastCall:
2892     return !is64Bit;
2893   case CallingConv::X86_ThisCall:
2894     return !is64Bit;
2895   case CallingConv::Fast:
2896     return TailCallOpt;
2897   case CallingConv::GHC:
2898     return TailCallOpt;
2899   }
2900 }
2901
2902 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2903 /// specific condition code, returning the condition code and the LHS/RHS of the
2904 /// comparison to make.
2905 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2906                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2907   if (!isFP) {
2908     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2909       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2910         // X > -1   -> X == 0, jump !sign.
2911         RHS = DAG.getConstant(0, RHS.getValueType());
2912         return X86::COND_NS;
2913       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2914         // X < 0   -> X == 0, jump on sign.
2915         return X86::COND_S;
2916       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2917         // X < 1   -> X <= 0
2918         RHS = DAG.getConstant(0, RHS.getValueType());
2919         return X86::COND_LE;
2920       }
2921     }
2922
2923     switch (SetCCOpcode) {
2924     default: llvm_unreachable("Invalid integer condition!");
2925     case ISD::SETEQ:  return X86::COND_E;
2926     case ISD::SETGT:  return X86::COND_G;
2927     case ISD::SETGE:  return X86::COND_GE;
2928     case ISD::SETLT:  return X86::COND_L;
2929     case ISD::SETLE:  return X86::COND_LE;
2930     case ISD::SETNE:  return X86::COND_NE;
2931     case ISD::SETULT: return X86::COND_B;
2932     case ISD::SETUGT: return X86::COND_A;
2933     case ISD::SETULE: return X86::COND_BE;
2934     case ISD::SETUGE: return X86::COND_AE;
2935     }
2936   }
2937
2938   // First determine if it is required or is profitable to flip the operands.
2939
2940   // If LHS is a foldable load, but RHS is not, flip the condition.
2941   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2942       !ISD::isNON_EXTLoad(RHS.getNode())) {
2943     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2944     std::swap(LHS, RHS);
2945   }
2946
2947   switch (SetCCOpcode) {
2948   default: break;
2949   case ISD::SETOLT:
2950   case ISD::SETOLE:
2951   case ISD::SETUGT:
2952   case ISD::SETUGE:
2953     std::swap(LHS, RHS);
2954     break;
2955   }
2956
2957   // On a floating point condition, the flags are set as follows:
2958   // ZF  PF  CF   op
2959   //  0 | 0 | 0 | X > Y
2960   //  0 | 0 | 1 | X < Y
2961   //  1 | 0 | 0 | X == Y
2962   //  1 | 1 | 1 | unordered
2963   switch (SetCCOpcode) {
2964   default: llvm_unreachable("Condcode should be pre-legalized away");
2965   case ISD::SETUEQ:
2966   case ISD::SETEQ:   return X86::COND_E;
2967   case ISD::SETOLT:              // flipped
2968   case ISD::SETOGT:
2969   case ISD::SETGT:   return X86::COND_A;
2970   case ISD::SETOLE:              // flipped
2971   case ISD::SETOGE:
2972   case ISD::SETGE:   return X86::COND_AE;
2973   case ISD::SETUGT:              // flipped
2974   case ISD::SETULT:
2975   case ISD::SETLT:   return X86::COND_B;
2976   case ISD::SETUGE:              // flipped
2977   case ISD::SETULE:
2978   case ISD::SETLE:   return X86::COND_BE;
2979   case ISD::SETONE:
2980   case ISD::SETNE:   return X86::COND_NE;
2981   case ISD::SETUO:   return X86::COND_P;
2982   case ISD::SETO:    return X86::COND_NP;
2983   case ISD::SETOEQ:
2984   case ISD::SETUNE:  return X86::COND_INVALID;
2985   }
2986 }
2987
2988 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2989 /// code. Current x86 isa includes the following FP cmov instructions:
2990 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2991 static bool hasFPCMov(unsigned X86CC) {
2992   switch (X86CC) {
2993   default:
2994     return false;
2995   case X86::COND_B:
2996   case X86::COND_BE:
2997   case X86::COND_E:
2998   case X86::COND_P:
2999   case X86::COND_A:
3000   case X86::COND_AE:
3001   case X86::COND_NE:
3002   case X86::COND_NP:
3003     return true;
3004   }
3005 }
3006
3007 /// isFPImmLegal - Returns true if the target can instruction select the
3008 /// specified FP immediate natively. If false, the legalizer will
3009 /// materialize the FP immediate as a load from a constant pool.
3010 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3011   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3012     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3013       return true;
3014   }
3015   return false;
3016 }
3017
3018 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3019 /// the specified range (L, H].
3020 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3021   return (Val < 0) || (Val >= Low && Val < Hi);
3022 }
3023
3024 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3025 /// specified value.
3026 static bool isUndefOrEqual(int Val, int CmpVal) {
3027   if (Val < 0 || Val == CmpVal)
3028     return true;
3029   return false;
3030 }
3031
3032 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3033 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3034 /// the second operand.
3035 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3036   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3037     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3038   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3039     return (Mask[0] < 2 && Mask[1] < 2);
3040   return false;
3041 }
3042
3043 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3044   SmallVector<int, 8> M;
3045   N->getMask(M);
3046   return ::isPSHUFDMask(M, N->getValueType(0));
3047 }
3048
3049 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3050 /// is suitable for input to PSHUFHW.
3051 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3052   if (VT != MVT::v8i16)
3053     return false;
3054
3055   // Lower quadword copied in order or undef.
3056   for (int i = 0; i != 4; ++i)
3057     if (Mask[i] >= 0 && Mask[i] != i)
3058       return false;
3059
3060   // Upper quadword shuffled.
3061   for (int i = 4; i != 8; ++i)
3062     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3063       return false;
3064
3065   return true;
3066 }
3067
3068 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3069   SmallVector<int, 8> M;
3070   N->getMask(M);
3071   return ::isPSHUFHWMask(M, N->getValueType(0));
3072 }
3073
3074 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3075 /// is suitable for input to PSHUFLW.
3076 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3077   if (VT != MVT::v8i16)
3078     return false;
3079
3080   // Upper quadword copied in order.
3081   for (int i = 4; i != 8; ++i)
3082     if (Mask[i] >= 0 && Mask[i] != i)
3083       return false;
3084
3085   // Lower quadword shuffled.
3086   for (int i = 0; i != 4; ++i)
3087     if (Mask[i] >= 4)
3088       return false;
3089
3090   return true;
3091 }
3092
3093 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3094   SmallVector<int, 8> M;
3095   N->getMask(M);
3096   return ::isPSHUFLWMask(M, N->getValueType(0));
3097 }
3098
3099 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3100 /// is suitable for input to PALIGNR.
3101 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3102                           bool hasSSSE3) {
3103   int i, e = VT.getVectorNumElements();
3104
3105   // Do not handle v2i64 / v2f64 shuffles with palignr.
3106   if (e < 4 || !hasSSSE3)
3107     return false;
3108
3109   for (i = 0; i != e; ++i)
3110     if (Mask[i] >= 0)
3111       break;
3112
3113   // All undef, not a palignr.
3114   if (i == e)
3115     return false;
3116
3117   // Determine if it's ok to perform a palignr with only the LHS, since we
3118   // don't have access to the actual shuffle elements to see if RHS is undef.
3119   bool Unary = Mask[i] < (int)e;
3120   bool NeedsUnary = false;
3121
3122   int s = Mask[i] - i;
3123
3124   // Check the rest of the elements to see if they are consecutive.
3125   for (++i; i != e; ++i) {
3126     int m = Mask[i];
3127     if (m < 0)
3128       continue;
3129
3130     Unary = Unary && (m < (int)e);
3131     NeedsUnary = NeedsUnary || (m < s);
3132
3133     if (NeedsUnary && !Unary)
3134       return false;
3135     if (Unary && m != ((s+i) & (e-1)))
3136       return false;
3137     if (!Unary && m != (s+i))
3138       return false;
3139   }
3140   return true;
3141 }
3142
3143 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3144   SmallVector<int, 8> M;
3145   N->getMask(M);
3146   return ::isPALIGNRMask(M, N->getValueType(0), true);
3147 }
3148
3149 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3150 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3151 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3152   int NumElems = VT.getVectorNumElements();
3153   if (NumElems != 2 && NumElems != 4)
3154     return false;
3155
3156   int Half = NumElems / 2;
3157   for (int i = 0; i < Half; ++i)
3158     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3159       return false;
3160   for (int i = Half; i < NumElems; ++i)
3161     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3162       return false;
3163
3164   return true;
3165 }
3166
3167 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3168   SmallVector<int, 8> M;
3169   N->getMask(M);
3170   return ::isSHUFPMask(M, N->getValueType(0));
3171 }
3172
3173 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3174 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3175 /// half elements to come from vector 1 (which would equal the dest.) and
3176 /// the upper half to come from vector 2.
3177 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3178   int NumElems = VT.getVectorNumElements();
3179
3180   if (NumElems != 2 && NumElems != 4)
3181     return false;
3182
3183   int Half = NumElems / 2;
3184   for (int i = 0; i < Half; ++i)
3185     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3186       return false;
3187   for (int i = Half; i < NumElems; ++i)
3188     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3189       return false;
3190   return true;
3191 }
3192
3193 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3194   SmallVector<int, 8> M;
3195   N->getMask(M);
3196   return isCommutedSHUFPMask(M, N->getValueType(0));
3197 }
3198
3199 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3200 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3201 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3202   if (N->getValueType(0).getVectorNumElements() != 4)
3203     return false;
3204
3205   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3206   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3207          isUndefOrEqual(N->getMaskElt(1), 7) &&
3208          isUndefOrEqual(N->getMaskElt(2), 2) &&
3209          isUndefOrEqual(N->getMaskElt(3), 3);
3210 }
3211
3212 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3213 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3214 /// <2, 3, 2, 3>
3215 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3216   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3217
3218   if (NumElems != 4)
3219     return false;
3220
3221   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3222   isUndefOrEqual(N->getMaskElt(1), 3) &&
3223   isUndefOrEqual(N->getMaskElt(2), 2) &&
3224   isUndefOrEqual(N->getMaskElt(3), 3);
3225 }
3226
3227 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3228 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3229 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3230   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3231
3232   if (NumElems != 2 && NumElems != 4)
3233     return false;
3234
3235   for (unsigned i = 0; i < NumElems/2; ++i)
3236     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3237       return false;
3238
3239   for (unsigned i = NumElems/2; i < NumElems; ++i)
3240     if (!isUndefOrEqual(N->getMaskElt(i), i))
3241       return false;
3242
3243   return true;
3244 }
3245
3246 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3247 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3248 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3249   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3250
3251   if ((NumElems != 2 && NumElems != 4)
3252       || N->getValueType(0).getSizeInBits() > 128)
3253     return false;
3254
3255   for (unsigned i = 0; i < NumElems/2; ++i)
3256     if (!isUndefOrEqual(N->getMaskElt(i), i))
3257       return false;
3258
3259   for (unsigned i = 0; i < NumElems/2; ++i)
3260     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3261       return false;
3262
3263   return true;
3264 }
3265
3266 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3267 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3268 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3269                          bool V2IsSplat = false) {
3270   int NumElts = VT.getVectorNumElements();
3271   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3272     return false;
3273
3274   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3275   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3276   // sections.
3277   unsigned NumSections = VT.getSizeInBits() / 128;
3278   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3279   unsigned NumSectionElts = NumElts / NumSections;
3280
3281   unsigned Start = 0;
3282   unsigned End = NumSectionElts;
3283   for (unsigned s = 0; s < NumSections; ++s) {
3284     for (unsigned i = Start, j = s * NumSectionElts;
3285          i != End;
3286          i += 2, ++j) {
3287       int BitI  = Mask[i];
3288       int BitI1 = Mask[i+1];
3289       if (!isUndefOrEqual(BitI, j))
3290         return false;
3291       if (V2IsSplat) {
3292         if (!isUndefOrEqual(BitI1, NumElts))
3293           return false;
3294       } else {
3295         if (!isUndefOrEqual(BitI1, j + NumElts))
3296           return false;
3297       }
3298     }
3299     // Process the next 128 bits.
3300     Start += NumSectionElts;
3301     End += NumSectionElts;
3302   }
3303
3304   return true;
3305 }
3306
3307 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3308   SmallVector<int, 8> M;
3309   N->getMask(M);
3310   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3311 }
3312
3313 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3314 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3315 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3316                          bool V2IsSplat = false) {
3317   int NumElts = VT.getVectorNumElements();
3318   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3319     return false;
3320
3321   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3322     int BitI  = Mask[i];
3323     int BitI1 = Mask[i+1];
3324     if (!isUndefOrEqual(BitI, j + NumElts/2))
3325       return false;
3326     if (V2IsSplat) {
3327       if (isUndefOrEqual(BitI1, NumElts))
3328         return false;
3329     } else {
3330       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3331         return false;
3332     }
3333   }
3334   return true;
3335 }
3336
3337 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3338   SmallVector<int, 8> M;
3339   N->getMask(M);
3340   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3341 }
3342
3343 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3344 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3345 /// <0, 0, 1, 1>
3346 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3347   int NumElems = VT.getVectorNumElements();
3348   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3349     return false;
3350
3351   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3352   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3353   // sections.
3354   unsigned NumSections = VT.getSizeInBits() / 128;
3355   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3356   unsigned NumSectionElts = NumElems / NumSections;
3357
3358   for (unsigned s = 0; s < NumSections; ++s) {
3359     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3360          i != NumSectionElts * (s + 1);
3361          i += 2, ++j) {
3362       int BitI  = Mask[i];
3363       int BitI1 = Mask[i+1];
3364
3365       if (!isUndefOrEqual(BitI, j))
3366         return false;
3367       if (!isUndefOrEqual(BitI1, j))
3368         return false;
3369     }
3370   }
3371
3372   return true;
3373 }
3374
3375 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3376   SmallVector<int, 8> M;
3377   N->getMask(M);
3378   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3379 }
3380
3381 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3382 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3383 /// <2, 2, 3, 3>
3384 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3385   int NumElems = VT.getVectorNumElements();
3386   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3387     return false;
3388
3389   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3390     int BitI  = Mask[i];
3391     int BitI1 = Mask[i+1];
3392     if (!isUndefOrEqual(BitI, j))
3393       return false;
3394     if (!isUndefOrEqual(BitI1, j))
3395       return false;
3396   }
3397   return true;
3398 }
3399
3400 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3401   SmallVector<int, 8> M;
3402   N->getMask(M);
3403   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3404 }
3405
3406 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3407 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3408 /// MOVSD, and MOVD, i.e. setting the lowest element.
3409 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3410   if (VT.getVectorElementType().getSizeInBits() < 32)
3411     return false;
3412
3413   int NumElts = VT.getVectorNumElements();
3414
3415   if (!isUndefOrEqual(Mask[0], NumElts))
3416     return false;
3417
3418   for (int i = 1; i < NumElts; ++i)
3419     if (!isUndefOrEqual(Mask[i], i))
3420       return false;
3421
3422   return true;
3423 }
3424
3425 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3426   SmallVector<int, 8> M;
3427   N->getMask(M);
3428   return ::isMOVLMask(M, N->getValueType(0));
3429 }
3430
3431 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3432 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3433 /// element of vector 2 and the other elements to come from vector 1 in order.
3434 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3435                                bool V2IsSplat = false, bool V2IsUndef = false) {
3436   int NumOps = VT.getVectorNumElements();
3437   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3438     return false;
3439
3440   if (!isUndefOrEqual(Mask[0], 0))
3441     return false;
3442
3443   for (int i = 1; i < NumOps; ++i)
3444     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3445           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3446           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3447       return false;
3448
3449   return true;
3450 }
3451
3452 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3453                            bool V2IsUndef = false) {
3454   SmallVector<int, 8> M;
3455   N->getMask(M);
3456   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3457 }
3458
3459 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3460 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3461 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3462   if (N->getValueType(0).getVectorNumElements() != 4)
3463     return false;
3464
3465   // Expect 1, 1, 3, 3
3466   for (unsigned i = 0; i < 2; ++i) {
3467     int Elt = N->getMaskElt(i);
3468     if (Elt >= 0 && Elt != 1)
3469       return false;
3470   }
3471
3472   bool HasHi = false;
3473   for (unsigned i = 2; i < 4; ++i) {
3474     int Elt = N->getMaskElt(i);
3475     if (Elt >= 0 && Elt != 3)
3476       return false;
3477     if (Elt == 3)
3478       HasHi = true;
3479   }
3480   // Don't use movshdup if it can be done with a shufps.
3481   // FIXME: verify that matching u, u, 3, 3 is what we want.
3482   return HasHi;
3483 }
3484
3485 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3486 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3487 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3488   if (N->getValueType(0).getVectorNumElements() != 4)
3489     return false;
3490
3491   // Expect 0, 0, 2, 2
3492   for (unsigned i = 0; i < 2; ++i)
3493     if (N->getMaskElt(i) > 0)
3494       return false;
3495
3496   bool HasHi = false;
3497   for (unsigned i = 2; i < 4; ++i) {
3498     int Elt = N->getMaskElt(i);
3499     if (Elt >= 0 && Elt != 2)
3500       return false;
3501     if (Elt == 2)
3502       HasHi = true;
3503   }
3504   // Don't use movsldup if it can be done with a shufps.
3505   return HasHi;
3506 }
3507
3508 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3509 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3510 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3511   int e = N->getValueType(0).getVectorNumElements() / 2;
3512
3513   for (int i = 0; i < e; ++i)
3514     if (!isUndefOrEqual(N->getMaskElt(i), i))
3515       return false;
3516   for (int i = 0; i < e; ++i)
3517     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3518       return false;
3519   return true;
3520 }
3521
3522 /// isVEXTRACTF128Index - Return true if the specified
3523 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3524 /// suitable for input to VEXTRACTF128.
3525 bool X86::isVEXTRACTF128Index(SDNode *N) {
3526   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3527     return false;
3528
3529   // The index should be aligned on a 128-bit boundary.
3530   uint64_t Index =
3531     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3532
3533   unsigned VL = N->getValueType(0).getVectorNumElements();
3534   unsigned VBits = N->getValueType(0).getSizeInBits();
3535   unsigned ElSize = VBits / VL;
3536   bool Result = (Index * ElSize) % 128 == 0;
3537
3538   return Result;
3539 }
3540
3541 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3542 /// operand specifies a subvector insert that is suitable for input to
3543 /// VINSERTF128.
3544 bool X86::isVINSERTF128Index(SDNode *N) {
3545   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3546     return false;
3547
3548   // The index should be aligned on a 128-bit boundary.
3549   uint64_t Index =
3550     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3551
3552   unsigned VL = N->getValueType(0).getVectorNumElements();
3553   unsigned VBits = N->getValueType(0).getSizeInBits();
3554   unsigned ElSize = VBits / VL;
3555   bool Result = (Index * ElSize) % 128 == 0;
3556
3557   return Result;
3558 }
3559
3560 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3561 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3562 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3563   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3564   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3565
3566   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3567   unsigned Mask = 0;
3568   for (int i = 0; i < NumOperands; ++i) {
3569     int Val = SVOp->getMaskElt(NumOperands-i-1);
3570     if (Val < 0) Val = 0;
3571     if (Val >= NumOperands) Val -= NumOperands;
3572     Mask |= Val;
3573     if (i != NumOperands - 1)
3574       Mask <<= Shift;
3575   }
3576   return Mask;
3577 }
3578
3579 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3580 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3581 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3582   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3583   unsigned Mask = 0;
3584   // 8 nodes, but we only care about the last 4.
3585   for (unsigned i = 7; i >= 4; --i) {
3586     int Val = SVOp->getMaskElt(i);
3587     if (Val >= 0)
3588       Mask |= (Val - 4);
3589     if (i != 4)
3590       Mask <<= 2;
3591   }
3592   return Mask;
3593 }
3594
3595 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3596 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3597 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3598   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3599   unsigned Mask = 0;
3600   // 8 nodes, but we only care about the first 4.
3601   for (int i = 3; i >= 0; --i) {
3602     int Val = SVOp->getMaskElt(i);
3603     if (Val >= 0)
3604       Mask |= Val;
3605     if (i != 0)
3606       Mask <<= 2;
3607   }
3608   return Mask;
3609 }
3610
3611 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3612 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3613 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3614   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3615   EVT VVT = N->getValueType(0);
3616   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3617   int Val = 0;
3618
3619   unsigned i, e;
3620   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3621     Val = SVOp->getMaskElt(i);
3622     if (Val >= 0)
3623       break;
3624   }
3625   return (Val - i) * EltSize;
3626 }
3627
3628 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3629 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3630 /// instructions.
3631 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3632   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3633     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3634
3635   uint64_t Index =
3636     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3637
3638   EVT VecVT = N->getOperand(0).getValueType();
3639   EVT ElVT = VecVT.getVectorElementType();
3640
3641   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3642
3643   return Index / NumElemsPerChunk;
3644 }
3645
3646 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3647 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3648 /// instructions.
3649 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3650   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3651     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3652
3653   uint64_t Index =
3654     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3655
3656   EVT VecVT = N->getValueType(0);
3657   EVT ElVT = VecVT.getVectorElementType();
3658
3659   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3660
3661   return Index / NumElemsPerChunk;
3662 }
3663
3664 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3665 /// constant +0.0.
3666 bool X86::isZeroNode(SDValue Elt) {
3667   return ((isa<ConstantSDNode>(Elt) &&
3668            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3669           (isa<ConstantFPSDNode>(Elt) &&
3670            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3671 }
3672
3673 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3674 /// their permute mask.
3675 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3676                                     SelectionDAG &DAG) {
3677   EVT VT = SVOp->getValueType(0);
3678   unsigned NumElems = VT.getVectorNumElements();
3679   SmallVector<int, 8> MaskVec;
3680
3681   for (unsigned i = 0; i != NumElems; ++i) {
3682     int idx = SVOp->getMaskElt(i);
3683     if (idx < 0)
3684       MaskVec.push_back(idx);
3685     else if (idx < (int)NumElems)
3686       MaskVec.push_back(idx + NumElems);
3687     else
3688       MaskVec.push_back(idx - NumElems);
3689   }
3690   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3691                               SVOp->getOperand(0), &MaskVec[0]);
3692 }
3693
3694 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3695 /// the two vector operands have swapped position.
3696 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3697   unsigned NumElems = VT.getVectorNumElements();
3698   for (unsigned i = 0; i != NumElems; ++i) {
3699     int idx = Mask[i];
3700     if (idx < 0)
3701       continue;
3702     else if (idx < (int)NumElems)
3703       Mask[i] = idx + NumElems;
3704     else
3705       Mask[i] = idx - NumElems;
3706   }
3707 }
3708
3709 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3710 /// match movhlps. The lower half elements should come from upper half of
3711 /// V1 (and in order), and the upper half elements should come from the upper
3712 /// half of V2 (and in order).
3713 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3714   if (Op->getValueType(0).getVectorNumElements() != 4)
3715     return false;
3716   for (unsigned i = 0, e = 2; i != e; ++i)
3717     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3718       return false;
3719   for (unsigned i = 2; i != 4; ++i)
3720     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3721       return false;
3722   return true;
3723 }
3724
3725 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3726 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3727 /// required.
3728 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3729   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3730     return false;
3731   N = N->getOperand(0).getNode();
3732   if (!ISD::isNON_EXTLoad(N))
3733     return false;
3734   if (LD)
3735     *LD = cast<LoadSDNode>(N);
3736   return true;
3737 }
3738
3739 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3740 /// match movlp{s|d}. The lower half elements should come from lower half of
3741 /// V1 (and in order), and the upper half elements should come from the upper
3742 /// half of V2 (and in order). And since V1 will become the source of the
3743 /// MOVLP, it must be either a vector load or a scalar load to vector.
3744 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3745                                ShuffleVectorSDNode *Op) {
3746   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3747     return false;
3748   // Is V2 is a vector load, don't do this transformation. We will try to use
3749   // load folding shufps op.
3750   if (ISD::isNON_EXTLoad(V2))
3751     return false;
3752
3753   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3754
3755   if (NumElems != 2 && NumElems != 4)
3756     return false;
3757   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3758     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3759       return false;
3760   for (unsigned i = NumElems/2; i != NumElems; ++i)
3761     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3762       return false;
3763   return true;
3764 }
3765
3766 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3767 /// all the same.
3768 static bool isSplatVector(SDNode *N) {
3769   if (N->getOpcode() != ISD::BUILD_VECTOR)
3770     return false;
3771
3772   SDValue SplatValue = N->getOperand(0);
3773   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3774     if (N->getOperand(i) != SplatValue)
3775       return false;
3776   return true;
3777 }
3778
3779 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3780 /// to an zero vector.
3781 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3782 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3783   SDValue V1 = N->getOperand(0);
3784   SDValue V2 = N->getOperand(1);
3785   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3786   for (unsigned i = 0; i != NumElems; ++i) {
3787     int Idx = N->getMaskElt(i);
3788     if (Idx >= (int)NumElems) {
3789       unsigned Opc = V2.getOpcode();
3790       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3791         continue;
3792       if (Opc != ISD::BUILD_VECTOR ||
3793           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3794         return false;
3795     } else if (Idx >= 0) {
3796       unsigned Opc = V1.getOpcode();
3797       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3798         continue;
3799       if (Opc != ISD::BUILD_VECTOR ||
3800           !X86::isZeroNode(V1.getOperand(Idx)))
3801         return false;
3802     }
3803   }
3804   return true;
3805 }
3806
3807 /// getZeroVector - Returns a vector of specified type with all zero elements.
3808 ///
3809 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3810                              DebugLoc dl) {
3811   assert(VT.isVector() && "Expected a vector type");
3812
3813   // Always build SSE zero vectors as <4 x i32> bitcasted
3814   // to their dest type. This ensures they get CSE'd.
3815   SDValue Vec;
3816   if (VT.getSizeInBits() == 128) {  // SSE
3817     if (HasSSE2) {  // SSE2
3818       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3819       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3820     } else { // SSE1
3821       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3822       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3823     }
3824   } else if (VT.getSizeInBits() == 256) { // AVX
3825     // 256-bit logic and arithmetic instructions in AVX are
3826     // all floating-point, no support for integer ops. Default
3827     // to emitting fp zeroed vectors then.
3828     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3829     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3830     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3831   }
3832   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3833 }
3834
3835 /// getOnesVector - Returns a vector of specified type with all bits set.
3836 ///
3837 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3838   assert(VT.isVector() && "Expected a vector type");
3839
3840   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3841   // type.  This ensures they get CSE'd.
3842   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3843   SDValue Vec;
3844   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3845   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3846 }
3847
3848
3849 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3850 /// that point to V2 points to its first element.
3851 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3852   EVT VT = SVOp->getValueType(0);
3853   unsigned NumElems = VT.getVectorNumElements();
3854
3855   bool Changed = false;
3856   SmallVector<int, 8> MaskVec;
3857   SVOp->getMask(MaskVec);
3858
3859   for (unsigned i = 0; i != NumElems; ++i) {
3860     if (MaskVec[i] > (int)NumElems) {
3861       MaskVec[i] = NumElems;
3862       Changed = true;
3863     }
3864   }
3865   if (Changed)
3866     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3867                                 SVOp->getOperand(1), &MaskVec[0]);
3868   return SDValue(SVOp, 0);
3869 }
3870
3871 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3872 /// operation of specified width.
3873 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3874                        SDValue V2) {
3875   unsigned NumElems = VT.getVectorNumElements();
3876   SmallVector<int, 8> Mask;
3877   Mask.push_back(NumElems);
3878   for (unsigned i = 1; i != NumElems; ++i)
3879     Mask.push_back(i);
3880   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3881 }
3882
3883 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3884 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3885                           SDValue V2) {
3886   unsigned NumElems = VT.getVectorNumElements();
3887   SmallVector<int, 8> Mask;
3888   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3889     Mask.push_back(i);
3890     Mask.push_back(i + NumElems);
3891   }
3892   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3893 }
3894
3895 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3896 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3897                           SDValue V2) {
3898   unsigned NumElems = VT.getVectorNumElements();
3899   unsigned Half = NumElems/2;
3900   SmallVector<int, 8> Mask;
3901   for (unsigned i = 0; i != Half; ++i) {
3902     Mask.push_back(i + Half);
3903     Mask.push_back(i + NumElems + Half);
3904   }
3905   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3906 }
3907
3908 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3909 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3910   EVT PVT = MVT::v4f32;
3911   EVT VT = SV->getValueType(0);
3912   DebugLoc dl = SV->getDebugLoc();
3913   SDValue V1 = SV->getOperand(0);
3914   int NumElems = VT.getVectorNumElements();
3915   int EltNo = SV->getSplatIndex();
3916
3917   // unpack elements to the correct location
3918   while (NumElems > 4) {
3919     if (EltNo < NumElems/2) {
3920       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3921     } else {
3922       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3923       EltNo -= NumElems/2;
3924     }
3925     NumElems >>= 1;
3926   }
3927
3928   // Perform the splat.
3929   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3930   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3931   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3932   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3933 }
3934
3935 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3936 /// vector of zero or undef vector.  This produces a shuffle where the low
3937 /// element of V2 is swizzled into the zero/undef vector, landing at element
3938 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3939 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3940                                              bool isZero, bool HasSSE2,
3941                                              SelectionDAG &DAG) {
3942   EVT VT = V2.getValueType();
3943   SDValue V1 = isZero
3944     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3945   unsigned NumElems = VT.getVectorNumElements();
3946   SmallVector<int, 16> MaskVec;
3947   for (unsigned i = 0; i != NumElems; ++i)
3948     // If this is the insertion idx, put the low elt of V2 here.
3949     MaskVec.push_back(i == Idx ? NumElems : i);
3950   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3951 }
3952
3953 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3954 /// element of the result of the vector shuffle.
3955 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3956                                    unsigned Depth) {
3957   if (Depth == 6)
3958     return SDValue();  // Limit search depth.
3959
3960   SDValue V = SDValue(N, 0);
3961   EVT VT = V.getValueType();
3962   unsigned Opcode = V.getOpcode();
3963
3964   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3965   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3966     Index = SV->getMaskElt(Index);
3967
3968     if (Index < 0)
3969       return DAG.getUNDEF(VT.getVectorElementType());
3970
3971     int NumElems = VT.getVectorNumElements();
3972     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3973     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3974   }
3975
3976   // Recurse into target specific vector shuffles to find scalars.
3977   if (isTargetShuffle(Opcode)) {
3978     int NumElems = VT.getVectorNumElements();
3979     SmallVector<unsigned, 16> ShuffleMask;
3980     SDValue ImmN;
3981
3982     switch(Opcode) {
3983     case X86ISD::SHUFPS:
3984     case X86ISD::SHUFPD:
3985       ImmN = N->getOperand(N->getNumOperands()-1);
3986       DecodeSHUFPSMask(NumElems,
3987                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3988                        ShuffleMask);
3989       break;
3990     case X86ISD::PUNPCKHBW:
3991     case X86ISD::PUNPCKHWD:
3992     case X86ISD::PUNPCKHDQ:
3993     case X86ISD::PUNPCKHQDQ:
3994       DecodePUNPCKHMask(NumElems, ShuffleMask);
3995       break;
3996     case X86ISD::UNPCKHPS:
3997     case X86ISD::UNPCKHPD:
3998       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3999       break;
4000     case X86ISD::PUNPCKLBW:
4001     case X86ISD::PUNPCKLWD:
4002     case X86ISD::PUNPCKLDQ:
4003     case X86ISD::PUNPCKLQDQ:
4004       DecodePUNPCKLMask(VT, ShuffleMask);
4005       break;
4006     case X86ISD::UNPCKLPS:
4007     case X86ISD::UNPCKLPD:
4008     case X86ISD::VUNPCKLPS:
4009     case X86ISD::VUNPCKLPD:
4010     case X86ISD::VUNPCKLPSY:
4011     case X86ISD::VUNPCKLPDY:
4012       DecodeUNPCKLPMask(VT, ShuffleMask);
4013       break;
4014     case X86ISD::MOVHLPS:
4015       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4016       break;
4017     case X86ISD::MOVLHPS:
4018       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4019       break;
4020     case X86ISD::PSHUFD:
4021       ImmN = N->getOperand(N->getNumOperands()-1);
4022       DecodePSHUFMask(NumElems,
4023                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4024                       ShuffleMask);
4025       break;
4026     case X86ISD::PSHUFHW:
4027       ImmN = N->getOperand(N->getNumOperands()-1);
4028       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4029                         ShuffleMask);
4030       break;
4031     case X86ISD::PSHUFLW:
4032       ImmN = N->getOperand(N->getNumOperands()-1);
4033       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4034                         ShuffleMask);
4035       break;
4036     case X86ISD::MOVSS:
4037     case X86ISD::MOVSD: {
4038       // The index 0 always comes from the first element of the second source,
4039       // this is why MOVSS and MOVSD are used in the first place. The other
4040       // elements come from the other positions of the first source vector.
4041       unsigned OpNum = (Index == 0) ? 1 : 0;
4042       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4043                                  Depth+1);
4044     }
4045     default:
4046       assert("not implemented for target shuffle node");
4047       return SDValue();
4048     }
4049
4050     Index = ShuffleMask[Index];
4051     if (Index < 0)
4052       return DAG.getUNDEF(VT.getVectorElementType());
4053
4054     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4055     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4056                                Depth+1);
4057   }
4058
4059   // Actual nodes that may contain scalar elements
4060   if (Opcode == ISD::BITCAST) {
4061     V = V.getOperand(0);
4062     EVT SrcVT = V.getValueType();
4063     unsigned NumElems = VT.getVectorNumElements();
4064
4065     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4066       return SDValue();
4067   }
4068
4069   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4070     return (Index == 0) ? V.getOperand(0)
4071                           : DAG.getUNDEF(VT.getVectorElementType());
4072
4073   if (V.getOpcode() == ISD::BUILD_VECTOR)
4074     return V.getOperand(Index);
4075
4076   return SDValue();
4077 }
4078
4079 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4080 /// shuffle operation which come from a consecutively from a zero. The
4081 /// search can start in two different directions, from left or right.
4082 static
4083 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4084                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4085   int i = 0;
4086
4087   while (i < NumElems) {
4088     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4089     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4090     if (!(Elt.getNode() &&
4091          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4092       break;
4093     ++i;
4094   }
4095
4096   return i;
4097 }
4098
4099 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4100 /// MaskE correspond consecutively to elements from one of the vector operands,
4101 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4102 static
4103 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4104                               int OpIdx, int NumElems, unsigned &OpNum) {
4105   bool SeenV1 = false;
4106   bool SeenV2 = false;
4107
4108   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4109     int Idx = SVOp->getMaskElt(i);
4110     // Ignore undef indicies
4111     if (Idx < 0)
4112       continue;
4113
4114     if (Idx < NumElems)
4115       SeenV1 = true;
4116     else
4117       SeenV2 = true;
4118
4119     // Only accept consecutive elements from the same vector
4120     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4121       return false;
4122   }
4123
4124   OpNum = SeenV1 ? 0 : 1;
4125   return true;
4126 }
4127
4128 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4129 /// logical left shift of a vector.
4130 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4131                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4132   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4133   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4134               false /* check zeros from right */, DAG);
4135   unsigned OpSrc;
4136
4137   if (!NumZeros)
4138     return false;
4139
4140   // Considering the elements in the mask that are not consecutive zeros,
4141   // check if they consecutively come from only one of the source vectors.
4142   //
4143   //               V1 = {X, A, B, C}     0
4144   //                         \  \  \    /
4145   //   vector_shuffle V1, V2 <1, 2, 3, X>
4146   //
4147   if (!isShuffleMaskConsecutive(SVOp,
4148             0,                   // Mask Start Index
4149             NumElems-NumZeros-1, // Mask End Index
4150             NumZeros,            // Where to start looking in the src vector
4151             NumElems,            // Number of elements in vector
4152             OpSrc))              // Which source operand ?
4153     return false;
4154
4155   isLeft = false;
4156   ShAmt = NumZeros;
4157   ShVal = SVOp->getOperand(OpSrc);
4158   return true;
4159 }
4160
4161 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4162 /// logical left shift of a vector.
4163 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4164                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4165   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4166   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4167               true /* check zeros from left */, DAG);
4168   unsigned OpSrc;
4169
4170   if (!NumZeros)
4171     return false;
4172
4173   // Considering the elements in the mask that are not consecutive zeros,
4174   // check if they consecutively come from only one of the source vectors.
4175   //
4176   //                           0    { A, B, X, X } = V2
4177   //                          / \    /  /
4178   //   vector_shuffle V1, V2 <X, X, 4, 5>
4179   //
4180   if (!isShuffleMaskConsecutive(SVOp,
4181             NumZeros,     // Mask Start Index
4182             NumElems-1,   // Mask End Index
4183             0,            // Where to start looking in the src vector
4184             NumElems,     // Number of elements in vector
4185             OpSrc))       // Which source operand ?
4186     return false;
4187
4188   isLeft = true;
4189   ShAmt = NumZeros;
4190   ShVal = SVOp->getOperand(OpSrc);
4191   return true;
4192 }
4193
4194 /// isVectorShift - Returns true if the shuffle can be implemented as a
4195 /// logical left or right shift of a vector.
4196 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4197                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4198   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4199       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4200     return true;
4201
4202   return false;
4203 }
4204
4205 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4206 ///
4207 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4208                                        unsigned NumNonZero, unsigned NumZero,
4209                                        SelectionDAG &DAG,
4210                                        const TargetLowering &TLI) {
4211   if (NumNonZero > 8)
4212     return SDValue();
4213
4214   DebugLoc dl = Op.getDebugLoc();
4215   SDValue V(0, 0);
4216   bool First = true;
4217   for (unsigned i = 0; i < 16; ++i) {
4218     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4219     if (ThisIsNonZero && First) {
4220       if (NumZero)
4221         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4222       else
4223         V = DAG.getUNDEF(MVT::v8i16);
4224       First = false;
4225     }
4226
4227     if ((i & 1) != 0) {
4228       SDValue ThisElt(0, 0), LastElt(0, 0);
4229       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4230       if (LastIsNonZero) {
4231         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4232                               MVT::i16, Op.getOperand(i-1));
4233       }
4234       if (ThisIsNonZero) {
4235         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4236         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4237                               ThisElt, DAG.getConstant(8, MVT::i8));
4238         if (LastIsNonZero)
4239           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4240       } else
4241         ThisElt = LastElt;
4242
4243       if (ThisElt.getNode())
4244         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4245                         DAG.getIntPtrConstant(i/2));
4246     }
4247   }
4248
4249   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4250 }
4251
4252 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4253 ///
4254 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4255                                      unsigned NumNonZero, unsigned NumZero,
4256                                      SelectionDAG &DAG,
4257                                      const TargetLowering &TLI) {
4258   if (NumNonZero > 4)
4259     return SDValue();
4260
4261   DebugLoc dl = Op.getDebugLoc();
4262   SDValue V(0, 0);
4263   bool First = true;
4264   for (unsigned i = 0; i < 8; ++i) {
4265     bool isNonZero = (NonZeros & (1 << i)) != 0;
4266     if (isNonZero) {
4267       if (First) {
4268         if (NumZero)
4269           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4270         else
4271           V = DAG.getUNDEF(MVT::v8i16);
4272         First = false;
4273       }
4274       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4275                       MVT::v8i16, V, Op.getOperand(i),
4276                       DAG.getIntPtrConstant(i));
4277     }
4278   }
4279
4280   return V;
4281 }
4282
4283 /// getVShift - Return a vector logical shift node.
4284 ///
4285 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4286                          unsigned NumBits, SelectionDAG &DAG,
4287                          const TargetLowering &TLI, DebugLoc dl) {
4288   EVT ShVT = MVT::v2i64;
4289   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4290   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4291   return DAG.getNode(ISD::BITCAST, dl, VT,
4292                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4293                              DAG.getConstant(NumBits,
4294                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4295 }
4296
4297 SDValue
4298 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4299                                           SelectionDAG &DAG) const {
4300
4301   // Check if the scalar load can be widened into a vector load. And if
4302   // the address is "base + cst" see if the cst can be "absorbed" into
4303   // the shuffle mask.
4304   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4305     SDValue Ptr = LD->getBasePtr();
4306     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4307       return SDValue();
4308     EVT PVT = LD->getValueType(0);
4309     if (PVT != MVT::i32 && PVT != MVT::f32)
4310       return SDValue();
4311
4312     int FI = -1;
4313     int64_t Offset = 0;
4314     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4315       FI = FINode->getIndex();
4316       Offset = 0;
4317     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4318                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4319       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4320       Offset = Ptr.getConstantOperandVal(1);
4321       Ptr = Ptr.getOperand(0);
4322     } else {
4323       return SDValue();
4324     }
4325
4326     SDValue Chain = LD->getChain();
4327     // Make sure the stack object alignment is at least 16.
4328     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4329     if (DAG.InferPtrAlignment(Ptr) < 16) {
4330       if (MFI->isFixedObjectIndex(FI)) {
4331         // Can't change the alignment. FIXME: It's possible to compute
4332         // the exact stack offset and reference FI + adjust offset instead.
4333         // If someone *really* cares about this. That's the way to implement it.
4334         return SDValue();
4335       } else {
4336         MFI->setObjectAlignment(FI, 16);
4337       }
4338     }
4339
4340     // (Offset % 16) must be multiple of 4. Then address is then
4341     // Ptr + (Offset & ~15).
4342     if (Offset < 0)
4343       return SDValue();
4344     if ((Offset % 16) & 3)
4345       return SDValue();
4346     int64_t StartOffset = Offset & ~15;
4347     if (StartOffset)
4348       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4349                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4350
4351     int EltNo = (Offset - StartOffset) >> 2;
4352     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4353     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4354     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4355                              LD->getPointerInfo().getWithOffset(StartOffset),
4356                              false, false, 0);
4357     // Canonicalize it to a v4i32 shuffle.
4358     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4359     return DAG.getNode(ISD::BITCAST, dl, VT,
4360                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4361                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4362   }
4363
4364   return SDValue();
4365 }
4366
4367 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4368 /// vector of type 'VT', see if the elements can be replaced by a single large
4369 /// load which has the same value as a build_vector whose operands are 'elts'.
4370 ///
4371 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4372 ///
4373 /// FIXME: we'd also like to handle the case where the last elements are zero
4374 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4375 /// There's even a handy isZeroNode for that purpose.
4376 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4377                                         DebugLoc &DL, SelectionDAG &DAG) {
4378   EVT EltVT = VT.getVectorElementType();
4379   unsigned NumElems = Elts.size();
4380
4381   LoadSDNode *LDBase = NULL;
4382   unsigned LastLoadedElt = -1U;
4383
4384   // For each element in the initializer, see if we've found a load or an undef.
4385   // If we don't find an initial load element, or later load elements are
4386   // non-consecutive, bail out.
4387   for (unsigned i = 0; i < NumElems; ++i) {
4388     SDValue Elt = Elts[i];
4389
4390     if (!Elt.getNode() ||
4391         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4392       return SDValue();
4393     if (!LDBase) {
4394       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4395         return SDValue();
4396       LDBase = cast<LoadSDNode>(Elt.getNode());
4397       LastLoadedElt = i;
4398       continue;
4399     }
4400     if (Elt.getOpcode() == ISD::UNDEF)
4401       continue;
4402
4403     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4404     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4405       return SDValue();
4406     LastLoadedElt = i;
4407   }
4408
4409   // If we have found an entire vector of loads and undefs, then return a large
4410   // load of the entire vector width starting at the base pointer.  If we found
4411   // consecutive loads for the low half, generate a vzext_load node.
4412   if (LastLoadedElt == NumElems - 1) {
4413     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4414       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4415                          LDBase->getPointerInfo(),
4416                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4417     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4418                        LDBase->getPointerInfo(),
4419                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4420                        LDBase->getAlignment());
4421   } else if (NumElems == 4 && LastLoadedElt == 1) {
4422     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4423     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4424     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4425                                               Ops, 2, MVT::i32,
4426                                               LDBase->getMemOperand());
4427     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4428   }
4429   return SDValue();
4430 }
4431
4432 SDValue
4433 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4434   DebugLoc dl = Op.getDebugLoc();
4435
4436   EVT VT = Op.getValueType();
4437   EVT ExtVT = VT.getVectorElementType();
4438
4439   unsigned NumElems = Op.getNumOperands();
4440
4441   // For AVX-length vectors, build the individual 128-bit pieces and
4442   // use shuffles to put them in place.
4443   if (VT.getSizeInBits() > 256 &&
4444       Subtarget->hasAVX() &&
4445       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4446     SmallVector<SDValue, 8> V;
4447     V.resize(NumElems);
4448     for (unsigned i = 0; i < NumElems; ++i) {
4449       V[i] = Op.getOperand(i);
4450     }
4451
4452     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4453
4454     // Build the lower subvector.
4455     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4456     // Build the upper subvector.
4457     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4458                                 NumElems/2);
4459
4460     return ConcatVectors(Lower, Upper, DAG);
4461   }
4462
4463   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4464   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4465   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4466   // is present, so AllOnes is ignored.
4467   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4468       (Op.getValueType().getSizeInBits() != 256 &&
4469        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4470     // Canonicalize this to <4 x i32> (SSE) to
4471     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4472     // eliminated on x86-32 hosts.
4473     if (Op.getValueType() == MVT::v4i32)
4474       return Op;
4475
4476     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4477       return getOnesVector(Op.getValueType(), DAG, dl);
4478     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4479   }
4480
4481   unsigned EVTBits = ExtVT.getSizeInBits();
4482
4483   unsigned NumZero  = 0;
4484   unsigned NumNonZero = 0;
4485   unsigned NonZeros = 0;
4486   bool IsAllConstants = true;
4487   SmallSet<SDValue, 8> Values;
4488   for (unsigned i = 0; i < NumElems; ++i) {
4489     SDValue Elt = Op.getOperand(i);
4490     if (Elt.getOpcode() == ISD::UNDEF)
4491       continue;
4492     Values.insert(Elt);
4493     if (Elt.getOpcode() != ISD::Constant &&
4494         Elt.getOpcode() != ISD::ConstantFP)
4495       IsAllConstants = false;
4496     if (X86::isZeroNode(Elt))
4497       NumZero++;
4498     else {
4499       NonZeros |= (1 << i);
4500       NumNonZero++;
4501     }
4502   }
4503
4504   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4505   if (NumNonZero == 0)
4506     return DAG.getUNDEF(VT);
4507
4508   // Special case for single non-zero, non-undef, element.
4509   if (NumNonZero == 1) {
4510     unsigned Idx = CountTrailingZeros_32(NonZeros);
4511     SDValue Item = Op.getOperand(Idx);
4512
4513     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4514     // the value are obviously zero, truncate the value to i32 and do the
4515     // insertion that way.  Only do this if the value is non-constant or if the
4516     // value is a constant being inserted into element 0.  It is cheaper to do
4517     // a constant pool load than it is to do a movd + shuffle.
4518     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4519         (!IsAllConstants || Idx == 0)) {
4520       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4521         // Handle SSE only.
4522         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4523         EVT VecVT = MVT::v4i32;
4524         unsigned VecElts = 4;
4525
4526         // Truncate the value (which may itself be a constant) to i32, and
4527         // convert it to a vector with movd (S2V+shuffle to zero extend).
4528         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4529         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4530         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4531                                            Subtarget->hasSSE2(), DAG);
4532
4533         // Now we have our 32-bit value zero extended in the low element of
4534         // a vector.  If Idx != 0, swizzle it into place.
4535         if (Idx != 0) {
4536           SmallVector<int, 4> Mask;
4537           Mask.push_back(Idx);
4538           for (unsigned i = 1; i != VecElts; ++i)
4539             Mask.push_back(i);
4540           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4541                                       DAG.getUNDEF(Item.getValueType()),
4542                                       &Mask[0]);
4543         }
4544         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4545       }
4546     }
4547
4548     // If we have a constant or non-constant insertion into the low element of
4549     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4550     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4551     // depending on what the source datatype is.
4552     if (Idx == 0) {
4553       if (NumZero == 0) {
4554         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4555       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4556           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4557         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4558         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4559         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4560                                            DAG);
4561       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4562         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4563         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4564         EVT MiddleVT = MVT::v4i32;
4565         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4566         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4567                                            Subtarget->hasSSE2(), DAG);
4568         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4569       }
4570     }
4571
4572     // Is it a vector logical left shift?
4573     if (NumElems == 2 && Idx == 1 &&
4574         X86::isZeroNode(Op.getOperand(0)) &&
4575         !X86::isZeroNode(Op.getOperand(1))) {
4576       unsigned NumBits = VT.getSizeInBits();
4577       return getVShift(true, VT,
4578                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4579                                    VT, Op.getOperand(1)),
4580                        NumBits/2, DAG, *this, dl);
4581     }
4582
4583     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4584       return SDValue();
4585
4586     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4587     // is a non-constant being inserted into an element other than the low one,
4588     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4589     // movd/movss) to move this into the low element, then shuffle it into
4590     // place.
4591     if (EVTBits == 32) {
4592       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4593
4594       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4595       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4596                                          Subtarget->hasSSE2(), DAG);
4597       SmallVector<int, 8> MaskVec;
4598       for (unsigned i = 0; i < NumElems; i++)
4599         MaskVec.push_back(i == Idx ? 0 : 1);
4600       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4601     }
4602   }
4603
4604   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4605   if (Values.size() == 1) {
4606     if (EVTBits == 32) {
4607       // Instead of a shuffle like this:
4608       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4609       // Check if it's possible to issue this instead.
4610       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4611       unsigned Idx = CountTrailingZeros_32(NonZeros);
4612       SDValue Item = Op.getOperand(Idx);
4613       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4614         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4615     }
4616     return SDValue();
4617   }
4618
4619   // A vector full of immediates; various special cases are already
4620   // handled, so this is best done with a single constant-pool load.
4621   if (IsAllConstants)
4622     return SDValue();
4623
4624   // Let legalizer expand 2-wide build_vectors.
4625   if (EVTBits == 64) {
4626     if (NumNonZero == 1) {
4627       // One half is zero or undef.
4628       unsigned Idx = CountTrailingZeros_32(NonZeros);
4629       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4630                                  Op.getOperand(Idx));
4631       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4632                                          Subtarget->hasSSE2(), DAG);
4633     }
4634     return SDValue();
4635   }
4636
4637   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4638   if (EVTBits == 8 && NumElems == 16) {
4639     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4640                                         *this);
4641     if (V.getNode()) return V;
4642   }
4643
4644   if (EVTBits == 16 && NumElems == 8) {
4645     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4646                                       *this);
4647     if (V.getNode()) return V;
4648   }
4649
4650   // If element VT is == 32 bits, turn it into a number of shuffles.
4651   SmallVector<SDValue, 8> V;
4652   V.resize(NumElems);
4653   if (NumElems == 4 && NumZero > 0) {
4654     for (unsigned i = 0; i < 4; ++i) {
4655       bool isZero = !(NonZeros & (1 << i));
4656       if (isZero)
4657         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4658       else
4659         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4660     }
4661
4662     for (unsigned i = 0; i < 2; ++i) {
4663       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4664         default: break;
4665         case 0:
4666           V[i] = V[i*2];  // Must be a zero vector.
4667           break;
4668         case 1:
4669           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4670           break;
4671         case 2:
4672           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4673           break;
4674         case 3:
4675           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4676           break;
4677       }
4678     }
4679
4680     SmallVector<int, 8> MaskVec;
4681     bool Reverse = (NonZeros & 0x3) == 2;
4682     for (unsigned i = 0; i < 2; ++i)
4683       MaskVec.push_back(Reverse ? 1-i : i);
4684     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4685     for (unsigned i = 0; i < 2; ++i)
4686       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4687     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4688   }
4689
4690   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4691     // Check for a build vector of consecutive loads.
4692     for (unsigned i = 0; i < NumElems; ++i)
4693       V[i] = Op.getOperand(i);
4694
4695     // Check for elements which are consecutive loads.
4696     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4697     if (LD.getNode())
4698       return LD;
4699
4700     // For SSE 4.1, use insertps to put the high elements into the low element.
4701     if (getSubtarget()->hasSSE41()) {
4702       SDValue Result;
4703       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4704         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4705       else
4706         Result = DAG.getUNDEF(VT);
4707
4708       for (unsigned i = 1; i < NumElems; ++i) {
4709         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4710         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4711                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4712       }
4713       return Result;
4714     }
4715
4716     // Otherwise, expand into a number of unpckl*, start by extending each of
4717     // our (non-undef) elements to the full vector width with the element in the
4718     // bottom slot of the vector (which generates no code for SSE).
4719     for (unsigned i = 0; i < NumElems; ++i) {
4720       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4721         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4722       else
4723         V[i] = DAG.getUNDEF(VT);
4724     }
4725
4726     // Next, we iteratively mix elements, e.g. for v4f32:
4727     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4728     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4729     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4730     unsigned EltStride = NumElems >> 1;
4731     while (EltStride != 0) {
4732       for (unsigned i = 0; i < EltStride; ++i) {
4733         // If V[i+EltStride] is undef and this is the first round of mixing,
4734         // then it is safe to just drop this shuffle: V[i] is already in the
4735         // right place, the one element (since it's the first round) being
4736         // inserted as undef can be dropped.  This isn't safe for successive
4737         // rounds because they will permute elements within both vectors.
4738         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4739             EltStride == NumElems/2)
4740           continue;
4741
4742         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4743       }
4744       EltStride >>= 1;
4745     }
4746     return V[0];
4747   }
4748   return SDValue();
4749 }
4750
4751 SDValue
4752 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4753   // We support concatenate two MMX registers and place them in a MMX
4754   // register.  This is better than doing a stack convert.
4755   DebugLoc dl = Op.getDebugLoc();
4756   EVT ResVT = Op.getValueType();
4757   assert(Op.getNumOperands() == 2);
4758   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4759          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4760   int Mask[2];
4761   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4762   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4763   InVec = Op.getOperand(1);
4764   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4765     unsigned NumElts = ResVT.getVectorNumElements();
4766     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4767     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4768                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4769   } else {
4770     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4771     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4772     Mask[0] = 0; Mask[1] = 2;
4773     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4774   }
4775   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4776 }
4777
4778 // v8i16 shuffles - Prefer shuffles in the following order:
4779 // 1. [all]   pshuflw, pshufhw, optional move
4780 // 2. [ssse3] 1 x pshufb
4781 // 3. [ssse3] 2 x pshufb + 1 x por
4782 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4783 SDValue
4784 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4785                                             SelectionDAG &DAG) const {
4786   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4787   SDValue V1 = SVOp->getOperand(0);
4788   SDValue V2 = SVOp->getOperand(1);
4789   DebugLoc dl = SVOp->getDebugLoc();
4790   SmallVector<int, 8> MaskVals;
4791
4792   // Determine if more than 1 of the words in each of the low and high quadwords
4793   // of the result come from the same quadword of one of the two inputs.  Undef
4794   // mask values count as coming from any quadword, for better codegen.
4795   SmallVector<unsigned, 4> LoQuad(4);
4796   SmallVector<unsigned, 4> HiQuad(4);
4797   BitVector InputQuads(4);
4798   for (unsigned i = 0; i < 8; ++i) {
4799     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4800     int EltIdx = SVOp->getMaskElt(i);
4801     MaskVals.push_back(EltIdx);
4802     if (EltIdx < 0) {
4803       ++Quad[0];
4804       ++Quad[1];
4805       ++Quad[2];
4806       ++Quad[3];
4807       continue;
4808     }
4809     ++Quad[EltIdx / 4];
4810     InputQuads.set(EltIdx / 4);
4811   }
4812
4813   int BestLoQuad = -1;
4814   unsigned MaxQuad = 1;
4815   for (unsigned i = 0; i < 4; ++i) {
4816     if (LoQuad[i] > MaxQuad) {
4817       BestLoQuad = i;
4818       MaxQuad = LoQuad[i];
4819     }
4820   }
4821
4822   int BestHiQuad = -1;
4823   MaxQuad = 1;
4824   for (unsigned i = 0; i < 4; ++i) {
4825     if (HiQuad[i] > MaxQuad) {
4826       BestHiQuad = i;
4827       MaxQuad = HiQuad[i];
4828     }
4829   }
4830
4831   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4832   // of the two input vectors, shuffle them into one input vector so only a
4833   // single pshufb instruction is necessary. If There are more than 2 input
4834   // quads, disable the next transformation since it does not help SSSE3.
4835   bool V1Used = InputQuads[0] || InputQuads[1];
4836   bool V2Used = InputQuads[2] || InputQuads[3];
4837   if (Subtarget->hasSSSE3()) {
4838     if (InputQuads.count() == 2 && V1Used && V2Used) {
4839       BestLoQuad = InputQuads.find_first();
4840       BestHiQuad = InputQuads.find_next(BestLoQuad);
4841     }
4842     if (InputQuads.count() > 2) {
4843       BestLoQuad = -1;
4844       BestHiQuad = -1;
4845     }
4846   }
4847
4848   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4849   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4850   // words from all 4 input quadwords.
4851   SDValue NewV;
4852   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4853     SmallVector<int, 8> MaskV;
4854     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4855     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4856     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4857                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4858                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4859     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4860
4861     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4862     // source words for the shuffle, to aid later transformations.
4863     bool AllWordsInNewV = true;
4864     bool InOrder[2] = { true, true };
4865     for (unsigned i = 0; i != 8; ++i) {
4866       int idx = MaskVals[i];
4867       if (idx != (int)i)
4868         InOrder[i/4] = false;
4869       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4870         continue;
4871       AllWordsInNewV = false;
4872       break;
4873     }
4874
4875     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4876     if (AllWordsInNewV) {
4877       for (int i = 0; i != 8; ++i) {
4878         int idx = MaskVals[i];
4879         if (idx < 0)
4880           continue;
4881         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4882         if ((idx != i) && idx < 4)
4883           pshufhw = false;
4884         if ((idx != i) && idx > 3)
4885           pshuflw = false;
4886       }
4887       V1 = NewV;
4888       V2Used = false;
4889       BestLoQuad = 0;
4890       BestHiQuad = 1;
4891     }
4892
4893     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4894     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4895     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4896       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4897       unsigned TargetMask = 0;
4898       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4899                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4900       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4901                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4902       V1 = NewV.getOperand(0);
4903       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4904     }
4905   }
4906
4907   // If we have SSSE3, and all words of the result are from 1 input vector,
4908   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4909   // is present, fall back to case 4.
4910   if (Subtarget->hasSSSE3()) {
4911     SmallVector<SDValue,16> pshufbMask;
4912
4913     // If we have elements from both input vectors, set the high bit of the
4914     // shuffle mask element to zero out elements that come from V2 in the V1
4915     // mask, and elements that come from V1 in the V2 mask, so that the two
4916     // results can be OR'd together.
4917     bool TwoInputs = V1Used && V2Used;
4918     for (unsigned i = 0; i != 8; ++i) {
4919       int EltIdx = MaskVals[i] * 2;
4920       if (TwoInputs && (EltIdx >= 16)) {
4921         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4922         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4923         continue;
4924       }
4925       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4926       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4927     }
4928     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4929     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4930                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4931                                  MVT::v16i8, &pshufbMask[0], 16));
4932     if (!TwoInputs)
4933       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4934
4935     // Calculate the shuffle mask for the second input, shuffle it, and
4936     // OR it with the first shuffled input.
4937     pshufbMask.clear();
4938     for (unsigned i = 0; i != 8; ++i) {
4939       int EltIdx = MaskVals[i] * 2;
4940       if (EltIdx < 16) {
4941         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4942         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4943         continue;
4944       }
4945       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4946       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4947     }
4948     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4949     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4950                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4951                                  MVT::v16i8, &pshufbMask[0], 16));
4952     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4953     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4954   }
4955
4956   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4957   // and update MaskVals with new element order.
4958   BitVector InOrder(8);
4959   if (BestLoQuad >= 0) {
4960     SmallVector<int, 8> MaskV;
4961     for (int i = 0; i != 4; ++i) {
4962       int idx = MaskVals[i];
4963       if (idx < 0) {
4964         MaskV.push_back(-1);
4965         InOrder.set(i);
4966       } else if ((idx / 4) == BestLoQuad) {
4967         MaskV.push_back(idx & 3);
4968         InOrder.set(i);
4969       } else {
4970         MaskV.push_back(-1);
4971       }
4972     }
4973     for (unsigned i = 4; i != 8; ++i)
4974       MaskV.push_back(i);
4975     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4976                                 &MaskV[0]);
4977
4978     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4979       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4980                                NewV.getOperand(0),
4981                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4982                                DAG);
4983   }
4984
4985   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4986   // and update MaskVals with the new element order.
4987   if (BestHiQuad >= 0) {
4988     SmallVector<int, 8> MaskV;
4989     for (unsigned i = 0; i != 4; ++i)
4990       MaskV.push_back(i);
4991     for (unsigned i = 4; i != 8; ++i) {
4992       int idx = MaskVals[i];
4993       if (idx < 0) {
4994         MaskV.push_back(-1);
4995         InOrder.set(i);
4996       } else if ((idx / 4) == BestHiQuad) {
4997         MaskV.push_back((idx & 3) + 4);
4998         InOrder.set(i);
4999       } else {
5000         MaskV.push_back(-1);
5001       }
5002     }
5003     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5004                                 &MaskV[0]);
5005
5006     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5007       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5008                               NewV.getOperand(0),
5009                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5010                               DAG);
5011   }
5012
5013   // In case BestHi & BestLo were both -1, which means each quadword has a word
5014   // from each of the four input quadwords, calculate the InOrder bitvector now
5015   // before falling through to the insert/extract cleanup.
5016   if (BestLoQuad == -1 && BestHiQuad == -1) {
5017     NewV = V1;
5018     for (int i = 0; i != 8; ++i)
5019       if (MaskVals[i] < 0 || MaskVals[i] == i)
5020         InOrder.set(i);
5021   }
5022
5023   // The other elements are put in the right place using pextrw and pinsrw.
5024   for (unsigned i = 0; i != 8; ++i) {
5025     if (InOrder[i])
5026       continue;
5027     int EltIdx = MaskVals[i];
5028     if (EltIdx < 0)
5029       continue;
5030     SDValue ExtOp = (EltIdx < 8)
5031     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5032                   DAG.getIntPtrConstant(EltIdx))
5033     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5034                   DAG.getIntPtrConstant(EltIdx - 8));
5035     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5036                        DAG.getIntPtrConstant(i));
5037   }
5038   return NewV;
5039 }
5040
5041 // v16i8 shuffles - Prefer shuffles in the following order:
5042 // 1. [ssse3] 1 x pshufb
5043 // 2. [ssse3] 2 x pshufb + 1 x por
5044 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5045 static
5046 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5047                                  SelectionDAG &DAG,
5048                                  const X86TargetLowering &TLI) {
5049   SDValue V1 = SVOp->getOperand(0);
5050   SDValue V2 = SVOp->getOperand(1);
5051   DebugLoc dl = SVOp->getDebugLoc();
5052   SmallVector<int, 16> MaskVals;
5053   SVOp->getMask(MaskVals);
5054
5055   // If we have SSSE3, case 1 is generated when all result bytes come from
5056   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5057   // present, fall back to case 3.
5058   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5059   bool V1Only = true;
5060   bool V2Only = true;
5061   for (unsigned i = 0; i < 16; ++i) {
5062     int EltIdx = MaskVals[i];
5063     if (EltIdx < 0)
5064       continue;
5065     if (EltIdx < 16)
5066       V2Only = false;
5067     else
5068       V1Only = false;
5069   }
5070
5071   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5072   if (TLI.getSubtarget()->hasSSSE3()) {
5073     SmallVector<SDValue,16> pshufbMask;
5074
5075     // If all result elements are from one input vector, then only translate
5076     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5077     //
5078     // Otherwise, we have elements from both input vectors, and must zero out
5079     // elements that come from V2 in the first mask, and V1 in the second mask
5080     // so that we can OR them together.
5081     bool TwoInputs = !(V1Only || V2Only);
5082     for (unsigned i = 0; i != 16; ++i) {
5083       int EltIdx = MaskVals[i];
5084       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5085         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5086         continue;
5087       }
5088       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5089     }
5090     // If all the elements are from V2, assign it to V1 and return after
5091     // building the first pshufb.
5092     if (V2Only)
5093       V1 = V2;
5094     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5095                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5096                                  MVT::v16i8, &pshufbMask[0], 16));
5097     if (!TwoInputs)
5098       return V1;
5099
5100     // Calculate the shuffle mask for the second input, shuffle it, and
5101     // OR it with the first shuffled input.
5102     pshufbMask.clear();
5103     for (unsigned i = 0; i != 16; ++i) {
5104       int EltIdx = MaskVals[i];
5105       if (EltIdx < 16) {
5106         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5107         continue;
5108       }
5109       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5110     }
5111     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5112                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5113                                  MVT::v16i8, &pshufbMask[0], 16));
5114     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5115   }
5116
5117   // No SSSE3 - Calculate in place words and then fix all out of place words
5118   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5119   // the 16 different words that comprise the two doublequadword input vectors.
5120   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5121   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5122   SDValue NewV = V2Only ? V2 : V1;
5123   for (int i = 0; i != 8; ++i) {
5124     int Elt0 = MaskVals[i*2];
5125     int Elt1 = MaskVals[i*2+1];
5126
5127     // This word of the result is all undef, skip it.
5128     if (Elt0 < 0 && Elt1 < 0)
5129       continue;
5130
5131     // This word of the result is already in the correct place, skip it.
5132     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5133       continue;
5134     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5135       continue;
5136
5137     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5138     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5139     SDValue InsElt;
5140
5141     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5142     // using a single extract together, load it and store it.
5143     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5144       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5145                            DAG.getIntPtrConstant(Elt1 / 2));
5146       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5147                         DAG.getIntPtrConstant(i));
5148       continue;
5149     }
5150
5151     // If Elt1 is defined, extract it from the appropriate source.  If the
5152     // source byte is not also odd, shift the extracted word left 8 bits
5153     // otherwise clear the bottom 8 bits if we need to do an or.
5154     if (Elt1 >= 0) {
5155       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5156                            DAG.getIntPtrConstant(Elt1 / 2));
5157       if ((Elt1 & 1) == 0)
5158         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5159                              DAG.getConstant(8,
5160                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5161       else if (Elt0 >= 0)
5162         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5163                              DAG.getConstant(0xFF00, MVT::i16));
5164     }
5165     // If Elt0 is defined, extract it from the appropriate source.  If the
5166     // source byte is not also even, shift the extracted word right 8 bits. If
5167     // Elt1 was also defined, OR the extracted values together before
5168     // inserting them in the result.
5169     if (Elt0 >= 0) {
5170       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5171                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5172       if ((Elt0 & 1) != 0)
5173         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5174                               DAG.getConstant(8,
5175                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5176       else if (Elt1 >= 0)
5177         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5178                              DAG.getConstant(0x00FF, MVT::i16));
5179       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5180                          : InsElt0;
5181     }
5182     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5183                        DAG.getIntPtrConstant(i));
5184   }
5185   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5186 }
5187
5188 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5189 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5190 /// done when every pair / quad of shuffle mask elements point to elements in
5191 /// the right sequence. e.g.
5192 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5193 static
5194 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5195                                  SelectionDAG &DAG, DebugLoc dl) {
5196   EVT VT = SVOp->getValueType(0);
5197   SDValue V1 = SVOp->getOperand(0);
5198   SDValue V2 = SVOp->getOperand(1);
5199   unsigned NumElems = VT.getVectorNumElements();
5200   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5201   EVT NewVT;
5202   switch (VT.getSimpleVT().SimpleTy) {
5203   default: assert(false && "Unexpected!");
5204   case MVT::v4f32: NewVT = MVT::v2f64; break;
5205   case MVT::v4i32: NewVT = MVT::v2i64; break;
5206   case MVT::v8i16: NewVT = MVT::v4i32; break;
5207   case MVT::v16i8: NewVT = MVT::v4i32; break;
5208   }
5209
5210   int Scale = NumElems / NewWidth;
5211   SmallVector<int, 8> MaskVec;
5212   for (unsigned i = 0; i < NumElems; i += Scale) {
5213     int StartIdx = -1;
5214     for (int j = 0; j < Scale; ++j) {
5215       int EltIdx = SVOp->getMaskElt(i+j);
5216       if (EltIdx < 0)
5217         continue;
5218       if (StartIdx == -1)
5219         StartIdx = EltIdx - (EltIdx % Scale);
5220       if (EltIdx != StartIdx + j)
5221         return SDValue();
5222     }
5223     if (StartIdx == -1)
5224       MaskVec.push_back(-1);
5225     else
5226       MaskVec.push_back(StartIdx / Scale);
5227   }
5228
5229   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5230   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5231   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5232 }
5233
5234 /// getVZextMovL - Return a zero-extending vector move low node.
5235 ///
5236 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5237                             SDValue SrcOp, SelectionDAG &DAG,
5238                             const X86Subtarget *Subtarget, DebugLoc dl) {
5239   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5240     LoadSDNode *LD = NULL;
5241     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5242       LD = dyn_cast<LoadSDNode>(SrcOp);
5243     if (!LD) {
5244       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5245       // instead.
5246       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5247       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5248           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5249           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5250           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5251         // PR2108
5252         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5253         return DAG.getNode(ISD::BITCAST, dl, VT,
5254                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5255                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5256                                                    OpVT,
5257                                                    SrcOp.getOperand(0)
5258                                                           .getOperand(0))));
5259       }
5260     }
5261   }
5262
5263   return DAG.getNode(ISD::BITCAST, dl, VT,
5264                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5265                                  DAG.getNode(ISD::BITCAST, dl,
5266                                              OpVT, SrcOp)));
5267 }
5268
5269 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5270 /// shuffles.
5271 static SDValue
5272 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5273   SDValue V1 = SVOp->getOperand(0);
5274   SDValue V2 = SVOp->getOperand(1);
5275   DebugLoc dl = SVOp->getDebugLoc();
5276   EVT VT = SVOp->getValueType(0);
5277
5278   SmallVector<std::pair<int, int>, 8> Locs;
5279   Locs.resize(4);
5280   SmallVector<int, 8> Mask1(4U, -1);
5281   SmallVector<int, 8> PermMask;
5282   SVOp->getMask(PermMask);
5283
5284   unsigned NumHi = 0;
5285   unsigned NumLo = 0;
5286   for (unsigned i = 0; i != 4; ++i) {
5287     int Idx = PermMask[i];
5288     if (Idx < 0) {
5289       Locs[i] = std::make_pair(-1, -1);
5290     } else {
5291       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5292       if (Idx < 4) {
5293         Locs[i] = std::make_pair(0, NumLo);
5294         Mask1[NumLo] = Idx;
5295         NumLo++;
5296       } else {
5297         Locs[i] = std::make_pair(1, NumHi);
5298         if (2+NumHi < 4)
5299           Mask1[2+NumHi] = Idx;
5300         NumHi++;
5301       }
5302     }
5303   }
5304
5305   if (NumLo <= 2 && NumHi <= 2) {
5306     // If no more than two elements come from either vector. This can be
5307     // implemented with two shuffles. First shuffle gather the elements.
5308     // The second shuffle, which takes the first shuffle as both of its
5309     // vector operands, put the elements into the right order.
5310     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5311
5312     SmallVector<int, 8> Mask2(4U, -1);
5313
5314     for (unsigned i = 0; i != 4; ++i) {
5315       if (Locs[i].first == -1)
5316         continue;
5317       else {
5318         unsigned Idx = (i < 2) ? 0 : 4;
5319         Idx += Locs[i].first * 2 + Locs[i].second;
5320         Mask2[i] = Idx;
5321       }
5322     }
5323
5324     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5325   } else if (NumLo == 3 || NumHi == 3) {
5326     // Otherwise, we must have three elements from one vector, call it X, and
5327     // one element from the other, call it Y.  First, use a shufps to build an
5328     // intermediate vector with the one element from Y and the element from X
5329     // that will be in the same half in the final destination (the indexes don't
5330     // matter). Then, use a shufps to build the final vector, taking the half
5331     // containing the element from Y from the intermediate, and the other half
5332     // from X.
5333     if (NumHi == 3) {
5334       // Normalize it so the 3 elements come from V1.
5335       CommuteVectorShuffleMask(PermMask, VT);
5336       std::swap(V1, V2);
5337     }
5338
5339     // Find the element from V2.
5340     unsigned HiIndex;
5341     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5342       int Val = PermMask[HiIndex];
5343       if (Val < 0)
5344         continue;
5345       if (Val >= 4)
5346         break;
5347     }
5348
5349     Mask1[0] = PermMask[HiIndex];
5350     Mask1[1] = -1;
5351     Mask1[2] = PermMask[HiIndex^1];
5352     Mask1[3] = -1;
5353     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5354
5355     if (HiIndex >= 2) {
5356       Mask1[0] = PermMask[0];
5357       Mask1[1] = PermMask[1];
5358       Mask1[2] = HiIndex & 1 ? 6 : 4;
5359       Mask1[3] = HiIndex & 1 ? 4 : 6;
5360       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5361     } else {
5362       Mask1[0] = HiIndex & 1 ? 2 : 0;
5363       Mask1[1] = HiIndex & 1 ? 0 : 2;
5364       Mask1[2] = PermMask[2];
5365       Mask1[3] = PermMask[3];
5366       if (Mask1[2] >= 0)
5367         Mask1[2] += 4;
5368       if (Mask1[3] >= 0)
5369         Mask1[3] += 4;
5370       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5371     }
5372   }
5373
5374   // Break it into (shuffle shuffle_hi, shuffle_lo).
5375   Locs.clear();
5376   Locs.resize(4);
5377   SmallVector<int,8> LoMask(4U, -1);
5378   SmallVector<int,8> HiMask(4U, -1);
5379
5380   SmallVector<int,8> *MaskPtr = &LoMask;
5381   unsigned MaskIdx = 0;
5382   unsigned LoIdx = 0;
5383   unsigned HiIdx = 2;
5384   for (unsigned i = 0; i != 4; ++i) {
5385     if (i == 2) {
5386       MaskPtr = &HiMask;
5387       MaskIdx = 1;
5388       LoIdx = 0;
5389       HiIdx = 2;
5390     }
5391     int Idx = PermMask[i];
5392     if (Idx < 0) {
5393       Locs[i] = std::make_pair(-1, -1);
5394     } else if (Idx < 4) {
5395       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5396       (*MaskPtr)[LoIdx] = Idx;
5397       LoIdx++;
5398     } else {
5399       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5400       (*MaskPtr)[HiIdx] = Idx;
5401       HiIdx++;
5402     }
5403   }
5404
5405   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5406   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5407   SmallVector<int, 8> MaskOps;
5408   for (unsigned i = 0; i != 4; ++i) {
5409     if (Locs[i].first == -1) {
5410       MaskOps.push_back(-1);
5411     } else {
5412       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5413       MaskOps.push_back(Idx);
5414     }
5415   }
5416   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5417 }
5418
5419 static bool MayFoldVectorLoad(SDValue V) {
5420   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5421     V = V.getOperand(0);
5422   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5423     V = V.getOperand(0);
5424   if (MayFoldLoad(V))
5425     return true;
5426   return false;
5427 }
5428
5429 // FIXME: the version above should always be used. Since there's
5430 // a bug where several vector shuffles can't be folded because the
5431 // DAG is not updated during lowering and a node claims to have two
5432 // uses while it only has one, use this version, and let isel match
5433 // another instruction if the load really happens to have more than
5434 // one use. Remove this version after this bug get fixed.
5435 // rdar://8434668, PR8156
5436 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5437   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5438     V = V.getOperand(0);
5439   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5440     V = V.getOperand(0);
5441   if (ISD::isNormalLoad(V.getNode()))
5442     return true;
5443   return false;
5444 }
5445
5446 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5447 /// a vector extract, and if both can be later optimized into a single load.
5448 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5449 /// here because otherwise a target specific shuffle node is going to be
5450 /// emitted for this shuffle, and the optimization not done.
5451 /// FIXME: This is probably not the best approach, but fix the problem
5452 /// until the right path is decided.
5453 static
5454 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5455                                          const TargetLowering &TLI) {
5456   EVT VT = V.getValueType();
5457   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5458
5459   // Be sure that the vector shuffle is present in a pattern like this:
5460   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5461   if (!V.hasOneUse())
5462     return false;
5463
5464   SDNode *N = *V.getNode()->use_begin();
5465   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5466     return false;
5467
5468   SDValue EltNo = N->getOperand(1);
5469   if (!isa<ConstantSDNode>(EltNo))
5470     return false;
5471
5472   // If the bit convert changed the number of elements, it is unsafe
5473   // to examine the mask.
5474   bool HasShuffleIntoBitcast = false;
5475   if (V.getOpcode() == ISD::BITCAST) {
5476     EVT SrcVT = V.getOperand(0).getValueType();
5477     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5478       return false;
5479     V = V.getOperand(0);
5480     HasShuffleIntoBitcast = true;
5481   }
5482
5483   // Select the input vector, guarding against out of range extract vector.
5484   unsigned NumElems = VT.getVectorNumElements();
5485   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5486   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5487   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5488
5489   // Skip one more bit_convert if necessary
5490   if (V.getOpcode() == ISD::BITCAST)
5491     V = V.getOperand(0);
5492
5493   if (ISD::isNormalLoad(V.getNode())) {
5494     // Is the original load suitable?
5495     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5496
5497     // FIXME: avoid the multi-use bug that is preventing lots of
5498     // of foldings to be detected, this is still wrong of course, but
5499     // give the temporary desired behavior, and if it happens that
5500     // the load has real more uses, during isel it will not fold, and
5501     // will generate poor code.
5502     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5503       return false;
5504
5505     if (!HasShuffleIntoBitcast)
5506       return true;
5507
5508     // If there's a bitcast before the shuffle, check if the load type and
5509     // alignment is valid.
5510     unsigned Align = LN0->getAlignment();
5511     unsigned NewAlign =
5512       TLI.getTargetData()->getABITypeAlignment(
5513                                     VT.getTypeForEVT(*DAG.getContext()));
5514
5515     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5516       return false;
5517   }
5518
5519   return true;
5520 }
5521
5522 static
5523 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5524   EVT VT = Op.getValueType();
5525
5526   // Canonizalize to v2f64.
5527   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5528   return DAG.getNode(ISD::BITCAST, dl, VT,
5529                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5530                                           V1, DAG));
5531 }
5532
5533 static
5534 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5535                         bool HasSSE2) {
5536   SDValue V1 = Op.getOperand(0);
5537   SDValue V2 = Op.getOperand(1);
5538   EVT VT = Op.getValueType();
5539
5540   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5541
5542   if (HasSSE2 && VT == MVT::v2f64)
5543     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5544
5545   // v4f32 or v4i32
5546   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5547 }
5548
5549 static
5550 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5551   SDValue V1 = Op.getOperand(0);
5552   SDValue V2 = Op.getOperand(1);
5553   EVT VT = Op.getValueType();
5554
5555   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5556          "unsupported shuffle type");
5557
5558   if (V2.getOpcode() == ISD::UNDEF)
5559     V2 = V1;
5560
5561   // v4i32 or v4f32
5562   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5563 }
5564
5565 static
5566 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5567   SDValue V1 = Op.getOperand(0);
5568   SDValue V2 = Op.getOperand(1);
5569   EVT VT = Op.getValueType();
5570   unsigned NumElems = VT.getVectorNumElements();
5571
5572   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5573   // operand of these instructions is only memory, so check if there's a
5574   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5575   // same masks.
5576   bool CanFoldLoad = false;
5577
5578   // Trivial case, when V2 comes from a load.
5579   if (MayFoldVectorLoad(V2))
5580     CanFoldLoad = true;
5581
5582   // When V1 is a load, it can be folded later into a store in isel, example:
5583   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5584   //    turns into:
5585   //  (MOVLPSmr addr:$src1, VR128:$src2)
5586   // So, recognize this potential and also use MOVLPS or MOVLPD
5587   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5588     CanFoldLoad = true;
5589
5590   // Both of them can't be memory operations though.
5591   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5592     CanFoldLoad = false;
5593
5594   if (CanFoldLoad) {
5595     if (HasSSE2 && NumElems == 2)
5596       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5597
5598     if (NumElems == 4)
5599       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5600   }
5601
5602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5603   // movl and movlp will both match v2i64, but v2i64 is never matched by
5604   // movl earlier because we make it strict to avoid messing with the movlp load
5605   // folding logic (see the code above getMOVLP call). Match it here then,
5606   // this is horrible, but will stay like this until we move all shuffle
5607   // matching to x86 specific nodes. Note that for the 1st condition all
5608   // types are matched with movsd.
5609   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5610     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5611   else if (HasSSE2)
5612     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5613
5614
5615   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5616
5617   // Invert the operand order and use SHUFPS to match it.
5618   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5619                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5620 }
5621
5622 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5623   switch(VT.getSimpleVT().SimpleTy) {
5624   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5625   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5626   case MVT::v4f32:
5627     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5628   case MVT::v2f64:
5629     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5630   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5631   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5632   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5633   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5634   default:
5635     llvm_unreachable("Unknown type for unpckl");
5636   }
5637   return 0;
5638 }
5639
5640 static inline unsigned getUNPCKHOpcode(EVT VT) {
5641   switch(VT.getSimpleVT().SimpleTy) {
5642   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5643   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5644   case MVT::v4f32: return X86ISD::UNPCKHPS;
5645   case MVT::v2f64: return X86ISD::UNPCKHPD;
5646   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5647   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5648   default:
5649     llvm_unreachable("Unknown type for unpckh");
5650   }
5651   return 0;
5652 }
5653
5654 static
5655 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5656                                const TargetLowering &TLI,
5657                                const X86Subtarget *Subtarget) {
5658   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5659   EVT VT = Op.getValueType();
5660   DebugLoc dl = Op.getDebugLoc();
5661   SDValue V1 = Op.getOperand(0);
5662   SDValue V2 = Op.getOperand(1);
5663
5664   if (isZeroShuffle(SVOp))
5665     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5666
5667   // Handle splat operations
5668   if (SVOp->isSplat()) {
5669     // Special case, this is the only place now where it's
5670     // allowed to return a vector_shuffle operation without
5671     // using a target specific node, because *hopefully* it
5672     // will be optimized away by the dag combiner.
5673     if (VT.getVectorNumElements() <= 4 &&
5674         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5675       return Op;
5676
5677     // Handle splats by matching through known masks
5678     if (VT.getVectorNumElements() <= 4)
5679       return SDValue();
5680
5681     // Canonicalize all of the remaining to v4f32.
5682     return PromoteSplat(SVOp, DAG);
5683   }
5684
5685   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5686   // do it!
5687   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5688     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5689     if (NewOp.getNode())
5690       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5691   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5692     // FIXME: Figure out a cleaner way to do this.
5693     // Try to make use of movq to zero out the top part.
5694     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5695       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5696       if (NewOp.getNode()) {
5697         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5698           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5699                               DAG, Subtarget, dl);
5700       }
5701     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5702       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5703       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5704         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5705                             DAG, Subtarget, dl);
5706     }
5707   }
5708   return SDValue();
5709 }
5710
5711 SDValue
5712 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5713   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5714   SDValue V1 = Op.getOperand(0);
5715   SDValue V2 = Op.getOperand(1);
5716   EVT VT = Op.getValueType();
5717   DebugLoc dl = Op.getDebugLoc();
5718   unsigned NumElems = VT.getVectorNumElements();
5719   bool isMMX = VT.getSizeInBits() == 64;
5720   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5721   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5722   bool V1IsSplat = false;
5723   bool V2IsSplat = false;
5724   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5725   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5726   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5727   MachineFunction &MF = DAG.getMachineFunction();
5728   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5729
5730   // Shuffle operations on MMX not supported.
5731   if (isMMX)
5732     return Op;
5733
5734   // Vector shuffle lowering takes 3 steps:
5735   //
5736   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5737   //    narrowing and commutation of operands should be handled.
5738   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5739   //    shuffle nodes.
5740   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5741   //    so the shuffle can be broken into other shuffles and the legalizer can
5742   //    try the lowering again.
5743   //
5744   // The general ideia is that no vector_shuffle operation should be left to
5745   // be matched during isel, all of them must be converted to a target specific
5746   // node here.
5747
5748   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5749   // narrowing and commutation of operands should be handled. The actual code
5750   // doesn't include all of those, work in progress...
5751   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5752   if (NewOp.getNode())
5753     return NewOp;
5754
5755   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5756   // unpckh_undef). Only use pshufd if speed is more important than size.
5757   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5758     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5759       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5760   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5761     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5762       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5763
5764   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5765       RelaxedMayFoldVectorLoad(V1))
5766     return getMOVDDup(Op, dl, V1, DAG);
5767
5768   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5769     return getMOVHighToLow(Op, dl, DAG);
5770
5771   // Use to match splats
5772   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5773       (VT == MVT::v2f64 || VT == MVT::v2i64))
5774     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5775
5776   if (X86::isPSHUFDMask(SVOp)) {
5777     // The actual implementation will match the mask in the if above and then
5778     // during isel it can match several different instructions, not only pshufd
5779     // as its name says, sad but true, emulate the behavior for now...
5780     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5781         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5782
5783     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5784
5785     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5786       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5787
5788     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5789       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5790                                   TargetMask, DAG);
5791
5792     if (VT == MVT::v4f32)
5793       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5794                                   TargetMask, DAG);
5795   }
5796
5797   // Check if this can be converted into a logical shift.
5798   bool isLeft = false;
5799   unsigned ShAmt = 0;
5800   SDValue ShVal;
5801   bool isShift = getSubtarget()->hasSSE2() &&
5802     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5803   if (isShift && ShVal.hasOneUse()) {
5804     // If the shifted value has multiple uses, it may be cheaper to use
5805     // v_set0 + movlhps or movhlps, etc.
5806     EVT EltVT = VT.getVectorElementType();
5807     ShAmt *= EltVT.getSizeInBits();
5808     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5809   }
5810
5811   if (X86::isMOVLMask(SVOp)) {
5812     if (V1IsUndef)
5813       return V2;
5814     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5815       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5816     if (!X86::isMOVLPMask(SVOp)) {
5817       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5818         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5819
5820       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5821         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5822     }
5823   }
5824
5825   // FIXME: fold these into legal mask.
5826   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5827     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5828
5829   if (X86::isMOVHLPSMask(SVOp))
5830     return getMOVHighToLow(Op, dl, DAG);
5831
5832   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5833     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5834
5835   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5836     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5837
5838   if (X86::isMOVLPMask(SVOp))
5839     return getMOVLP(Op, dl, DAG, HasSSE2);
5840
5841   if (ShouldXformToMOVHLPS(SVOp) ||
5842       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5843     return CommuteVectorShuffle(SVOp, DAG);
5844
5845   if (isShift) {
5846     // No better options. Use a vshl / vsrl.
5847     EVT EltVT = VT.getVectorElementType();
5848     ShAmt *= EltVT.getSizeInBits();
5849     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5850   }
5851
5852   bool Commuted = false;
5853   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5854   // 1,1,1,1 -> v8i16 though.
5855   V1IsSplat = isSplatVector(V1.getNode());
5856   V2IsSplat = isSplatVector(V2.getNode());
5857
5858   // Canonicalize the splat or undef, if present, to be on the RHS.
5859   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5860     Op = CommuteVectorShuffle(SVOp, DAG);
5861     SVOp = cast<ShuffleVectorSDNode>(Op);
5862     V1 = SVOp->getOperand(0);
5863     V2 = SVOp->getOperand(1);
5864     std::swap(V1IsSplat, V2IsSplat);
5865     std::swap(V1IsUndef, V2IsUndef);
5866     Commuted = true;
5867   }
5868
5869   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5870     // Shuffling low element of v1 into undef, just return v1.
5871     if (V2IsUndef)
5872       return V1;
5873     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5874     // the instruction selector will not match, so get a canonical MOVL with
5875     // swapped operands to undo the commute.
5876     return getMOVL(DAG, dl, VT, V2, V1);
5877   }
5878
5879   if (X86::isUNPCKLMask(SVOp))
5880     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5881                                 dl, VT, V1, V2, DAG);
5882
5883   if (X86::isUNPCKHMask(SVOp))
5884     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5885
5886   if (V2IsSplat) {
5887     // Normalize mask so all entries that point to V2 points to its first
5888     // element then try to match unpck{h|l} again. If match, return a
5889     // new vector_shuffle with the corrected mask.
5890     SDValue NewMask = NormalizeMask(SVOp, DAG);
5891     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5892     if (NSVOp != SVOp) {
5893       if (X86::isUNPCKLMask(NSVOp, true)) {
5894         return NewMask;
5895       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5896         return NewMask;
5897       }
5898     }
5899   }
5900
5901   if (Commuted) {
5902     // Commute is back and try unpck* again.
5903     // FIXME: this seems wrong.
5904     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5905     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5906
5907     if (X86::isUNPCKLMask(NewSVOp))
5908       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5909                                   dl, VT, V2, V1, DAG);
5910
5911     if (X86::isUNPCKHMask(NewSVOp))
5912       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5913   }
5914
5915   // Normalize the node to match x86 shuffle ops if needed
5916   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5917     return CommuteVectorShuffle(SVOp, DAG);
5918
5919   // The checks below are all present in isShuffleMaskLegal, but they are
5920   // inlined here right now to enable us to directly emit target specific
5921   // nodes, and remove one by one until they don't return Op anymore.
5922   SmallVector<int, 16> M;
5923   SVOp->getMask(M);
5924
5925   if (isPALIGNRMask(M, VT, HasSSSE3))
5926     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5927                                 X86::getShufflePALIGNRImmediate(SVOp),
5928                                 DAG);
5929
5930   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5931       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5932     if (VT == MVT::v2f64) {
5933       X86ISD::NodeType Opcode =
5934         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5935       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5936     }
5937     if (VT == MVT::v2i64)
5938       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5939   }
5940
5941   if (isPSHUFHWMask(M, VT))
5942     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5943                                 X86::getShufflePSHUFHWImmediate(SVOp),
5944                                 DAG);
5945
5946   if (isPSHUFLWMask(M, VT))
5947     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5948                                 X86::getShufflePSHUFLWImmediate(SVOp),
5949                                 DAG);
5950
5951   if (isSHUFPMask(M, VT)) {
5952     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5953     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5954       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5955                                   TargetMask, DAG);
5956     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5957       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5958                                   TargetMask, DAG);
5959   }
5960
5961   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5962     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5963       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5964                                   dl, VT, V1, V1, DAG);
5965   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5966     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5967       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5968
5969   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5970   if (VT == MVT::v8i16) {
5971     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5972     if (NewOp.getNode())
5973       return NewOp;
5974   }
5975
5976   if (VT == MVT::v16i8) {
5977     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5978     if (NewOp.getNode())
5979       return NewOp;
5980   }
5981
5982   // Handle all 4 wide cases with a number of shuffles.
5983   if (NumElems == 4)
5984     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5985
5986   return SDValue();
5987 }
5988
5989 SDValue
5990 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5991                                                 SelectionDAG &DAG) const {
5992   EVT VT = Op.getValueType();
5993   DebugLoc dl = Op.getDebugLoc();
5994   if (VT.getSizeInBits() == 8) {
5995     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5996                                     Op.getOperand(0), Op.getOperand(1));
5997     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5998                                     DAG.getValueType(VT));
5999     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6000   } else if (VT.getSizeInBits() == 16) {
6001     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6002     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6003     if (Idx == 0)
6004       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6005                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6006                                      DAG.getNode(ISD::BITCAST, dl,
6007                                                  MVT::v4i32,
6008                                                  Op.getOperand(0)),
6009                                      Op.getOperand(1)));
6010     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6011                                     Op.getOperand(0), Op.getOperand(1));
6012     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6013                                     DAG.getValueType(VT));
6014     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6015   } else if (VT == MVT::f32) {
6016     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6017     // the result back to FR32 register. It's only worth matching if the
6018     // result has a single use which is a store or a bitcast to i32.  And in
6019     // the case of a store, it's not worth it if the index is a constant 0,
6020     // because a MOVSSmr can be used instead, which is smaller and faster.
6021     if (!Op.hasOneUse())
6022       return SDValue();
6023     SDNode *User = *Op.getNode()->use_begin();
6024     if ((User->getOpcode() != ISD::STORE ||
6025          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6026           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6027         (User->getOpcode() != ISD::BITCAST ||
6028          User->getValueType(0) != MVT::i32))
6029       return SDValue();
6030     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6031                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6032                                               Op.getOperand(0)),
6033                                               Op.getOperand(1));
6034     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6035   } else if (VT == MVT::i32) {
6036     // ExtractPS works with constant index.
6037     if (isa<ConstantSDNode>(Op.getOperand(1)))
6038       return Op;
6039   }
6040   return SDValue();
6041 }
6042
6043
6044 SDValue
6045 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6046                                            SelectionDAG &DAG) const {
6047   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6048     return SDValue();
6049
6050   SDValue Vec = Op.getOperand(0);
6051   EVT VecVT = Vec.getValueType();
6052
6053   // If this is a 256-bit vector result, first extract the 128-bit
6054   // vector and then extract from the 128-bit vector.
6055   if (VecVT.getSizeInBits() > 128) {
6056     DebugLoc dl = Op.getNode()->getDebugLoc();
6057     unsigned NumElems = VecVT.getVectorNumElements();
6058     SDValue Idx = Op.getOperand(1);
6059
6060     if (!isa<ConstantSDNode>(Idx))
6061       return SDValue();
6062
6063     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6064     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6065
6066     // Get the 128-bit vector.
6067     bool Upper = IdxVal >= ExtractNumElems;
6068     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6069
6070     // Extract from it.
6071     SDValue ScaledIdx = Idx;
6072     if (Upper)
6073       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6074                               DAG.getConstant(ExtractNumElems,
6075                                               Idx.getValueType()));
6076     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6077                        ScaledIdx);
6078   }
6079
6080   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6081
6082   if (Subtarget->hasSSE41()) {
6083     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6084     if (Res.getNode())
6085       return Res;
6086   }
6087
6088   EVT VT = Op.getValueType();
6089   DebugLoc dl = Op.getDebugLoc();
6090   // TODO: handle v16i8.
6091   if (VT.getSizeInBits() == 16) {
6092     SDValue Vec = Op.getOperand(0);
6093     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6094     if (Idx == 0)
6095       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6096                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6097                                      DAG.getNode(ISD::BITCAST, dl,
6098                                                  MVT::v4i32, Vec),
6099                                      Op.getOperand(1)));
6100     // Transform it so it match pextrw which produces a 32-bit result.
6101     EVT EltVT = MVT::i32;
6102     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6103                                     Op.getOperand(0), Op.getOperand(1));
6104     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6105                                     DAG.getValueType(VT));
6106     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6107   } else if (VT.getSizeInBits() == 32) {
6108     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6109     if (Idx == 0)
6110       return Op;
6111
6112     // SHUFPS the element to the lowest double word, then movss.
6113     int Mask[4] = { Idx, -1, -1, -1 };
6114     EVT VVT = Op.getOperand(0).getValueType();
6115     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6116                                        DAG.getUNDEF(VVT), Mask);
6117     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6118                        DAG.getIntPtrConstant(0));
6119   } else if (VT.getSizeInBits() == 64) {
6120     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6121     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6122     //        to match extract_elt for f64.
6123     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6124     if (Idx == 0)
6125       return Op;
6126
6127     // UNPCKHPD the element to the lowest double word, then movsd.
6128     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6129     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6130     int Mask[2] = { 1, -1 };
6131     EVT VVT = Op.getOperand(0).getValueType();
6132     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6133                                        DAG.getUNDEF(VVT), Mask);
6134     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6135                        DAG.getIntPtrConstant(0));
6136   }
6137
6138   return SDValue();
6139 }
6140
6141 SDValue
6142 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6143                                                SelectionDAG &DAG) const {
6144   EVT VT = Op.getValueType();
6145   EVT EltVT = VT.getVectorElementType();
6146   DebugLoc dl = Op.getDebugLoc();
6147
6148   SDValue N0 = Op.getOperand(0);
6149   SDValue N1 = Op.getOperand(1);
6150   SDValue N2 = Op.getOperand(2);
6151
6152   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6153       isa<ConstantSDNode>(N2)) {
6154     unsigned Opc;
6155     if (VT == MVT::v8i16)
6156       Opc = X86ISD::PINSRW;
6157     else if (VT == MVT::v16i8)
6158       Opc = X86ISD::PINSRB;
6159     else
6160       Opc = X86ISD::PINSRB;
6161
6162     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6163     // argument.
6164     if (N1.getValueType() != MVT::i32)
6165       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6166     if (N2.getValueType() != MVT::i32)
6167       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6168     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6169   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6170     // Bits [7:6] of the constant are the source select.  This will always be
6171     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6172     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6173     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6174     // Bits [5:4] of the constant are the destination select.  This is the
6175     //  value of the incoming immediate.
6176     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6177     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6178     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6179     // Create this as a scalar to vector..
6180     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6181     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6182   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6183     // PINSR* works with constant index.
6184     return Op;
6185   }
6186   return SDValue();
6187 }
6188
6189 SDValue
6190 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6191   EVT VT = Op.getValueType();
6192   EVT EltVT = VT.getVectorElementType();
6193
6194   DebugLoc dl = Op.getDebugLoc();
6195   SDValue N0 = Op.getOperand(0);
6196   SDValue N1 = Op.getOperand(1);
6197   SDValue N2 = Op.getOperand(2);
6198
6199   // If this is a 256-bit vector result, first insert into a 128-bit
6200   // vector and then insert into the 256-bit vector.
6201   if (VT.getSizeInBits() > 128) {
6202     if (!isa<ConstantSDNode>(N2))
6203       return SDValue();
6204
6205     // Get the 128-bit vector.
6206     unsigned NumElems = VT.getVectorNumElements();
6207     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6208     bool Upper = IdxVal >= NumElems / 2;
6209
6210     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6211
6212     // Insert into it.
6213     SDValue ScaledN2 = N2;
6214     if (Upper)
6215       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6216                              DAG.getConstant(NumElems /
6217                                              (VT.getSizeInBits() / 128),
6218                                              N2.getValueType()));
6219     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6220                      N1, ScaledN2);
6221
6222     // Insert the 128-bit vector
6223     // FIXME: Why UNDEF?
6224     return Insert128BitVector(N0, Op, N2, DAG, dl);
6225   }
6226
6227   if (Subtarget->hasSSE41())
6228     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6229
6230   if (EltVT == MVT::i8)
6231     return SDValue();
6232
6233   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6234     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6235     // as its second argument.
6236     if (N1.getValueType() != MVT::i32)
6237       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6238     if (N2.getValueType() != MVT::i32)
6239       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6240     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6241   }
6242   return SDValue();
6243 }
6244
6245 SDValue
6246 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6247   LLVMContext *Context = DAG.getContext();
6248   DebugLoc dl = Op.getDebugLoc();
6249   EVT OpVT = Op.getValueType();
6250
6251   // If this is a 256-bit vector result, first insert into a 128-bit
6252   // vector and then insert into the 256-bit vector.
6253   if (OpVT.getSizeInBits() > 128) {
6254     // Insert into a 128-bit vector.
6255     EVT VT128 = EVT::getVectorVT(*Context,
6256                                  OpVT.getVectorElementType(),
6257                                  OpVT.getVectorNumElements() / 2);
6258
6259     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6260
6261     // Insert the 128-bit vector.
6262     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6263                               DAG.getConstant(0, MVT::i32),
6264                               DAG, dl);
6265   }
6266
6267   if (Op.getValueType() == MVT::v1i64 &&
6268       Op.getOperand(0).getValueType() == MVT::i64)
6269     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6270
6271   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6272   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6273          "Expected an SSE type!");
6274   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6275                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6276 }
6277
6278 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6279 // a simple subregister reference or explicit instructions to grab
6280 // upper bits of a vector.
6281 SDValue
6282 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6283   if (Subtarget->hasAVX()) {
6284     DebugLoc dl = Op.getNode()->getDebugLoc();
6285     SDValue Vec = Op.getNode()->getOperand(0);
6286     SDValue Idx = Op.getNode()->getOperand(1);
6287
6288     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6289         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6290         return Extract128BitVector(Vec, Idx, DAG, dl);
6291     }
6292   }
6293   return SDValue();
6294 }
6295
6296 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6297 // simple superregister reference or explicit instructions to insert
6298 // the upper bits of a vector.
6299 SDValue
6300 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6301   if (Subtarget->hasAVX()) {
6302     DebugLoc dl = Op.getNode()->getDebugLoc();
6303     SDValue Vec = Op.getNode()->getOperand(0);
6304     SDValue SubVec = Op.getNode()->getOperand(1);
6305     SDValue Idx = Op.getNode()->getOperand(2);
6306
6307     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6308         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6309       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6310     }
6311   }
6312   return SDValue();
6313 }
6314
6315 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6316 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6317 // one of the above mentioned nodes. It has to be wrapped because otherwise
6318 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6319 // be used to form addressing mode. These wrapped nodes will be selected
6320 // into MOV32ri.
6321 SDValue
6322 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6323   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6324
6325   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6326   // global base reg.
6327   unsigned char OpFlag = 0;
6328   unsigned WrapperKind = X86ISD::Wrapper;
6329   CodeModel::Model M = getTargetMachine().getCodeModel();
6330
6331   if (Subtarget->isPICStyleRIPRel() &&
6332       (M == CodeModel::Small || M == CodeModel::Kernel))
6333     WrapperKind = X86ISD::WrapperRIP;
6334   else if (Subtarget->isPICStyleGOT())
6335     OpFlag = X86II::MO_GOTOFF;
6336   else if (Subtarget->isPICStyleStubPIC())
6337     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6338
6339   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6340                                              CP->getAlignment(),
6341                                              CP->getOffset(), OpFlag);
6342   DebugLoc DL = CP->getDebugLoc();
6343   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6344   // With PIC, the address is actually $g + Offset.
6345   if (OpFlag) {
6346     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6347                          DAG.getNode(X86ISD::GlobalBaseReg,
6348                                      DebugLoc(), getPointerTy()),
6349                          Result);
6350   }
6351
6352   return Result;
6353 }
6354
6355 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6356   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6357
6358   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6359   // global base reg.
6360   unsigned char OpFlag = 0;
6361   unsigned WrapperKind = X86ISD::Wrapper;
6362   CodeModel::Model M = getTargetMachine().getCodeModel();
6363
6364   if (Subtarget->isPICStyleRIPRel() &&
6365       (M == CodeModel::Small || M == CodeModel::Kernel))
6366     WrapperKind = X86ISD::WrapperRIP;
6367   else if (Subtarget->isPICStyleGOT())
6368     OpFlag = X86II::MO_GOTOFF;
6369   else if (Subtarget->isPICStyleStubPIC())
6370     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6371
6372   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6373                                           OpFlag);
6374   DebugLoc DL = JT->getDebugLoc();
6375   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6376
6377   // With PIC, the address is actually $g + Offset.
6378   if (OpFlag)
6379     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6380                          DAG.getNode(X86ISD::GlobalBaseReg,
6381                                      DebugLoc(), getPointerTy()),
6382                          Result);
6383
6384   return Result;
6385 }
6386
6387 SDValue
6388 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6389   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6390
6391   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6392   // global base reg.
6393   unsigned char OpFlag = 0;
6394   unsigned WrapperKind = X86ISD::Wrapper;
6395   CodeModel::Model M = getTargetMachine().getCodeModel();
6396
6397   if (Subtarget->isPICStyleRIPRel() &&
6398       (M == CodeModel::Small || M == CodeModel::Kernel))
6399     WrapperKind = X86ISD::WrapperRIP;
6400   else if (Subtarget->isPICStyleGOT())
6401     OpFlag = X86II::MO_GOTOFF;
6402   else if (Subtarget->isPICStyleStubPIC())
6403     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6404
6405   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6406
6407   DebugLoc DL = Op.getDebugLoc();
6408   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6409
6410
6411   // With PIC, the address is actually $g + Offset.
6412   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6413       !Subtarget->is64Bit()) {
6414     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6415                          DAG.getNode(X86ISD::GlobalBaseReg,
6416                                      DebugLoc(), getPointerTy()),
6417                          Result);
6418   }
6419
6420   return Result;
6421 }
6422
6423 SDValue
6424 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6425   // Create the TargetBlockAddressAddress node.
6426   unsigned char OpFlags =
6427     Subtarget->ClassifyBlockAddressReference();
6428   CodeModel::Model M = getTargetMachine().getCodeModel();
6429   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6430   DebugLoc dl = Op.getDebugLoc();
6431   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6432                                        /*isTarget=*/true, OpFlags);
6433
6434   if (Subtarget->isPICStyleRIPRel() &&
6435       (M == CodeModel::Small || M == CodeModel::Kernel))
6436     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6437   else
6438     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6439
6440   // With PIC, the address is actually $g + Offset.
6441   if (isGlobalRelativeToPICBase(OpFlags)) {
6442     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6443                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6444                          Result);
6445   }
6446
6447   return Result;
6448 }
6449
6450 SDValue
6451 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6452                                       int64_t Offset,
6453                                       SelectionDAG &DAG) const {
6454   // Create the TargetGlobalAddress node, folding in the constant
6455   // offset if it is legal.
6456   unsigned char OpFlags =
6457     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6458   CodeModel::Model M = getTargetMachine().getCodeModel();
6459   SDValue Result;
6460   if (OpFlags == X86II::MO_NO_FLAG &&
6461       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6462     // A direct static reference to a global.
6463     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6464     Offset = 0;
6465   } else {
6466     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6467   }
6468
6469   if (Subtarget->isPICStyleRIPRel() &&
6470       (M == CodeModel::Small || M == CodeModel::Kernel))
6471     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6472   else
6473     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6474
6475   // With PIC, the address is actually $g + Offset.
6476   if (isGlobalRelativeToPICBase(OpFlags)) {
6477     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6478                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6479                          Result);
6480   }
6481
6482   // For globals that require a load from a stub to get the address, emit the
6483   // load.
6484   if (isGlobalStubReference(OpFlags))
6485     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6486                          MachinePointerInfo::getGOT(), false, false, 0);
6487
6488   // If there was a non-zero offset that we didn't fold, create an explicit
6489   // addition for it.
6490   if (Offset != 0)
6491     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6492                          DAG.getConstant(Offset, getPointerTy()));
6493
6494   return Result;
6495 }
6496
6497 SDValue
6498 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6499   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6500   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6501   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6502 }
6503
6504 static SDValue
6505 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6506            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6507            unsigned char OperandFlags) {
6508   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6509   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6510   DebugLoc dl = GA->getDebugLoc();
6511   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6512                                            GA->getValueType(0),
6513                                            GA->getOffset(),
6514                                            OperandFlags);
6515   if (InFlag) {
6516     SDValue Ops[] = { Chain,  TGA, *InFlag };
6517     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6518   } else {
6519     SDValue Ops[]  = { Chain, TGA };
6520     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6521   }
6522
6523   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6524   MFI->setAdjustsStack(true);
6525
6526   SDValue Flag = Chain.getValue(1);
6527   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6528 }
6529
6530 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6531 static SDValue
6532 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6533                                 const EVT PtrVT) {
6534   SDValue InFlag;
6535   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6536   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6537                                      DAG.getNode(X86ISD::GlobalBaseReg,
6538                                                  DebugLoc(), PtrVT), InFlag);
6539   InFlag = Chain.getValue(1);
6540
6541   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6542 }
6543
6544 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6545 static SDValue
6546 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6547                                 const EVT PtrVT) {
6548   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6549                     X86::RAX, X86II::MO_TLSGD);
6550 }
6551
6552 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6553 // "local exec" model.
6554 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6555                                    const EVT PtrVT, TLSModel::Model model,
6556                                    bool is64Bit) {
6557   DebugLoc dl = GA->getDebugLoc();
6558
6559   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6560   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6561                                                          is64Bit ? 257 : 256));
6562
6563   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6564                                       DAG.getIntPtrConstant(0),
6565                                       MachinePointerInfo(Ptr), false, false, 0);
6566
6567   unsigned char OperandFlags = 0;
6568   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6569   // initialexec.
6570   unsigned WrapperKind = X86ISD::Wrapper;
6571   if (model == TLSModel::LocalExec) {
6572     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6573   } else if (is64Bit) {
6574     assert(model == TLSModel::InitialExec);
6575     OperandFlags = X86II::MO_GOTTPOFF;
6576     WrapperKind = X86ISD::WrapperRIP;
6577   } else {
6578     assert(model == TLSModel::InitialExec);
6579     OperandFlags = X86II::MO_INDNTPOFF;
6580   }
6581
6582   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6583   // exec)
6584   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6585                                            GA->getValueType(0),
6586                                            GA->getOffset(), OperandFlags);
6587   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6588
6589   if (model == TLSModel::InitialExec)
6590     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6591                          MachinePointerInfo::getGOT(), false, false, 0);
6592
6593   // The address of the thread local variable is the add of the thread
6594   // pointer with the offset of the variable.
6595   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6596 }
6597
6598 SDValue
6599 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6600
6601   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6602   const GlobalValue *GV = GA->getGlobal();
6603
6604   if (Subtarget->isTargetELF()) {
6605     // TODO: implement the "local dynamic" model
6606     // TODO: implement the "initial exec"model for pic executables
6607
6608     // If GV is an alias then use the aliasee for determining
6609     // thread-localness.
6610     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6611       GV = GA->resolveAliasedGlobal(false);
6612
6613     TLSModel::Model model
6614       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6615
6616     switch (model) {
6617       case TLSModel::GeneralDynamic:
6618       case TLSModel::LocalDynamic: // not implemented
6619         if (Subtarget->is64Bit())
6620           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6621         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6622
6623       case TLSModel::InitialExec:
6624       case TLSModel::LocalExec:
6625         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6626                                    Subtarget->is64Bit());
6627     }
6628   } else if (Subtarget->isTargetDarwin()) {
6629     // Darwin only has one model of TLS.  Lower to that.
6630     unsigned char OpFlag = 0;
6631     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6632                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6633
6634     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6635     // global base reg.
6636     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6637                   !Subtarget->is64Bit();
6638     if (PIC32)
6639       OpFlag = X86II::MO_TLVP_PIC_BASE;
6640     else
6641       OpFlag = X86II::MO_TLVP;
6642     DebugLoc DL = Op.getDebugLoc();
6643     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6644                                                 GA->getValueType(0),
6645                                                 GA->getOffset(), OpFlag);
6646     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6647
6648     // With PIC32, the address is actually $g + Offset.
6649     if (PIC32)
6650       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6651                            DAG.getNode(X86ISD::GlobalBaseReg,
6652                                        DebugLoc(), getPointerTy()),
6653                            Offset);
6654
6655     // Lowering the machine isd will make sure everything is in the right
6656     // location.
6657     SDValue Chain = DAG.getEntryNode();
6658     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6659     SDValue Args[] = { Chain, Offset };
6660     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6661
6662     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6663     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6664     MFI->setAdjustsStack(true);
6665
6666     // And our return value (tls address) is in the standard call return value
6667     // location.
6668     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6669     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6670   }
6671
6672   assert(false &&
6673          "TLS not implemented for this target.");
6674
6675   llvm_unreachable("Unreachable");
6676   return SDValue();
6677 }
6678
6679
6680 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6681 /// take a 2 x i32 value to shift plus a shift amount.
6682 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6683   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6684   EVT VT = Op.getValueType();
6685   unsigned VTBits = VT.getSizeInBits();
6686   DebugLoc dl = Op.getDebugLoc();
6687   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6688   SDValue ShOpLo = Op.getOperand(0);
6689   SDValue ShOpHi = Op.getOperand(1);
6690   SDValue ShAmt  = Op.getOperand(2);
6691   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6692                                      DAG.getConstant(VTBits - 1, MVT::i8))
6693                        : DAG.getConstant(0, VT);
6694
6695   SDValue Tmp2, Tmp3;
6696   if (Op.getOpcode() == ISD::SHL_PARTS) {
6697     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6698     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6699   } else {
6700     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6701     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6702   }
6703
6704   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6705                                 DAG.getConstant(VTBits, MVT::i8));
6706   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6707                              AndNode, DAG.getConstant(0, MVT::i8));
6708
6709   SDValue Hi, Lo;
6710   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6711   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6712   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6713
6714   if (Op.getOpcode() == ISD::SHL_PARTS) {
6715     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6716     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6717   } else {
6718     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6719     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6720   }
6721
6722   SDValue Ops[2] = { Lo, Hi };
6723   return DAG.getMergeValues(Ops, 2, dl);
6724 }
6725
6726 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6727                                            SelectionDAG &DAG) const {
6728   EVT SrcVT = Op.getOperand(0).getValueType();
6729
6730   if (SrcVT.isVector())
6731     return SDValue();
6732
6733   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6734          "Unknown SINT_TO_FP to lower!");
6735
6736   // These are really Legal; return the operand so the caller accepts it as
6737   // Legal.
6738   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6739     return Op;
6740   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6741       Subtarget->is64Bit()) {
6742     return Op;
6743   }
6744
6745   DebugLoc dl = Op.getDebugLoc();
6746   unsigned Size = SrcVT.getSizeInBits()/8;
6747   MachineFunction &MF = DAG.getMachineFunction();
6748   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6749   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6750   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6751                                StackSlot,
6752                                MachinePointerInfo::getFixedStack(SSFI),
6753                                false, false, 0);
6754   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6755 }
6756
6757 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6758                                      SDValue StackSlot,
6759                                      SelectionDAG &DAG) const {
6760   // Build the FILD
6761   DebugLoc DL = Op.getDebugLoc();
6762   SDVTList Tys;
6763   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6764   if (useSSE)
6765     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6766   else
6767     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6768
6769   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6770
6771   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6772   MachineMemOperand *MMO;
6773   if (FI) {
6774     int SSFI = FI->getIndex();
6775     MMO =
6776       DAG.getMachineFunction()
6777       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6778                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6779   } else {
6780     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6781     StackSlot = StackSlot.getOperand(1);
6782   }
6783   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6784   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6785                                            X86ISD::FILD, DL,
6786                                            Tys, Ops, array_lengthof(Ops),
6787                                            SrcVT, MMO);
6788
6789   if (useSSE) {
6790     Chain = Result.getValue(1);
6791     SDValue InFlag = Result.getValue(2);
6792
6793     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6794     // shouldn't be necessary except that RFP cannot be live across
6795     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6796     MachineFunction &MF = DAG.getMachineFunction();
6797     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6798     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6799     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6800     Tys = DAG.getVTList(MVT::Other);
6801     SDValue Ops[] = {
6802       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6803     };
6804     MachineMemOperand *MMO =
6805       DAG.getMachineFunction()
6806       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6807                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6808
6809     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6810                                     Ops, array_lengthof(Ops),
6811                                     Op.getValueType(), MMO);
6812     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6813                          MachinePointerInfo::getFixedStack(SSFI),
6814                          false, false, 0);
6815   }
6816
6817   return Result;
6818 }
6819
6820 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6821 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6822                                                SelectionDAG &DAG) const {
6823   // This algorithm is not obvious. Here it is in C code, more or less:
6824   /*
6825     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6826       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6827       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6828
6829       // Copy ints to xmm registers.
6830       __m128i xh = _mm_cvtsi32_si128( hi );
6831       __m128i xl = _mm_cvtsi32_si128( lo );
6832
6833       // Combine into low half of a single xmm register.
6834       __m128i x = _mm_unpacklo_epi32( xh, xl );
6835       __m128d d;
6836       double sd;
6837
6838       // Merge in appropriate exponents to give the integer bits the right
6839       // magnitude.
6840       x = _mm_unpacklo_epi32( x, exp );
6841
6842       // Subtract away the biases to deal with the IEEE-754 double precision
6843       // implicit 1.
6844       d = _mm_sub_pd( (__m128d) x, bias );
6845
6846       // All conversions up to here are exact. The correctly rounded result is
6847       // calculated using the current rounding mode using the following
6848       // horizontal add.
6849       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6850       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6851                                 // store doesn't really need to be here (except
6852                                 // maybe to zero the other double)
6853       return sd;
6854     }
6855   */
6856
6857   DebugLoc dl = Op.getDebugLoc();
6858   LLVMContext *Context = DAG.getContext();
6859
6860   // Build some magic constants.
6861   std::vector<Constant*> CV0;
6862   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6863   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6864   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6865   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6866   Constant *C0 = ConstantVector::get(CV0);
6867   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6868
6869   std::vector<Constant*> CV1;
6870   CV1.push_back(
6871     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6872   CV1.push_back(
6873     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6874   Constant *C1 = ConstantVector::get(CV1);
6875   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6876
6877   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6878                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6879                                         Op.getOperand(0),
6880                                         DAG.getIntPtrConstant(1)));
6881   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6882                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6883                                         Op.getOperand(0),
6884                                         DAG.getIntPtrConstant(0)));
6885   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6886   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6887                               MachinePointerInfo::getConstantPool(),
6888                               false, false, 16);
6889   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6890   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6891   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6892                               MachinePointerInfo::getConstantPool(),
6893                               false, false, 16);
6894   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6895
6896   // Add the halves; easiest way is to swap them into another reg first.
6897   int ShufMask[2] = { 1, -1 };
6898   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6899                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6900   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6901   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6902                      DAG.getIntPtrConstant(0));
6903 }
6904
6905 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6906 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6907                                                SelectionDAG &DAG) const {
6908   DebugLoc dl = Op.getDebugLoc();
6909   // FP constant to bias correct the final result.
6910   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6911                                    MVT::f64);
6912
6913   // Load the 32-bit value into an XMM register.
6914   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6915                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6916                                          Op.getOperand(0),
6917                                          DAG.getIntPtrConstant(0)));
6918
6919   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6920                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6921                      DAG.getIntPtrConstant(0));
6922
6923   // Or the load with the bias.
6924   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6925                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6926                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6927                                                    MVT::v2f64, Load)),
6928                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6929                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6930                                                    MVT::v2f64, Bias)));
6931   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6932                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6933                    DAG.getIntPtrConstant(0));
6934
6935   // Subtract the bias.
6936   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6937
6938   // Handle final rounding.
6939   EVT DestVT = Op.getValueType();
6940
6941   if (DestVT.bitsLT(MVT::f64)) {
6942     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6943                        DAG.getIntPtrConstant(0));
6944   } else if (DestVT.bitsGT(MVT::f64)) {
6945     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6946   }
6947
6948   // Handle final rounding.
6949   return Sub;
6950 }
6951
6952 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6953                                            SelectionDAG &DAG) const {
6954   SDValue N0 = Op.getOperand(0);
6955   DebugLoc dl = Op.getDebugLoc();
6956
6957   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6958   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6959   // the optimization here.
6960   if (DAG.SignBitIsZero(N0))
6961     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6962
6963   EVT SrcVT = N0.getValueType();
6964   EVT DstVT = Op.getValueType();
6965   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6966     return LowerUINT_TO_FP_i64(Op, DAG);
6967   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6968     return LowerUINT_TO_FP_i32(Op, DAG);
6969
6970   // Make a 64-bit buffer, and use it to build an FILD.
6971   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6972   if (SrcVT == MVT::i32) {
6973     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6974     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6975                                      getPointerTy(), StackSlot, WordOff);
6976     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6977                                   StackSlot, MachinePointerInfo(),
6978                                   false, false, 0);
6979     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6980                                   OffsetSlot, MachinePointerInfo(),
6981                                   false, false, 0);
6982     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6983     return Fild;
6984   }
6985
6986   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6987   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6988                                 StackSlot, MachinePointerInfo(),
6989                                false, false, 0);
6990   // For i64 source, we need to add the appropriate power of 2 if the input
6991   // was negative.  This is the same as the optimization in
6992   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6993   // we must be careful to do the computation in x87 extended precision, not
6994   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6995   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6996   MachineMemOperand *MMO =
6997     DAG.getMachineFunction()
6998     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6999                           MachineMemOperand::MOLoad, 8, 8);
7000
7001   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7002   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7003   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7004                                          MVT::i64, MMO);
7005
7006   APInt FF(32, 0x5F800000ULL);
7007
7008   // Check whether the sign bit is set.
7009   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7010                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7011                                  ISD::SETLT);
7012
7013   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7014   SDValue FudgePtr = DAG.getConstantPool(
7015                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7016                                          getPointerTy());
7017
7018   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7019   SDValue Zero = DAG.getIntPtrConstant(0);
7020   SDValue Four = DAG.getIntPtrConstant(4);
7021   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7022                                Zero, Four);
7023   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7024
7025   // Load the value out, extending it from f32 to f80.
7026   // FIXME: Avoid the extend by constructing the right constant pool?
7027   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7028                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7029                                  MVT::f32, false, false, 4);
7030   // Extend everything to 80 bits to force it to be done on x87.
7031   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7032   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7033 }
7034
7035 std::pair<SDValue,SDValue> X86TargetLowering::
7036 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7037   DebugLoc DL = Op.getDebugLoc();
7038
7039   EVT DstTy = Op.getValueType();
7040
7041   if (!IsSigned) {
7042     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7043     DstTy = MVT::i64;
7044   }
7045
7046   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7047          DstTy.getSimpleVT() >= MVT::i16 &&
7048          "Unknown FP_TO_SINT to lower!");
7049
7050   // These are really Legal.
7051   if (DstTy == MVT::i32 &&
7052       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7053     return std::make_pair(SDValue(), SDValue());
7054   if (Subtarget->is64Bit() &&
7055       DstTy == MVT::i64 &&
7056       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7057     return std::make_pair(SDValue(), SDValue());
7058
7059   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7060   // stack slot.
7061   MachineFunction &MF = DAG.getMachineFunction();
7062   unsigned MemSize = DstTy.getSizeInBits()/8;
7063   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7064   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7065
7066
7067
7068   unsigned Opc;
7069   switch (DstTy.getSimpleVT().SimpleTy) {
7070   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7071   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7072   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7073   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7074   }
7075
7076   SDValue Chain = DAG.getEntryNode();
7077   SDValue Value = Op.getOperand(0);
7078   EVT TheVT = Op.getOperand(0).getValueType();
7079   if (isScalarFPTypeInSSEReg(TheVT)) {
7080     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7081     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7082                          MachinePointerInfo::getFixedStack(SSFI),
7083                          false, false, 0);
7084     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7085     SDValue Ops[] = {
7086       Chain, StackSlot, DAG.getValueType(TheVT)
7087     };
7088
7089     MachineMemOperand *MMO =
7090       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7091                               MachineMemOperand::MOLoad, MemSize, MemSize);
7092     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7093                                     DstTy, MMO);
7094     Chain = Value.getValue(1);
7095     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7096     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7097   }
7098
7099   MachineMemOperand *MMO =
7100     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7101                             MachineMemOperand::MOStore, MemSize, MemSize);
7102
7103   // Build the FP_TO_INT*_IN_MEM
7104   SDValue Ops[] = { Chain, Value, StackSlot };
7105   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7106                                          Ops, 3, DstTy, MMO);
7107
7108   return std::make_pair(FIST, StackSlot);
7109 }
7110
7111 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7112                                            SelectionDAG &DAG) const {
7113   if (Op.getValueType().isVector())
7114     return SDValue();
7115
7116   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7117   SDValue FIST = Vals.first, StackSlot = Vals.second;
7118   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7119   if (FIST.getNode() == 0) return Op;
7120
7121   // Load the result.
7122   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7123                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7124 }
7125
7126 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7127                                            SelectionDAG &DAG) const {
7128   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7129   SDValue FIST = Vals.first, StackSlot = Vals.second;
7130   assert(FIST.getNode() && "Unexpected failure");
7131
7132   // Load the result.
7133   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7134                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7135 }
7136
7137 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7138                                      SelectionDAG &DAG) const {
7139   LLVMContext *Context = DAG.getContext();
7140   DebugLoc dl = Op.getDebugLoc();
7141   EVT VT = Op.getValueType();
7142   EVT EltVT = VT;
7143   if (VT.isVector())
7144     EltVT = VT.getVectorElementType();
7145   std::vector<Constant*> CV;
7146   if (EltVT == MVT::f64) {
7147     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7148     CV.push_back(C);
7149     CV.push_back(C);
7150   } else {
7151     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7152     CV.push_back(C);
7153     CV.push_back(C);
7154     CV.push_back(C);
7155     CV.push_back(C);
7156   }
7157   Constant *C = ConstantVector::get(CV);
7158   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7159   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7160                              MachinePointerInfo::getConstantPool(),
7161                              false, false, 16);
7162   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7163 }
7164
7165 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7166   LLVMContext *Context = DAG.getContext();
7167   DebugLoc dl = Op.getDebugLoc();
7168   EVT VT = Op.getValueType();
7169   EVT EltVT = VT;
7170   if (VT.isVector())
7171     EltVT = VT.getVectorElementType();
7172   std::vector<Constant*> CV;
7173   if (EltVT == MVT::f64) {
7174     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7175     CV.push_back(C);
7176     CV.push_back(C);
7177   } else {
7178     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7179     CV.push_back(C);
7180     CV.push_back(C);
7181     CV.push_back(C);
7182     CV.push_back(C);
7183   }
7184   Constant *C = ConstantVector::get(CV);
7185   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7186   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7187                              MachinePointerInfo::getConstantPool(),
7188                              false, false, 16);
7189   if (VT.isVector()) {
7190     return DAG.getNode(ISD::BITCAST, dl, VT,
7191                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7192                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7193                                 Op.getOperand(0)),
7194                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7195   } else {
7196     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7197   }
7198 }
7199
7200 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7201   LLVMContext *Context = DAG.getContext();
7202   SDValue Op0 = Op.getOperand(0);
7203   SDValue Op1 = Op.getOperand(1);
7204   DebugLoc dl = Op.getDebugLoc();
7205   EVT VT = Op.getValueType();
7206   EVT SrcVT = Op1.getValueType();
7207
7208   // If second operand is smaller, extend it first.
7209   if (SrcVT.bitsLT(VT)) {
7210     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7211     SrcVT = VT;
7212   }
7213   // And if it is bigger, shrink it first.
7214   if (SrcVT.bitsGT(VT)) {
7215     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7216     SrcVT = VT;
7217   }
7218
7219   // At this point the operands and the result should have the same
7220   // type, and that won't be f80 since that is not custom lowered.
7221
7222   // First get the sign bit of second operand.
7223   std::vector<Constant*> CV;
7224   if (SrcVT == MVT::f64) {
7225     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7226     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7227   } else {
7228     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7229     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7230     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7231     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7232   }
7233   Constant *C = ConstantVector::get(CV);
7234   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7235   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7236                               MachinePointerInfo::getConstantPool(),
7237                               false, false, 16);
7238   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7239
7240   // Shift sign bit right or left if the two operands have different types.
7241   if (SrcVT.bitsGT(VT)) {
7242     // Op0 is MVT::f32, Op1 is MVT::f64.
7243     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7244     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7245                           DAG.getConstant(32, MVT::i32));
7246     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7247     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7248                           DAG.getIntPtrConstant(0));
7249   }
7250
7251   // Clear first operand sign bit.
7252   CV.clear();
7253   if (VT == MVT::f64) {
7254     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7255     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7256   } else {
7257     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7258     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7259     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7260     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7261   }
7262   C = ConstantVector::get(CV);
7263   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7264   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7265                               MachinePointerInfo::getConstantPool(),
7266                               false, false, 16);
7267   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7268
7269   // Or the value with the sign bit.
7270   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7271 }
7272
7273 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7274   SDValue N0 = Op.getOperand(0);
7275   DebugLoc dl = Op.getDebugLoc();
7276   EVT VT = Op.getValueType();
7277
7278   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7279   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7280                                   DAG.getConstant(1, VT));
7281   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7282 }
7283
7284 /// Emit nodes that will be selected as "test Op0,Op0", or something
7285 /// equivalent.
7286 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7287                                     SelectionDAG &DAG) const {
7288   DebugLoc dl = Op.getDebugLoc();
7289
7290   // CF and OF aren't always set the way we want. Determine which
7291   // of these we need.
7292   bool NeedCF = false;
7293   bool NeedOF = false;
7294   switch (X86CC) {
7295   default: break;
7296   case X86::COND_A: case X86::COND_AE:
7297   case X86::COND_B: case X86::COND_BE:
7298     NeedCF = true;
7299     break;
7300   case X86::COND_G: case X86::COND_GE:
7301   case X86::COND_L: case X86::COND_LE:
7302   case X86::COND_O: case X86::COND_NO:
7303     NeedOF = true;
7304     break;
7305   }
7306
7307   // See if we can use the EFLAGS value from the operand instead of
7308   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7309   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7310   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7311     // Emit a CMP with 0, which is the TEST pattern.
7312     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7313                        DAG.getConstant(0, Op.getValueType()));
7314
7315   unsigned Opcode = 0;
7316   unsigned NumOperands = 0;
7317   switch (Op.getNode()->getOpcode()) {
7318   case ISD::ADD:
7319     // Due to an isel shortcoming, be conservative if this add is likely to be
7320     // selected as part of a load-modify-store instruction. When the root node
7321     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7322     // uses of other nodes in the match, such as the ADD in this case. This
7323     // leads to the ADD being left around and reselected, with the result being
7324     // two adds in the output.  Alas, even if none our users are stores, that
7325     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7326     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7327     // climbing the DAG back to the root, and it doesn't seem to be worth the
7328     // effort.
7329     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7330            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7331       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7332         goto default_case;
7333
7334     if (ConstantSDNode *C =
7335         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7336       // An add of one will be selected as an INC.
7337       if (C->getAPIntValue() == 1) {
7338         Opcode = X86ISD::INC;
7339         NumOperands = 1;
7340         break;
7341       }
7342
7343       // An add of negative one (subtract of one) will be selected as a DEC.
7344       if (C->getAPIntValue().isAllOnesValue()) {
7345         Opcode = X86ISD::DEC;
7346         NumOperands = 1;
7347         break;
7348       }
7349     }
7350
7351     // Otherwise use a regular EFLAGS-setting add.
7352     Opcode = X86ISD::ADD;
7353     NumOperands = 2;
7354     break;
7355   case ISD::AND: {
7356     // If the primary and result isn't used, don't bother using X86ISD::AND,
7357     // because a TEST instruction will be better.
7358     bool NonFlagUse = false;
7359     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7360            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7361       SDNode *User = *UI;
7362       unsigned UOpNo = UI.getOperandNo();
7363       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7364         // Look pass truncate.
7365         UOpNo = User->use_begin().getOperandNo();
7366         User = *User->use_begin();
7367       }
7368
7369       if (User->getOpcode() != ISD::BRCOND &&
7370           User->getOpcode() != ISD::SETCC &&
7371           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7372         NonFlagUse = true;
7373         break;
7374       }
7375     }
7376
7377     if (!NonFlagUse)
7378       break;
7379   }
7380     // FALL THROUGH
7381   case ISD::SUB:
7382   case ISD::OR:
7383   case ISD::XOR:
7384     // Due to the ISEL shortcoming noted above, be conservative if this op is
7385     // likely to be selected as part of a load-modify-store instruction.
7386     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7387            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7388       if (UI->getOpcode() == ISD::STORE)
7389         goto default_case;
7390
7391     // Otherwise use a regular EFLAGS-setting instruction.
7392     switch (Op.getNode()->getOpcode()) {
7393     default: llvm_unreachable("unexpected operator!");
7394     case ISD::SUB: Opcode = X86ISD::SUB; break;
7395     case ISD::OR:  Opcode = X86ISD::OR;  break;
7396     case ISD::XOR: Opcode = X86ISD::XOR; break;
7397     case ISD::AND: Opcode = X86ISD::AND; break;
7398     }
7399
7400     NumOperands = 2;
7401     break;
7402   case X86ISD::ADD:
7403   case X86ISD::SUB:
7404   case X86ISD::INC:
7405   case X86ISD::DEC:
7406   case X86ISD::OR:
7407   case X86ISD::XOR:
7408   case X86ISD::AND:
7409     return SDValue(Op.getNode(), 1);
7410   default:
7411   default_case:
7412     break;
7413   }
7414
7415   if (Opcode == 0)
7416     // Emit a CMP with 0, which is the TEST pattern.
7417     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7418                        DAG.getConstant(0, Op.getValueType()));
7419
7420   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7421   SmallVector<SDValue, 4> Ops;
7422   for (unsigned i = 0; i != NumOperands; ++i)
7423     Ops.push_back(Op.getOperand(i));
7424
7425   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7426   DAG.ReplaceAllUsesWith(Op, New);
7427   return SDValue(New.getNode(), 1);
7428 }
7429
7430 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7431 /// equivalent.
7432 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7433                                    SelectionDAG &DAG) const {
7434   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7435     if (C->getAPIntValue() == 0)
7436       return EmitTest(Op0, X86CC, DAG);
7437
7438   DebugLoc dl = Op0.getDebugLoc();
7439   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7440 }
7441
7442 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7443 /// if it's possible.
7444 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7445                                      DebugLoc dl, SelectionDAG &DAG) const {
7446   SDValue Op0 = And.getOperand(0);
7447   SDValue Op1 = And.getOperand(1);
7448   if (Op0.getOpcode() == ISD::TRUNCATE)
7449     Op0 = Op0.getOperand(0);
7450   if (Op1.getOpcode() == ISD::TRUNCATE)
7451     Op1 = Op1.getOperand(0);
7452
7453   SDValue LHS, RHS;
7454   if (Op1.getOpcode() == ISD::SHL)
7455     std::swap(Op0, Op1);
7456   if (Op0.getOpcode() == ISD::SHL) {
7457     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7458       if (And00C->getZExtValue() == 1) {
7459         // If we looked past a truncate, check that it's only truncating away
7460         // known zeros.
7461         unsigned BitWidth = Op0.getValueSizeInBits();
7462         unsigned AndBitWidth = And.getValueSizeInBits();
7463         if (BitWidth > AndBitWidth) {
7464           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7465           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7466           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7467             return SDValue();
7468         }
7469         LHS = Op1;
7470         RHS = Op0.getOperand(1);
7471       }
7472   } else if (Op1.getOpcode() == ISD::Constant) {
7473     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7474     SDValue AndLHS = Op0;
7475     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7476       LHS = AndLHS.getOperand(0);
7477       RHS = AndLHS.getOperand(1);
7478     }
7479   }
7480
7481   if (LHS.getNode()) {
7482     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7483     // instruction.  Since the shift amount is in-range-or-undefined, we know
7484     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7485     // the encoding for the i16 version is larger than the i32 version.
7486     // Also promote i16 to i32 for performance / code size reason.
7487     if (LHS.getValueType() == MVT::i8 ||
7488         LHS.getValueType() == MVT::i16)
7489       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7490
7491     // If the operand types disagree, extend the shift amount to match.  Since
7492     // BT ignores high bits (like shifts) we can use anyextend.
7493     if (LHS.getValueType() != RHS.getValueType())
7494       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7495
7496     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7497     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7498     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7499                        DAG.getConstant(Cond, MVT::i8), BT);
7500   }
7501
7502   return SDValue();
7503 }
7504
7505 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7506   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7507   SDValue Op0 = Op.getOperand(0);
7508   SDValue Op1 = Op.getOperand(1);
7509   DebugLoc dl = Op.getDebugLoc();
7510   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7511
7512   // Optimize to BT if possible.
7513   // Lower (X & (1 << N)) == 0 to BT(X, N).
7514   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7515   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7516   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7517       Op1.getOpcode() == ISD::Constant &&
7518       cast<ConstantSDNode>(Op1)->isNullValue() &&
7519       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7520     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7521     if (NewSetCC.getNode())
7522       return NewSetCC;
7523   }
7524
7525   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7526   // these.
7527   if (Op1.getOpcode() == ISD::Constant &&
7528       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7529        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7530       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7531
7532     // If the input is a setcc, then reuse the input setcc or use a new one with
7533     // the inverted condition.
7534     if (Op0.getOpcode() == X86ISD::SETCC) {
7535       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7536       bool Invert = (CC == ISD::SETNE) ^
7537         cast<ConstantSDNode>(Op1)->isNullValue();
7538       if (!Invert) return Op0;
7539
7540       CCode = X86::GetOppositeBranchCondition(CCode);
7541       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7542                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7543     }
7544   }
7545
7546   bool isFP = Op1.getValueType().isFloatingPoint();
7547   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7548   if (X86CC == X86::COND_INVALID)
7549     return SDValue();
7550
7551   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7552   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7553                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7554 }
7555
7556 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7557   SDValue Cond;
7558   SDValue Op0 = Op.getOperand(0);
7559   SDValue Op1 = Op.getOperand(1);
7560   SDValue CC = Op.getOperand(2);
7561   EVT VT = Op.getValueType();
7562   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7563   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7564   DebugLoc dl = Op.getDebugLoc();
7565
7566   if (isFP) {
7567     unsigned SSECC = 8;
7568     EVT VT0 = Op0.getValueType();
7569     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7570     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7571     bool Swap = false;
7572
7573     switch (SetCCOpcode) {
7574     default: break;
7575     case ISD::SETOEQ:
7576     case ISD::SETEQ:  SSECC = 0; break;
7577     case ISD::SETOGT:
7578     case ISD::SETGT: Swap = true; // Fallthrough
7579     case ISD::SETLT:
7580     case ISD::SETOLT: SSECC = 1; break;
7581     case ISD::SETOGE:
7582     case ISD::SETGE: Swap = true; // Fallthrough
7583     case ISD::SETLE:
7584     case ISD::SETOLE: SSECC = 2; break;
7585     case ISD::SETUO:  SSECC = 3; break;
7586     case ISD::SETUNE:
7587     case ISD::SETNE:  SSECC = 4; break;
7588     case ISD::SETULE: Swap = true;
7589     case ISD::SETUGE: SSECC = 5; break;
7590     case ISD::SETULT: Swap = true;
7591     case ISD::SETUGT: SSECC = 6; break;
7592     case ISD::SETO:   SSECC = 7; break;
7593     }
7594     if (Swap)
7595       std::swap(Op0, Op1);
7596
7597     // In the two special cases we can't handle, emit two comparisons.
7598     if (SSECC == 8) {
7599       if (SetCCOpcode == ISD::SETUEQ) {
7600         SDValue UNORD, EQ;
7601         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7602         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7603         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7604       }
7605       else if (SetCCOpcode == ISD::SETONE) {
7606         SDValue ORD, NEQ;
7607         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7608         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7609         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7610       }
7611       llvm_unreachable("Illegal FP comparison");
7612     }
7613     // Handle all other FP comparisons here.
7614     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7615   }
7616
7617   // We are handling one of the integer comparisons here.  Since SSE only has
7618   // GT and EQ comparisons for integer, swapping operands and multiple
7619   // operations may be required for some comparisons.
7620   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7621   bool Swap = false, Invert = false, FlipSigns = false;
7622
7623   switch (VT.getSimpleVT().SimpleTy) {
7624   default: break;
7625   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7626   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7627   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7628   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7629   }
7630
7631   switch (SetCCOpcode) {
7632   default: break;
7633   case ISD::SETNE:  Invert = true;
7634   case ISD::SETEQ:  Opc = EQOpc; break;
7635   case ISD::SETLT:  Swap = true;
7636   case ISD::SETGT:  Opc = GTOpc; break;
7637   case ISD::SETGE:  Swap = true;
7638   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7639   case ISD::SETULT: Swap = true;
7640   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7641   case ISD::SETUGE: Swap = true;
7642   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7643   }
7644   if (Swap)
7645     std::swap(Op0, Op1);
7646
7647   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7648   // bits of the inputs before performing those operations.
7649   if (FlipSigns) {
7650     EVT EltVT = VT.getVectorElementType();
7651     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7652                                       EltVT);
7653     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7654     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7655                                     SignBits.size());
7656     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7657     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7658   }
7659
7660   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7661
7662   // If the logical-not of the result is required, perform that now.
7663   if (Invert)
7664     Result = DAG.getNOT(dl, Result, VT);
7665
7666   return Result;
7667 }
7668
7669 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7670 static bool isX86LogicalCmp(SDValue Op) {
7671   unsigned Opc = Op.getNode()->getOpcode();
7672   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7673     return true;
7674   if (Op.getResNo() == 1 &&
7675       (Opc == X86ISD::ADD ||
7676        Opc == X86ISD::SUB ||
7677        Opc == X86ISD::ADC ||
7678        Opc == X86ISD::SBB ||
7679        Opc == X86ISD::SMUL ||
7680        Opc == X86ISD::UMUL ||
7681        Opc == X86ISD::INC ||
7682        Opc == X86ISD::DEC ||
7683        Opc == X86ISD::OR ||
7684        Opc == X86ISD::XOR ||
7685        Opc == X86ISD::AND))
7686     return true;
7687
7688   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7689     return true;
7690
7691   return false;
7692 }
7693
7694 static bool isZero(SDValue V) {
7695   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7696   return C && C->isNullValue();
7697 }
7698
7699 static bool isAllOnes(SDValue V) {
7700   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7701   return C && C->isAllOnesValue();
7702 }
7703
7704 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7705   bool addTest = true;
7706   SDValue Cond  = Op.getOperand(0);
7707   SDValue Op1 = Op.getOperand(1);
7708   SDValue Op2 = Op.getOperand(2);
7709   DebugLoc DL = Op.getDebugLoc();
7710   SDValue CC;
7711
7712   if (Cond.getOpcode() == ISD::SETCC) {
7713     SDValue NewCond = LowerSETCC(Cond, DAG);
7714     if (NewCond.getNode())
7715       Cond = NewCond;
7716   }
7717
7718   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7719   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7720   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7721   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7722   if (Cond.getOpcode() == X86ISD::SETCC &&
7723       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7724       isZero(Cond.getOperand(1).getOperand(1))) {
7725     SDValue Cmp = Cond.getOperand(1);
7726
7727     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7728
7729     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7730         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7731       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7732
7733       SDValue CmpOp0 = Cmp.getOperand(0);
7734       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7735                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7736
7737       SDValue Res =   // Res = 0 or -1.
7738         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7739                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7740
7741       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7742         Res = DAG.getNOT(DL, Res, Res.getValueType());
7743
7744       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7745       if (N2C == 0 || !N2C->isNullValue())
7746         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7747       return Res;
7748     }
7749   }
7750
7751   // Look past (and (setcc_carry (cmp ...)), 1).
7752   if (Cond.getOpcode() == ISD::AND &&
7753       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7754     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7755     if (C && C->getAPIntValue() == 1)
7756       Cond = Cond.getOperand(0);
7757   }
7758
7759   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7760   // setting operand in place of the X86ISD::SETCC.
7761   if (Cond.getOpcode() == X86ISD::SETCC ||
7762       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7763     CC = Cond.getOperand(0);
7764
7765     SDValue Cmp = Cond.getOperand(1);
7766     unsigned Opc = Cmp.getOpcode();
7767     EVT VT = Op.getValueType();
7768
7769     bool IllegalFPCMov = false;
7770     if (VT.isFloatingPoint() && !VT.isVector() &&
7771         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7772       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7773
7774     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7775         Opc == X86ISD::BT) { // FIXME
7776       Cond = Cmp;
7777       addTest = false;
7778     }
7779   }
7780
7781   if (addTest) {
7782     // Look pass the truncate.
7783     if (Cond.getOpcode() == ISD::TRUNCATE)
7784       Cond = Cond.getOperand(0);
7785
7786     // We know the result of AND is compared against zero. Try to match
7787     // it to BT.
7788     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7789       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7790       if (NewSetCC.getNode()) {
7791         CC = NewSetCC.getOperand(0);
7792         Cond = NewSetCC.getOperand(1);
7793         addTest = false;
7794       }
7795     }
7796   }
7797
7798   if (addTest) {
7799     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7800     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7801   }
7802
7803   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7804   // a <  b ?  0 : -1 -> RES = setcc_carry
7805   // a >= b ? -1 :  0 -> RES = setcc_carry
7806   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7807   if (Cond.getOpcode() == X86ISD::CMP) {
7808     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7809
7810     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7811         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7812       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7813                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7814       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7815         return DAG.getNOT(DL, Res, Res.getValueType());
7816       return Res;
7817     }
7818   }
7819
7820   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7821   // condition is true.
7822   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7823   SDValue Ops[] = { Op2, Op1, CC, Cond };
7824   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7825 }
7826
7827 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7828 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7829 // from the AND / OR.
7830 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7831   Opc = Op.getOpcode();
7832   if (Opc != ISD::OR && Opc != ISD::AND)
7833     return false;
7834   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7835           Op.getOperand(0).hasOneUse() &&
7836           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7837           Op.getOperand(1).hasOneUse());
7838 }
7839
7840 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7841 // 1 and that the SETCC node has a single use.
7842 static bool isXor1OfSetCC(SDValue Op) {
7843   if (Op.getOpcode() != ISD::XOR)
7844     return false;
7845   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7846   if (N1C && N1C->getAPIntValue() == 1) {
7847     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7848       Op.getOperand(0).hasOneUse();
7849   }
7850   return false;
7851 }
7852
7853 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7854   bool addTest = true;
7855   SDValue Chain = Op.getOperand(0);
7856   SDValue Cond  = Op.getOperand(1);
7857   SDValue Dest  = Op.getOperand(2);
7858   DebugLoc dl = Op.getDebugLoc();
7859   SDValue CC;
7860
7861   if (Cond.getOpcode() == ISD::SETCC) {
7862     SDValue NewCond = LowerSETCC(Cond, DAG);
7863     if (NewCond.getNode())
7864       Cond = NewCond;
7865   }
7866 #if 0
7867   // FIXME: LowerXALUO doesn't handle these!!
7868   else if (Cond.getOpcode() == X86ISD::ADD  ||
7869            Cond.getOpcode() == X86ISD::SUB  ||
7870            Cond.getOpcode() == X86ISD::SMUL ||
7871            Cond.getOpcode() == X86ISD::UMUL)
7872     Cond = LowerXALUO(Cond, DAG);
7873 #endif
7874
7875   // Look pass (and (setcc_carry (cmp ...)), 1).
7876   if (Cond.getOpcode() == ISD::AND &&
7877       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7878     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7879     if (C && C->getAPIntValue() == 1)
7880       Cond = Cond.getOperand(0);
7881   }
7882
7883   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7884   // setting operand in place of the X86ISD::SETCC.
7885   if (Cond.getOpcode() == X86ISD::SETCC ||
7886       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7887     CC = Cond.getOperand(0);
7888
7889     SDValue Cmp = Cond.getOperand(1);
7890     unsigned Opc = Cmp.getOpcode();
7891     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7892     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7893       Cond = Cmp;
7894       addTest = false;
7895     } else {
7896       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7897       default: break;
7898       case X86::COND_O:
7899       case X86::COND_B:
7900         // These can only come from an arithmetic instruction with overflow,
7901         // e.g. SADDO, UADDO.
7902         Cond = Cond.getNode()->getOperand(1);
7903         addTest = false;
7904         break;
7905       }
7906     }
7907   } else {
7908     unsigned CondOpc;
7909     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7910       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7911       if (CondOpc == ISD::OR) {
7912         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7913         // two branches instead of an explicit OR instruction with a
7914         // separate test.
7915         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7916             isX86LogicalCmp(Cmp)) {
7917           CC = Cond.getOperand(0).getOperand(0);
7918           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7919                               Chain, Dest, CC, Cmp);
7920           CC = Cond.getOperand(1).getOperand(0);
7921           Cond = Cmp;
7922           addTest = false;
7923         }
7924       } else { // ISD::AND
7925         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7926         // two branches instead of an explicit AND instruction with a
7927         // separate test. However, we only do this if this block doesn't
7928         // have a fall-through edge, because this requires an explicit
7929         // jmp when the condition is false.
7930         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7931             isX86LogicalCmp(Cmp) &&
7932             Op.getNode()->hasOneUse()) {
7933           X86::CondCode CCode =
7934             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7935           CCode = X86::GetOppositeBranchCondition(CCode);
7936           CC = DAG.getConstant(CCode, MVT::i8);
7937           SDNode *User = *Op.getNode()->use_begin();
7938           // Look for an unconditional branch following this conditional branch.
7939           // We need this because we need to reverse the successors in order
7940           // to implement FCMP_OEQ.
7941           if (User->getOpcode() == ISD::BR) {
7942             SDValue FalseBB = User->getOperand(1);
7943             SDNode *NewBR =
7944               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7945             assert(NewBR == User);
7946             (void)NewBR;
7947             Dest = FalseBB;
7948
7949             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7950                                 Chain, Dest, CC, Cmp);
7951             X86::CondCode CCode =
7952               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7953             CCode = X86::GetOppositeBranchCondition(CCode);
7954             CC = DAG.getConstant(CCode, MVT::i8);
7955             Cond = Cmp;
7956             addTest = false;
7957           }
7958         }
7959       }
7960     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7961       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7962       // It should be transformed during dag combiner except when the condition
7963       // is set by a arithmetics with overflow node.
7964       X86::CondCode CCode =
7965         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7966       CCode = X86::GetOppositeBranchCondition(CCode);
7967       CC = DAG.getConstant(CCode, MVT::i8);
7968       Cond = Cond.getOperand(0).getOperand(1);
7969       addTest = false;
7970     }
7971   }
7972
7973   if (addTest) {
7974     // Look pass the truncate.
7975     if (Cond.getOpcode() == ISD::TRUNCATE)
7976       Cond = Cond.getOperand(0);
7977
7978     // We know the result of AND is compared against zero. Try to match
7979     // it to BT.
7980     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7981       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7982       if (NewSetCC.getNode()) {
7983         CC = NewSetCC.getOperand(0);
7984         Cond = NewSetCC.getOperand(1);
7985         addTest = false;
7986       }
7987     }
7988   }
7989
7990   if (addTest) {
7991     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7992     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7993   }
7994   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7995                      Chain, Dest, CC, Cond);
7996 }
7997
7998
7999 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8000 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8001 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8002 // that the guard pages used by the OS virtual memory manager are allocated in
8003 // correct sequence.
8004 SDValue
8005 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8006                                            SelectionDAG &DAG) const {
8007   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8008          "This should be used only on Windows targets");
8009   assert(!Subtarget->isTargetEnvMacho());
8010   DebugLoc dl = Op.getDebugLoc();
8011
8012   // Get the inputs.
8013   SDValue Chain = Op.getOperand(0);
8014   SDValue Size  = Op.getOperand(1);
8015   // FIXME: Ensure alignment here
8016
8017   SDValue Flag;
8018
8019   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8020   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8021
8022   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8023   Flag = Chain.getValue(1);
8024
8025   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8026
8027   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8028   Flag = Chain.getValue(1);
8029
8030   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8031
8032   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8033   return DAG.getMergeValues(Ops1, 2, dl);
8034 }
8035
8036 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8037   MachineFunction &MF = DAG.getMachineFunction();
8038   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8039
8040   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8041   DebugLoc DL = Op.getDebugLoc();
8042
8043   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8044     // vastart just stores the address of the VarArgsFrameIndex slot into the
8045     // memory location argument.
8046     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8047                                    getPointerTy());
8048     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8049                         MachinePointerInfo(SV), false, false, 0);
8050   }
8051
8052   // __va_list_tag:
8053   //   gp_offset         (0 - 6 * 8)
8054   //   fp_offset         (48 - 48 + 8 * 16)
8055   //   overflow_arg_area (point to parameters coming in memory).
8056   //   reg_save_area
8057   SmallVector<SDValue, 8> MemOps;
8058   SDValue FIN = Op.getOperand(1);
8059   // Store gp_offset
8060   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8061                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8062                                                MVT::i32),
8063                                FIN, MachinePointerInfo(SV), false, false, 0);
8064   MemOps.push_back(Store);
8065
8066   // Store fp_offset
8067   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8068                     FIN, DAG.getIntPtrConstant(4));
8069   Store = DAG.getStore(Op.getOperand(0), DL,
8070                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8071                                        MVT::i32),
8072                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8073   MemOps.push_back(Store);
8074
8075   // Store ptr to overflow_arg_area
8076   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8077                     FIN, DAG.getIntPtrConstant(4));
8078   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8079                                     getPointerTy());
8080   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8081                        MachinePointerInfo(SV, 8),
8082                        false, false, 0);
8083   MemOps.push_back(Store);
8084
8085   // Store ptr to reg_save_area.
8086   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8087                     FIN, DAG.getIntPtrConstant(8));
8088   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8089                                     getPointerTy());
8090   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8091                        MachinePointerInfo(SV, 16), false, false, 0);
8092   MemOps.push_back(Store);
8093   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8094                      &MemOps[0], MemOps.size());
8095 }
8096
8097 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8098   assert(Subtarget->is64Bit() &&
8099          "LowerVAARG only handles 64-bit va_arg!");
8100   assert((Subtarget->isTargetLinux() ||
8101           Subtarget->isTargetDarwin()) &&
8102           "Unhandled target in LowerVAARG");
8103   assert(Op.getNode()->getNumOperands() == 4);
8104   SDValue Chain = Op.getOperand(0);
8105   SDValue SrcPtr = Op.getOperand(1);
8106   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8107   unsigned Align = Op.getConstantOperandVal(3);
8108   DebugLoc dl = Op.getDebugLoc();
8109
8110   EVT ArgVT = Op.getNode()->getValueType(0);
8111   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8112   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8113   uint8_t ArgMode;
8114
8115   // Decide which area this value should be read from.
8116   // TODO: Implement the AMD64 ABI in its entirety. This simple
8117   // selection mechanism works only for the basic types.
8118   if (ArgVT == MVT::f80) {
8119     llvm_unreachable("va_arg for f80 not yet implemented");
8120   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8121     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8122   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8123     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8124   } else {
8125     llvm_unreachable("Unhandled argument type in LowerVAARG");
8126   }
8127
8128   if (ArgMode == 2) {
8129     // Sanity Check: Make sure using fp_offset makes sense.
8130     assert(!UseSoftFloat &&
8131            !(DAG.getMachineFunction()
8132                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8133            Subtarget->hasXMM());
8134   }
8135
8136   // Insert VAARG_64 node into the DAG
8137   // VAARG_64 returns two values: Variable Argument Address, Chain
8138   SmallVector<SDValue, 11> InstOps;
8139   InstOps.push_back(Chain);
8140   InstOps.push_back(SrcPtr);
8141   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8142   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8143   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8144   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8145   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8146                                           VTs, &InstOps[0], InstOps.size(),
8147                                           MVT::i64,
8148                                           MachinePointerInfo(SV),
8149                                           /*Align=*/0,
8150                                           /*Volatile=*/false,
8151                                           /*ReadMem=*/true,
8152                                           /*WriteMem=*/true);
8153   Chain = VAARG.getValue(1);
8154
8155   // Load the next argument and return it
8156   return DAG.getLoad(ArgVT, dl,
8157                      Chain,
8158                      VAARG,
8159                      MachinePointerInfo(),
8160                      false, false, 0);
8161 }
8162
8163 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8164   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8165   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8166   SDValue Chain = Op.getOperand(0);
8167   SDValue DstPtr = Op.getOperand(1);
8168   SDValue SrcPtr = Op.getOperand(2);
8169   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8170   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8171   DebugLoc DL = Op.getDebugLoc();
8172
8173   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8174                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8175                        false,
8176                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8177 }
8178
8179 SDValue
8180 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8181   DebugLoc dl = Op.getDebugLoc();
8182   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8183   switch (IntNo) {
8184   default: return SDValue();    // Don't custom lower most intrinsics.
8185   // Comparison intrinsics.
8186   case Intrinsic::x86_sse_comieq_ss:
8187   case Intrinsic::x86_sse_comilt_ss:
8188   case Intrinsic::x86_sse_comile_ss:
8189   case Intrinsic::x86_sse_comigt_ss:
8190   case Intrinsic::x86_sse_comige_ss:
8191   case Intrinsic::x86_sse_comineq_ss:
8192   case Intrinsic::x86_sse_ucomieq_ss:
8193   case Intrinsic::x86_sse_ucomilt_ss:
8194   case Intrinsic::x86_sse_ucomile_ss:
8195   case Intrinsic::x86_sse_ucomigt_ss:
8196   case Intrinsic::x86_sse_ucomige_ss:
8197   case Intrinsic::x86_sse_ucomineq_ss:
8198   case Intrinsic::x86_sse2_comieq_sd:
8199   case Intrinsic::x86_sse2_comilt_sd:
8200   case Intrinsic::x86_sse2_comile_sd:
8201   case Intrinsic::x86_sse2_comigt_sd:
8202   case Intrinsic::x86_sse2_comige_sd:
8203   case Intrinsic::x86_sse2_comineq_sd:
8204   case Intrinsic::x86_sse2_ucomieq_sd:
8205   case Intrinsic::x86_sse2_ucomilt_sd:
8206   case Intrinsic::x86_sse2_ucomile_sd:
8207   case Intrinsic::x86_sse2_ucomigt_sd:
8208   case Intrinsic::x86_sse2_ucomige_sd:
8209   case Intrinsic::x86_sse2_ucomineq_sd: {
8210     unsigned Opc = 0;
8211     ISD::CondCode CC = ISD::SETCC_INVALID;
8212     switch (IntNo) {
8213     default: break;
8214     case Intrinsic::x86_sse_comieq_ss:
8215     case Intrinsic::x86_sse2_comieq_sd:
8216       Opc = X86ISD::COMI;
8217       CC = ISD::SETEQ;
8218       break;
8219     case Intrinsic::x86_sse_comilt_ss:
8220     case Intrinsic::x86_sse2_comilt_sd:
8221       Opc = X86ISD::COMI;
8222       CC = ISD::SETLT;
8223       break;
8224     case Intrinsic::x86_sse_comile_ss:
8225     case Intrinsic::x86_sse2_comile_sd:
8226       Opc = X86ISD::COMI;
8227       CC = ISD::SETLE;
8228       break;
8229     case Intrinsic::x86_sse_comigt_ss:
8230     case Intrinsic::x86_sse2_comigt_sd:
8231       Opc = X86ISD::COMI;
8232       CC = ISD::SETGT;
8233       break;
8234     case Intrinsic::x86_sse_comige_ss:
8235     case Intrinsic::x86_sse2_comige_sd:
8236       Opc = X86ISD::COMI;
8237       CC = ISD::SETGE;
8238       break;
8239     case Intrinsic::x86_sse_comineq_ss:
8240     case Intrinsic::x86_sse2_comineq_sd:
8241       Opc = X86ISD::COMI;
8242       CC = ISD::SETNE;
8243       break;
8244     case Intrinsic::x86_sse_ucomieq_ss:
8245     case Intrinsic::x86_sse2_ucomieq_sd:
8246       Opc = X86ISD::UCOMI;
8247       CC = ISD::SETEQ;
8248       break;
8249     case Intrinsic::x86_sse_ucomilt_ss:
8250     case Intrinsic::x86_sse2_ucomilt_sd:
8251       Opc = X86ISD::UCOMI;
8252       CC = ISD::SETLT;
8253       break;
8254     case Intrinsic::x86_sse_ucomile_ss:
8255     case Intrinsic::x86_sse2_ucomile_sd:
8256       Opc = X86ISD::UCOMI;
8257       CC = ISD::SETLE;
8258       break;
8259     case Intrinsic::x86_sse_ucomigt_ss:
8260     case Intrinsic::x86_sse2_ucomigt_sd:
8261       Opc = X86ISD::UCOMI;
8262       CC = ISD::SETGT;
8263       break;
8264     case Intrinsic::x86_sse_ucomige_ss:
8265     case Intrinsic::x86_sse2_ucomige_sd:
8266       Opc = X86ISD::UCOMI;
8267       CC = ISD::SETGE;
8268       break;
8269     case Intrinsic::x86_sse_ucomineq_ss:
8270     case Intrinsic::x86_sse2_ucomineq_sd:
8271       Opc = X86ISD::UCOMI;
8272       CC = ISD::SETNE;
8273       break;
8274     }
8275
8276     SDValue LHS = Op.getOperand(1);
8277     SDValue RHS = Op.getOperand(2);
8278     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8279     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8280     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8281     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8282                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8283     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8284   }
8285   // ptest and testp intrinsics. The intrinsic these come from are designed to
8286   // return an integer value, not just an instruction so lower it to the ptest
8287   // or testp pattern and a setcc for the result.
8288   case Intrinsic::x86_sse41_ptestz:
8289   case Intrinsic::x86_sse41_ptestc:
8290   case Intrinsic::x86_sse41_ptestnzc:
8291   case Intrinsic::x86_avx_ptestz_256:
8292   case Intrinsic::x86_avx_ptestc_256:
8293   case Intrinsic::x86_avx_ptestnzc_256:
8294   case Intrinsic::x86_avx_vtestz_ps:
8295   case Intrinsic::x86_avx_vtestc_ps:
8296   case Intrinsic::x86_avx_vtestnzc_ps:
8297   case Intrinsic::x86_avx_vtestz_pd:
8298   case Intrinsic::x86_avx_vtestc_pd:
8299   case Intrinsic::x86_avx_vtestnzc_pd:
8300   case Intrinsic::x86_avx_vtestz_ps_256:
8301   case Intrinsic::x86_avx_vtestc_ps_256:
8302   case Intrinsic::x86_avx_vtestnzc_ps_256:
8303   case Intrinsic::x86_avx_vtestz_pd_256:
8304   case Intrinsic::x86_avx_vtestc_pd_256:
8305   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8306     bool IsTestPacked = false;
8307     unsigned X86CC = 0;
8308     switch (IntNo) {
8309     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8310     case Intrinsic::x86_avx_vtestz_ps:
8311     case Intrinsic::x86_avx_vtestz_pd:
8312     case Intrinsic::x86_avx_vtestz_ps_256:
8313     case Intrinsic::x86_avx_vtestz_pd_256:
8314       IsTestPacked = true; // Fallthrough
8315     case Intrinsic::x86_sse41_ptestz:
8316     case Intrinsic::x86_avx_ptestz_256:
8317       // ZF = 1
8318       X86CC = X86::COND_E;
8319       break;
8320     case Intrinsic::x86_avx_vtestc_ps:
8321     case Intrinsic::x86_avx_vtestc_pd:
8322     case Intrinsic::x86_avx_vtestc_ps_256:
8323     case Intrinsic::x86_avx_vtestc_pd_256:
8324       IsTestPacked = true; // Fallthrough
8325     case Intrinsic::x86_sse41_ptestc:
8326     case Intrinsic::x86_avx_ptestc_256:
8327       // CF = 1
8328       X86CC = X86::COND_B;
8329       break;
8330     case Intrinsic::x86_avx_vtestnzc_ps:
8331     case Intrinsic::x86_avx_vtestnzc_pd:
8332     case Intrinsic::x86_avx_vtestnzc_ps_256:
8333     case Intrinsic::x86_avx_vtestnzc_pd_256:
8334       IsTestPacked = true; // Fallthrough
8335     case Intrinsic::x86_sse41_ptestnzc:
8336     case Intrinsic::x86_avx_ptestnzc_256:
8337       // ZF and CF = 0
8338       X86CC = X86::COND_A;
8339       break;
8340     }
8341
8342     SDValue LHS = Op.getOperand(1);
8343     SDValue RHS = Op.getOperand(2);
8344     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8345     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8346     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8347     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8348     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8349   }
8350
8351   // Fix vector shift instructions where the last operand is a non-immediate
8352   // i32 value.
8353   case Intrinsic::x86_sse2_pslli_w:
8354   case Intrinsic::x86_sse2_pslli_d:
8355   case Intrinsic::x86_sse2_pslli_q:
8356   case Intrinsic::x86_sse2_psrli_w:
8357   case Intrinsic::x86_sse2_psrli_d:
8358   case Intrinsic::x86_sse2_psrli_q:
8359   case Intrinsic::x86_sse2_psrai_w:
8360   case Intrinsic::x86_sse2_psrai_d:
8361   case Intrinsic::x86_mmx_pslli_w:
8362   case Intrinsic::x86_mmx_pslli_d:
8363   case Intrinsic::x86_mmx_pslli_q:
8364   case Intrinsic::x86_mmx_psrli_w:
8365   case Intrinsic::x86_mmx_psrli_d:
8366   case Intrinsic::x86_mmx_psrli_q:
8367   case Intrinsic::x86_mmx_psrai_w:
8368   case Intrinsic::x86_mmx_psrai_d: {
8369     SDValue ShAmt = Op.getOperand(2);
8370     if (isa<ConstantSDNode>(ShAmt))
8371       return SDValue();
8372
8373     unsigned NewIntNo = 0;
8374     EVT ShAmtVT = MVT::v4i32;
8375     switch (IntNo) {
8376     case Intrinsic::x86_sse2_pslli_w:
8377       NewIntNo = Intrinsic::x86_sse2_psll_w;
8378       break;
8379     case Intrinsic::x86_sse2_pslli_d:
8380       NewIntNo = Intrinsic::x86_sse2_psll_d;
8381       break;
8382     case Intrinsic::x86_sse2_pslli_q:
8383       NewIntNo = Intrinsic::x86_sse2_psll_q;
8384       break;
8385     case Intrinsic::x86_sse2_psrli_w:
8386       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8387       break;
8388     case Intrinsic::x86_sse2_psrli_d:
8389       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8390       break;
8391     case Intrinsic::x86_sse2_psrli_q:
8392       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8393       break;
8394     case Intrinsic::x86_sse2_psrai_w:
8395       NewIntNo = Intrinsic::x86_sse2_psra_w;
8396       break;
8397     case Intrinsic::x86_sse2_psrai_d:
8398       NewIntNo = Intrinsic::x86_sse2_psra_d;
8399       break;
8400     default: {
8401       ShAmtVT = MVT::v2i32;
8402       switch (IntNo) {
8403       case Intrinsic::x86_mmx_pslli_w:
8404         NewIntNo = Intrinsic::x86_mmx_psll_w;
8405         break;
8406       case Intrinsic::x86_mmx_pslli_d:
8407         NewIntNo = Intrinsic::x86_mmx_psll_d;
8408         break;
8409       case Intrinsic::x86_mmx_pslli_q:
8410         NewIntNo = Intrinsic::x86_mmx_psll_q;
8411         break;
8412       case Intrinsic::x86_mmx_psrli_w:
8413         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8414         break;
8415       case Intrinsic::x86_mmx_psrli_d:
8416         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8417         break;
8418       case Intrinsic::x86_mmx_psrli_q:
8419         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8420         break;
8421       case Intrinsic::x86_mmx_psrai_w:
8422         NewIntNo = Intrinsic::x86_mmx_psra_w;
8423         break;
8424       case Intrinsic::x86_mmx_psrai_d:
8425         NewIntNo = Intrinsic::x86_mmx_psra_d;
8426         break;
8427       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8428       }
8429       break;
8430     }
8431     }
8432
8433     // The vector shift intrinsics with scalars uses 32b shift amounts but
8434     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8435     // to be zero.
8436     SDValue ShOps[4];
8437     ShOps[0] = ShAmt;
8438     ShOps[1] = DAG.getConstant(0, MVT::i32);
8439     if (ShAmtVT == MVT::v4i32) {
8440       ShOps[2] = DAG.getUNDEF(MVT::i32);
8441       ShOps[3] = DAG.getUNDEF(MVT::i32);
8442       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8443     } else {
8444       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8445 // FIXME this must be lowered to get rid of the invalid type.
8446     }
8447
8448     EVT VT = Op.getValueType();
8449     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8450     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8451                        DAG.getConstant(NewIntNo, MVT::i32),
8452                        Op.getOperand(1), ShAmt);
8453   }
8454   }
8455 }
8456
8457 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8458                                            SelectionDAG &DAG) const {
8459   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8460   MFI->setReturnAddressIsTaken(true);
8461
8462   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8463   DebugLoc dl = Op.getDebugLoc();
8464
8465   if (Depth > 0) {
8466     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8467     SDValue Offset =
8468       DAG.getConstant(TD->getPointerSize(),
8469                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8470     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8471                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8472                                    FrameAddr, Offset),
8473                        MachinePointerInfo(), false, false, 0);
8474   }
8475
8476   // Just load the return address.
8477   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8478   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8479                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8480 }
8481
8482 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8483   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8484   MFI->setFrameAddressIsTaken(true);
8485
8486   EVT VT = Op.getValueType();
8487   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8488   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8489   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8490   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8491   while (Depth--)
8492     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8493                             MachinePointerInfo(),
8494                             false, false, 0);
8495   return FrameAddr;
8496 }
8497
8498 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8499                                                      SelectionDAG &DAG) const {
8500   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8501 }
8502
8503 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8504   MachineFunction &MF = DAG.getMachineFunction();
8505   SDValue Chain     = Op.getOperand(0);
8506   SDValue Offset    = Op.getOperand(1);
8507   SDValue Handler   = Op.getOperand(2);
8508   DebugLoc dl       = Op.getDebugLoc();
8509
8510   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8511                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8512                                      getPointerTy());
8513   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8514
8515   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8516                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8517   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8518   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8519                        false, false, 0);
8520   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8521   MF.getRegInfo().addLiveOut(StoreAddrReg);
8522
8523   return DAG.getNode(X86ISD::EH_RETURN, dl,
8524                      MVT::Other,
8525                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8526 }
8527
8528 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8529                                              SelectionDAG &DAG) const {
8530   SDValue Root = Op.getOperand(0);
8531   SDValue Trmp = Op.getOperand(1); // trampoline
8532   SDValue FPtr = Op.getOperand(2); // nested function
8533   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8534   DebugLoc dl  = Op.getDebugLoc();
8535
8536   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8537
8538   if (Subtarget->is64Bit()) {
8539     SDValue OutChains[6];
8540
8541     // Large code-model.
8542     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8543     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8544
8545     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8546     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8547
8548     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8549
8550     // Load the pointer to the nested function into R11.
8551     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8552     SDValue Addr = Trmp;
8553     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8554                                 Addr, MachinePointerInfo(TrmpAddr),
8555                                 false, false, 0);
8556
8557     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8558                        DAG.getConstant(2, MVT::i64));
8559     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8560                                 MachinePointerInfo(TrmpAddr, 2),
8561                                 false, false, 2);
8562
8563     // Load the 'nest' parameter value into R10.
8564     // R10 is specified in X86CallingConv.td
8565     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8566     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8567                        DAG.getConstant(10, MVT::i64));
8568     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8569                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8570                                 false, false, 0);
8571
8572     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8573                        DAG.getConstant(12, MVT::i64));
8574     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8575                                 MachinePointerInfo(TrmpAddr, 12),
8576                                 false, false, 2);
8577
8578     // Jump to the nested function.
8579     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8580     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8581                        DAG.getConstant(20, MVT::i64));
8582     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8583                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8584                                 false, false, 0);
8585
8586     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8587     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8588                        DAG.getConstant(22, MVT::i64));
8589     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8590                                 MachinePointerInfo(TrmpAddr, 22),
8591                                 false, false, 0);
8592
8593     SDValue Ops[] =
8594       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8595     return DAG.getMergeValues(Ops, 2, dl);
8596   } else {
8597     const Function *Func =
8598       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8599     CallingConv::ID CC = Func->getCallingConv();
8600     unsigned NestReg;
8601
8602     switch (CC) {
8603     default:
8604       llvm_unreachable("Unsupported calling convention");
8605     case CallingConv::C:
8606     case CallingConv::X86_StdCall: {
8607       // Pass 'nest' parameter in ECX.
8608       // Must be kept in sync with X86CallingConv.td
8609       NestReg = X86::ECX;
8610
8611       // Check that ECX wasn't needed by an 'inreg' parameter.
8612       const FunctionType *FTy = Func->getFunctionType();
8613       const AttrListPtr &Attrs = Func->getAttributes();
8614
8615       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8616         unsigned InRegCount = 0;
8617         unsigned Idx = 1;
8618
8619         for (FunctionType::param_iterator I = FTy->param_begin(),
8620              E = FTy->param_end(); I != E; ++I, ++Idx)
8621           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8622             // FIXME: should only count parameters that are lowered to integers.
8623             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8624
8625         if (InRegCount > 2) {
8626           report_fatal_error("Nest register in use - reduce number of inreg"
8627                              " parameters!");
8628         }
8629       }
8630       break;
8631     }
8632     case CallingConv::X86_FastCall:
8633     case CallingConv::X86_ThisCall:
8634     case CallingConv::Fast:
8635       // Pass 'nest' parameter in EAX.
8636       // Must be kept in sync with X86CallingConv.td
8637       NestReg = X86::EAX;
8638       break;
8639     }
8640
8641     SDValue OutChains[4];
8642     SDValue Addr, Disp;
8643
8644     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8645                        DAG.getConstant(10, MVT::i32));
8646     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8647
8648     // This is storing the opcode for MOV32ri.
8649     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8650     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8651     OutChains[0] = DAG.getStore(Root, dl,
8652                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8653                                 Trmp, MachinePointerInfo(TrmpAddr),
8654                                 false, false, 0);
8655
8656     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8657                        DAG.getConstant(1, MVT::i32));
8658     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8659                                 MachinePointerInfo(TrmpAddr, 1),
8660                                 false, false, 1);
8661
8662     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8663     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8664                        DAG.getConstant(5, MVT::i32));
8665     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8666                                 MachinePointerInfo(TrmpAddr, 5),
8667                                 false, false, 1);
8668
8669     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8670                        DAG.getConstant(6, MVT::i32));
8671     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8672                                 MachinePointerInfo(TrmpAddr, 6),
8673                                 false, false, 1);
8674
8675     SDValue Ops[] =
8676       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8677     return DAG.getMergeValues(Ops, 2, dl);
8678   }
8679 }
8680
8681 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8682                                             SelectionDAG &DAG) const {
8683   /*
8684    The rounding mode is in bits 11:10 of FPSR, and has the following
8685    settings:
8686      00 Round to nearest
8687      01 Round to -inf
8688      10 Round to +inf
8689      11 Round to 0
8690
8691   FLT_ROUNDS, on the other hand, expects the following:
8692     -1 Undefined
8693      0 Round to 0
8694      1 Round to nearest
8695      2 Round to +inf
8696      3 Round to -inf
8697
8698   To perform the conversion, we do:
8699     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8700   */
8701
8702   MachineFunction &MF = DAG.getMachineFunction();
8703   const TargetMachine &TM = MF.getTarget();
8704   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8705   unsigned StackAlignment = TFI.getStackAlignment();
8706   EVT VT = Op.getValueType();
8707   DebugLoc DL = Op.getDebugLoc();
8708
8709   // Save FP Control Word to stack slot
8710   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8711   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8712
8713
8714   MachineMemOperand *MMO =
8715    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8716                            MachineMemOperand::MOStore, 2, 2);
8717
8718   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8719   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8720                                           DAG.getVTList(MVT::Other),
8721                                           Ops, 2, MVT::i16, MMO);
8722
8723   // Load FP Control Word from stack slot
8724   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8725                             MachinePointerInfo(), false, false, 0);
8726
8727   // Transform as necessary
8728   SDValue CWD1 =
8729     DAG.getNode(ISD::SRL, DL, MVT::i16,
8730                 DAG.getNode(ISD::AND, DL, MVT::i16,
8731                             CWD, DAG.getConstant(0x800, MVT::i16)),
8732                 DAG.getConstant(11, MVT::i8));
8733   SDValue CWD2 =
8734     DAG.getNode(ISD::SRL, DL, MVT::i16,
8735                 DAG.getNode(ISD::AND, DL, MVT::i16,
8736                             CWD, DAG.getConstant(0x400, MVT::i16)),
8737                 DAG.getConstant(9, MVT::i8));
8738
8739   SDValue RetVal =
8740     DAG.getNode(ISD::AND, DL, MVT::i16,
8741                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8742                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8743                             DAG.getConstant(1, MVT::i16)),
8744                 DAG.getConstant(3, MVT::i16));
8745
8746
8747   return DAG.getNode((VT.getSizeInBits() < 16 ?
8748                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8749 }
8750
8751 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8752   EVT VT = Op.getValueType();
8753   EVT OpVT = VT;
8754   unsigned NumBits = VT.getSizeInBits();
8755   DebugLoc dl = Op.getDebugLoc();
8756
8757   Op = Op.getOperand(0);
8758   if (VT == MVT::i8) {
8759     // Zero extend to i32 since there is not an i8 bsr.
8760     OpVT = MVT::i32;
8761     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8762   }
8763
8764   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8765   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8766   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8767
8768   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8769   SDValue Ops[] = {
8770     Op,
8771     DAG.getConstant(NumBits+NumBits-1, OpVT),
8772     DAG.getConstant(X86::COND_E, MVT::i8),
8773     Op.getValue(1)
8774   };
8775   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8776
8777   // Finally xor with NumBits-1.
8778   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8779
8780   if (VT == MVT::i8)
8781     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8782   return Op;
8783 }
8784
8785 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8786   EVT VT = Op.getValueType();
8787   EVT OpVT = VT;
8788   unsigned NumBits = VT.getSizeInBits();
8789   DebugLoc dl = Op.getDebugLoc();
8790
8791   Op = Op.getOperand(0);
8792   if (VT == MVT::i8) {
8793     OpVT = MVT::i32;
8794     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8795   }
8796
8797   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8798   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8799   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8800
8801   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8802   SDValue Ops[] = {
8803     Op,
8804     DAG.getConstant(NumBits, OpVT),
8805     DAG.getConstant(X86::COND_E, MVT::i8),
8806     Op.getValue(1)
8807   };
8808   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8809
8810   if (VT == MVT::i8)
8811     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8812   return Op;
8813 }
8814
8815 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8816   EVT VT = Op.getValueType();
8817   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8818   DebugLoc dl = Op.getDebugLoc();
8819
8820   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8821   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8822   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8823   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8824   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8825   //
8826   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8827   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8828   //  return AloBlo + AloBhi + AhiBlo;
8829
8830   SDValue A = Op.getOperand(0);
8831   SDValue B = Op.getOperand(1);
8832
8833   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8834                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8835                        A, DAG.getConstant(32, MVT::i32));
8836   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8837                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8838                        B, DAG.getConstant(32, MVT::i32));
8839   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8840                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8841                        A, B);
8842   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8843                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8844                        A, Bhi);
8845   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8846                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8847                        Ahi, B);
8848   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8849                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8850                        AloBhi, DAG.getConstant(32, MVT::i32));
8851   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8852                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8853                        AhiBlo, DAG.getConstant(32, MVT::i32));
8854   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8855   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8856   return Res;
8857 }
8858
8859 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8860
8861   EVT VT = Op.getValueType();
8862   DebugLoc dl = Op.getDebugLoc();
8863   SDValue R = Op.getOperand(0);
8864   SDValue Amt = Op.getOperand(1);
8865
8866   LLVMContext *Context = DAG.getContext();
8867
8868   // Must have SSE2.
8869   if (!Subtarget->hasSSE2()) return SDValue();
8870
8871   // Optimize shl/srl/sra with constant shift amount.
8872   if (isSplatVector(Amt.getNode())) {
8873     SDValue SclrAmt = Amt->getOperand(0);
8874     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8875       uint64_t ShiftAmt = C->getZExtValue();
8876
8877       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8878        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8879                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8880                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8881
8882       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8883        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8884                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8885                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8886
8887       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8888        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8889                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8890                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8891
8892       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8893        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8894                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8895                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8896
8897       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8898        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8899                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8900                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8901
8902       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8903        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8904                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8905                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8906
8907       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8908        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8909                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8910                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8911
8912       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8913        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8914                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8915                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8916     }
8917   }
8918
8919   // Lower SHL with variable shift amount.
8920   // Cannot lower SHL without SSE4.1 or later.
8921   if (!Subtarget->hasSSE41()) return SDValue();
8922
8923   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8924     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8925                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8926                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8927
8928     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8929
8930     std::vector<Constant*> CV(4, CI);
8931     Constant *C = ConstantVector::get(CV);
8932     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8933     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8934                                  MachinePointerInfo::getConstantPool(),
8935                                  false, false, 16);
8936
8937     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8938     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8939     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8940     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8941   }
8942   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8943     // a = a << 5;
8944     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8945                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8946                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8947
8948     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8949     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8950
8951     std::vector<Constant*> CVM1(16, CM1);
8952     std::vector<Constant*> CVM2(16, CM2);
8953     Constant *C = ConstantVector::get(CVM1);
8954     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8955     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8956                             MachinePointerInfo::getConstantPool(),
8957                             false, false, 16);
8958
8959     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8960     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8961     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8962                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8963                     DAG.getConstant(4, MVT::i32));
8964     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8965     // a += a
8966     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8967
8968     C = ConstantVector::get(CVM2);
8969     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8970     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8971                     MachinePointerInfo::getConstantPool(),
8972                     false, false, 16);
8973
8974     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8975     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8976     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8977                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8978                     DAG.getConstant(2, MVT::i32));
8979     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8980     // a += a
8981     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8982
8983     // return pblendv(r, r+r, a);
8984     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8985                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8986     return R;
8987   }
8988   return SDValue();
8989 }
8990
8991 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8992   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8993   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8994   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8995   // has only one use.
8996   SDNode *N = Op.getNode();
8997   SDValue LHS = N->getOperand(0);
8998   SDValue RHS = N->getOperand(1);
8999   unsigned BaseOp = 0;
9000   unsigned Cond = 0;
9001   DebugLoc DL = Op.getDebugLoc();
9002   switch (Op.getOpcode()) {
9003   default: llvm_unreachable("Unknown ovf instruction!");
9004   case ISD::SADDO:
9005     // A subtract of one will be selected as a INC. Note that INC doesn't
9006     // set CF, so we can't do this for UADDO.
9007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9008       if (C->isOne()) {
9009         BaseOp = X86ISD::INC;
9010         Cond = X86::COND_O;
9011         break;
9012       }
9013     BaseOp = X86ISD::ADD;
9014     Cond = X86::COND_O;
9015     break;
9016   case ISD::UADDO:
9017     BaseOp = X86ISD::ADD;
9018     Cond = X86::COND_B;
9019     break;
9020   case ISD::SSUBO:
9021     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9022     // set CF, so we can't do this for USUBO.
9023     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9024       if (C->isOne()) {
9025         BaseOp = X86ISD::DEC;
9026         Cond = X86::COND_O;
9027         break;
9028       }
9029     BaseOp = X86ISD::SUB;
9030     Cond = X86::COND_O;
9031     break;
9032   case ISD::USUBO:
9033     BaseOp = X86ISD::SUB;
9034     Cond = X86::COND_B;
9035     break;
9036   case ISD::SMULO:
9037     BaseOp = X86ISD::SMUL;
9038     Cond = X86::COND_O;
9039     break;
9040   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9041     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9042                                  MVT::i32);
9043     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9044
9045     SDValue SetCC =
9046       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9047                   DAG.getConstant(X86::COND_O, MVT::i32),
9048                   SDValue(Sum.getNode(), 2));
9049
9050     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9051     return Sum;
9052   }
9053   }
9054
9055   // Also sets EFLAGS.
9056   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9057   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9058
9059   SDValue SetCC =
9060     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9061                 DAG.getConstant(Cond, MVT::i32),
9062                 SDValue(Sum.getNode(), 1));
9063
9064   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9065   return Sum;
9066 }
9067
9068 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9069   DebugLoc dl = Op.getDebugLoc();
9070
9071   if (!Subtarget->hasSSE2()) {
9072     SDValue Chain = Op.getOperand(0);
9073     SDValue Zero = DAG.getConstant(0,
9074                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9075     SDValue Ops[] = {
9076       DAG.getRegister(X86::ESP, MVT::i32), // Base
9077       DAG.getTargetConstant(1, MVT::i8),   // Scale
9078       DAG.getRegister(0, MVT::i32),        // Index
9079       DAG.getTargetConstant(0, MVT::i32),  // Disp
9080       DAG.getRegister(0, MVT::i32),        // Segment.
9081       Zero,
9082       Chain
9083     };
9084     SDNode *Res =
9085       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9086                           array_lengthof(Ops));
9087     return SDValue(Res, 0);
9088   }
9089
9090   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9091   if (!isDev)
9092     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9093
9094   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9095   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9096   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9097   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9098
9099   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9100   if (!Op1 && !Op2 && !Op3 && Op4)
9101     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9102
9103   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9104   if (Op1 && !Op2 && !Op3 && !Op4)
9105     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9106
9107   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9108   //           (MFENCE)>;
9109   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9110 }
9111
9112 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9113   EVT T = Op.getValueType();
9114   DebugLoc DL = Op.getDebugLoc();
9115   unsigned Reg = 0;
9116   unsigned size = 0;
9117   switch(T.getSimpleVT().SimpleTy) {
9118   default:
9119     assert(false && "Invalid value type!");
9120   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9121   case MVT::i16: Reg = X86::AX;  size = 2; break;
9122   case MVT::i32: Reg = X86::EAX; size = 4; break;
9123   case MVT::i64:
9124     assert(Subtarget->is64Bit() && "Node not type legal!");
9125     Reg = X86::RAX; size = 8;
9126     break;
9127   }
9128   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9129                                     Op.getOperand(2), SDValue());
9130   SDValue Ops[] = { cpIn.getValue(0),
9131                     Op.getOperand(1),
9132                     Op.getOperand(3),
9133                     DAG.getTargetConstant(size, MVT::i8),
9134                     cpIn.getValue(1) };
9135   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9136   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9137   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9138                                            Ops, 5, T, MMO);
9139   SDValue cpOut =
9140     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9141   return cpOut;
9142 }
9143
9144 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9145                                                  SelectionDAG &DAG) const {
9146   assert(Subtarget->is64Bit() && "Result not type legalized?");
9147   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9148   SDValue TheChain = Op.getOperand(0);
9149   DebugLoc dl = Op.getDebugLoc();
9150   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9151   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9152   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9153                                    rax.getValue(2));
9154   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9155                             DAG.getConstant(32, MVT::i8));
9156   SDValue Ops[] = {
9157     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9158     rdx.getValue(1)
9159   };
9160   return DAG.getMergeValues(Ops, 2, dl);
9161 }
9162
9163 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9164                                             SelectionDAG &DAG) const {
9165   EVT SrcVT = Op.getOperand(0).getValueType();
9166   EVT DstVT = Op.getValueType();
9167   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9168          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9169   assert((DstVT == MVT::i64 ||
9170           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9171          "Unexpected custom BITCAST");
9172   // i64 <=> MMX conversions are Legal.
9173   if (SrcVT==MVT::i64 && DstVT.isVector())
9174     return Op;
9175   if (DstVT==MVT::i64 && SrcVT.isVector())
9176     return Op;
9177   // MMX <=> MMX conversions are Legal.
9178   if (SrcVT.isVector() && DstVT.isVector())
9179     return Op;
9180   // All other conversions need to be expanded.
9181   return SDValue();
9182 }
9183
9184 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9185   SDNode *Node = Op.getNode();
9186   DebugLoc dl = Node->getDebugLoc();
9187   EVT T = Node->getValueType(0);
9188   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9189                               DAG.getConstant(0, T), Node->getOperand(2));
9190   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9191                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9192                        Node->getOperand(0),
9193                        Node->getOperand(1), negOp,
9194                        cast<AtomicSDNode>(Node)->getSrcValue(),
9195                        cast<AtomicSDNode>(Node)->getAlignment());
9196 }
9197
9198 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9199   EVT VT = Op.getNode()->getValueType(0);
9200
9201   // Let legalize expand this if it isn't a legal type yet.
9202   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9203     return SDValue();
9204
9205   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9206
9207   unsigned Opc;
9208   bool ExtraOp = false;
9209   switch (Op.getOpcode()) {
9210   default: assert(0 && "Invalid code");
9211   case ISD::ADDC: Opc = X86ISD::ADD; break;
9212   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9213   case ISD::SUBC: Opc = X86ISD::SUB; break;
9214   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9215   }
9216
9217   if (!ExtraOp)
9218     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9219                        Op.getOperand(1));
9220   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9221                      Op.getOperand(1), Op.getOperand(2));
9222 }
9223
9224 /// LowerOperation - Provide custom lowering hooks for some operations.
9225 ///
9226 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9227   switch (Op.getOpcode()) {
9228   default: llvm_unreachable("Should not custom lower this!");
9229   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9230   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9231   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9232   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9233   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9234   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9235   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9236   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9237   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9238   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9239   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9240   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9241   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9242   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9243   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9244   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9245   case ISD::SHL_PARTS:
9246   case ISD::SRA_PARTS:
9247   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9248   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9249   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9250   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9251   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9252   case ISD::FABS:               return LowerFABS(Op, DAG);
9253   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9254   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9255   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9256   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9257   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9258   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9259   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9260   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9261   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9262   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9263   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9264   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9265   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9266   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9267   case ISD::FRAME_TO_ARGS_OFFSET:
9268                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9269   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9270   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9271   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9272   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9273   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9274   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9275   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9276   case ISD::SRA:
9277   case ISD::SRL:
9278   case ISD::SHL:                return LowerShift(Op, DAG);
9279   case ISD::SADDO:
9280   case ISD::UADDO:
9281   case ISD::SSUBO:
9282   case ISD::USUBO:
9283   case ISD::SMULO:
9284   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9285   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9286   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9287   case ISD::ADDC:
9288   case ISD::ADDE:
9289   case ISD::SUBC:
9290   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9291   }
9292 }
9293
9294 void X86TargetLowering::
9295 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9296                         SelectionDAG &DAG, unsigned NewOp) const {
9297   EVT T = Node->getValueType(0);
9298   DebugLoc dl = Node->getDebugLoc();
9299   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9300
9301   SDValue Chain = Node->getOperand(0);
9302   SDValue In1 = Node->getOperand(1);
9303   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9304                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9305   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9306                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9307   SDValue Ops[] = { Chain, In1, In2L, In2H };
9308   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9309   SDValue Result =
9310     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9311                             cast<MemSDNode>(Node)->getMemOperand());
9312   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9313   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9314   Results.push_back(Result.getValue(2));
9315 }
9316
9317 /// ReplaceNodeResults - Replace a node with an illegal result type
9318 /// with a new node built out of custom code.
9319 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9320                                            SmallVectorImpl<SDValue>&Results,
9321                                            SelectionDAG &DAG) const {
9322   DebugLoc dl = N->getDebugLoc();
9323   switch (N->getOpcode()) {
9324   default:
9325     assert(false && "Do not know how to custom type legalize this operation!");
9326     return;
9327   case ISD::ADDC:
9328   case ISD::ADDE:
9329   case ISD::SUBC:
9330   case ISD::SUBE:
9331     // We don't want to expand or promote these.
9332     return;
9333   case ISD::FP_TO_SINT: {
9334     std::pair<SDValue,SDValue> Vals =
9335         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9336     SDValue FIST = Vals.first, StackSlot = Vals.second;
9337     if (FIST.getNode() != 0) {
9338       EVT VT = N->getValueType(0);
9339       // Return a load from the stack slot.
9340       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9341                                     MachinePointerInfo(), false, false, 0));
9342     }
9343     return;
9344   }
9345   case ISD::READCYCLECOUNTER: {
9346     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9347     SDValue TheChain = N->getOperand(0);
9348     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9349     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9350                                      rd.getValue(1));
9351     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9352                                      eax.getValue(2));
9353     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9354     SDValue Ops[] = { eax, edx };
9355     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9356     Results.push_back(edx.getValue(1));
9357     return;
9358   }
9359   case ISD::ATOMIC_CMP_SWAP: {
9360     EVT T = N->getValueType(0);
9361     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9362     SDValue cpInL, cpInH;
9363     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9364                         DAG.getConstant(0, MVT::i32));
9365     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9366                         DAG.getConstant(1, MVT::i32));
9367     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9368     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9369                              cpInL.getValue(1));
9370     SDValue swapInL, swapInH;
9371     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9372                           DAG.getConstant(0, MVT::i32));
9373     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9374                           DAG.getConstant(1, MVT::i32));
9375     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9376                                cpInH.getValue(1));
9377     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9378                                swapInL.getValue(1));
9379     SDValue Ops[] = { swapInH.getValue(0),
9380                       N->getOperand(1),
9381                       swapInH.getValue(1) };
9382     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9383     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9384     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9385                                              Ops, 3, T, MMO);
9386     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9387                                         MVT::i32, Result.getValue(1));
9388     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9389                                         MVT::i32, cpOutL.getValue(2));
9390     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9391     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9392     Results.push_back(cpOutH.getValue(1));
9393     return;
9394   }
9395   case ISD::ATOMIC_LOAD_ADD:
9396     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9397     return;
9398   case ISD::ATOMIC_LOAD_AND:
9399     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9400     return;
9401   case ISD::ATOMIC_LOAD_NAND:
9402     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9403     return;
9404   case ISD::ATOMIC_LOAD_OR:
9405     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9406     return;
9407   case ISD::ATOMIC_LOAD_SUB:
9408     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9409     return;
9410   case ISD::ATOMIC_LOAD_XOR:
9411     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9412     return;
9413   case ISD::ATOMIC_SWAP:
9414     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9415     return;
9416   }
9417 }
9418
9419 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9420   switch (Opcode) {
9421   default: return NULL;
9422   case X86ISD::BSF:                return "X86ISD::BSF";
9423   case X86ISD::BSR:                return "X86ISD::BSR";
9424   case X86ISD::SHLD:               return "X86ISD::SHLD";
9425   case X86ISD::SHRD:               return "X86ISD::SHRD";
9426   case X86ISD::FAND:               return "X86ISD::FAND";
9427   case X86ISD::FOR:                return "X86ISD::FOR";
9428   case X86ISD::FXOR:               return "X86ISD::FXOR";
9429   case X86ISD::FSRL:               return "X86ISD::FSRL";
9430   case X86ISD::FILD:               return "X86ISD::FILD";
9431   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9432   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9433   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9434   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9435   case X86ISD::FLD:                return "X86ISD::FLD";
9436   case X86ISD::FST:                return "X86ISD::FST";
9437   case X86ISD::CALL:               return "X86ISD::CALL";
9438   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9439   case X86ISD::BT:                 return "X86ISD::BT";
9440   case X86ISD::CMP:                return "X86ISD::CMP";
9441   case X86ISD::COMI:               return "X86ISD::COMI";
9442   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9443   case X86ISD::SETCC:              return "X86ISD::SETCC";
9444   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9445   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9446   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9447   case X86ISD::CMOV:               return "X86ISD::CMOV";
9448   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9449   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9450   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9451   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9452   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9453   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9454   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9455   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9456   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9457   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9458   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9459   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9460   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9461   case X86ISD::PANDN:              return "X86ISD::PANDN";
9462   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9463   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9464   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9465   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9466   case X86ISD::FMAX:               return "X86ISD::FMAX";
9467   case X86ISD::FMIN:               return "X86ISD::FMIN";
9468   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9469   case X86ISD::FRCP:               return "X86ISD::FRCP";
9470   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9471   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9472   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9473   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9474   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9475   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9476   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9477   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9478   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9479   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9480   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9481   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9482   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9483   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9484   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9485   case X86ISD::VSHL:               return "X86ISD::VSHL";
9486   case X86ISD::VSRL:               return "X86ISD::VSRL";
9487   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9488   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9489   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9490   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9491   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9492   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9493   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9494   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9495   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9496   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9497   case X86ISD::ADD:                return "X86ISD::ADD";
9498   case X86ISD::SUB:                return "X86ISD::SUB";
9499   case X86ISD::ADC:                return "X86ISD::ADC";
9500   case X86ISD::SBB:                return "X86ISD::SBB";
9501   case X86ISD::SMUL:               return "X86ISD::SMUL";
9502   case X86ISD::UMUL:               return "X86ISD::UMUL";
9503   case X86ISD::INC:                return "X86ISD::INC";
9504   case X86ISD::DEC:                return "X86ISD::DEC";
9505   case X86ISD::OR:                 return "X86ISD::OR";
9506   case X86ISD::XOR:                return "X86ISD::XOR";
9507   case X86ISD::AND:                return "X86ISD::AND";
9508   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9509   case X86ISD::PTEST:              return "X86ISD::PTEST";
9510   case X86ISD::TESTP:              return "X86ISD::TESTP";
9511   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9512   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9513   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9514   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9515   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9516   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9517   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9518   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9519   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9520   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9521   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9522   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9523   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9524   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9525   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9526   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9527   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9528   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9529   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9530   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9531   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9532   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9533   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9534   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9535   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9536   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9537   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9538   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9539   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9540   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9541   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9542   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9543   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9544   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9545   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9546   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9547   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9548   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9549   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9550   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9551   }
9552 }
9553
9554 // isLegalAddressingMode - Return true if the addressing mode represented
9555 // by AM is legal for this target, for a load/store of the specified type.
9556 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9557                                               const Type *Ty) const {
9558   // X86 supports extremely general addressing modes.
9559   CodeModel::Model M = getTargetMachine().getCodeModel();
9560   Reloc::Model R = getTargetMachine().getRelocationModel();
9561
9562   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9563   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9564     return false;
9565
9566   if (AM.BaseGV) {
9567     unsigned GVFlags =
9568       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9569
9570     // If a reference to this global requires an extra load, we can't fold it.
9571     if (isGlobalStubReference(GVFlags))
9572       return false;
9573
9574     // If BaseGV requires a register for the PIC base, we cannot also have a
9575     // BaseReg specified.
9576     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9577       return false;
9578
9579     // If lower 4G is not available, then we must use rip-relative addressing.
9580     if ((M != CodeModel::Small || R != Reloc::Static) &&
9581         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9582       return false;
9583   }
9584
9585   switch (AM.Scale) {
9586   case 0:
9587   case 1:
9588   case 2:
9589   case 4:
9590   case 8:
9591     // These scales always work.
9592     break;
9593   case 3:
9594   case 5:
9595   case 9:
9596     // These scales are formed with basereg+scalereg.  Only accept if there is
9597     // no basereg yet.
9598     if (AM.HasBaseReg)
9599       return false;
9600     break;
9601   default:  // Other stuff never works.
9602     return false;
9603   }
9604
9605   return true;
9606 }
9607
9608
9609 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9610   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9611     return false;
9612   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9613   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9614   if (NumBits1 <= NumBits2)
9615     return false;
9616   return true;
9617 }
9618
9619 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9620   if (!VT1.isInteger() || !VT2.isInteger())
9621     return false;
9622   unsigned NumBits1 = VT1.getSizeInBits();
9623   unsigned NumBits2 = VT2.getSizeInBits();
9624   if (NumBits1 <= NumBits2)
9625     return false;
9626   return true;
9627 }
9628
9629 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9630   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9631   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9632 }
9633
9634 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9635   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9636   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9637 }
9638
9639 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9640   // i16 instructions are longer (0x66 prefix) and potentially slower.
9641   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9642 }
9643
9644 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9645 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9646 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9647 /// are assumed to be legal.
9648 bool
9649 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9650                                       EVT VT) const {
9651   // Very little shuffling can be done for 64-bit vectors right now.
9652   if (VT.getSizeInBits() == 64)
9653     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9654
9655   // FIXME: pshufb, blends, shifts.
9656   return (VT.getVectorNumElements() == 2 ||
9657           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9658           isMOVLMask(M, VT) ||
9659           isSHUFPMask(M, VT) ||
9660           isPSHUFDMask(M, VT) ||
9661           isPSHUFHWMask(M, VT) ||
9662           isPSHUFLWMask(M, VT) ||
9663           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9664           isUNPCKLMask(M, VT) ||
9665           isUNPCKHMask(M, VT) ||
9666           isUNPCKL_v_undef_Mask(M, VT) ||
9667           isUNPCKH_v_undef_Mask(M, VT));
9668 }
9669
9670 bool
9671 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9672                                           EVT VT) const {
9673   unsigned NumElts = VT.getVectorNumElements();
9674   // FIXME: This collection of masks seems suspect.
9675   if (NumElts == 2)
9676     return true;
9677   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9678     return (isMOVLMask(Mask, VT)  ||
9679             isCommutedMOVLMask(Mask, VT, true) ||
9680             isSHUFPMask(Mask, VT) ||
9681             isCommutedSHUFPMask(Mask, VT));
9682   }
9683   return false;
9684 }
9685
9686 //===----------------------------------------------------------------------===//
9687 //                           X86 Scheduler Hooks
9688 //===----------------------------------------------------------------------===//
9689
9690 // private utility function
9691 MachineBasicBlock *
9692 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9693                                                        MachineBasicBlock *MBB,
9694                                                        unsigned regOpc,
9695                                                        unsigned immOpc,
9696                                                        unsigned LoadOpc,
9697                                                        unsigned CXchgOpc,
9698                                                        unsigned notOpc,
9699                                                        unsigned EAXreg,
9700                                                        TargetRegisterClass *RC,
9701                                                        bool invSrc) const {
9702   // For the atomic bitwise operator, we generate
9703   //   thisMBB:
9704   //   newMBB:
9705   //     ld  t1 = [bitinstr.addr]
9706   //     op  t2 = t1, [bitinstr.val]
9707   //     mov EAX = t1
9708   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9709   //     bz  newMBB
9710   //     fallthrough -->nextMBB
9711   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9712   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9713   MachineFunction::iterator MBBIter = MBB;
9714   ++MBBIter;
9715
9716   /// First build the CFG
9717   MachineFunction *F = MBB->getParent();
9718   MachineBasicBlock *thisMBB = MBB;
9719   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9720   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9721   F->insert(MBBIter, newMBB);
9722   F->insert(MBBIter, nextMBB);
9723
9724   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9725   nextMBB->splice(nextMBB->begin(), thisMBB,
9726                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9727                   thisMBB->end());
9728   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9729
9730   // Update thisMBB to fall through to newMBB
9731   thisMBB->addSuccessor(newMBB);
9732
9733   // newMBB jumps to itself and fall through to nextMBB
9734   newMBB->addSuccessor(nextMBB);
9735   newMBB->addSuccessor(newMBB);
9736
9737   // Insert instructions into newMBB based on incoming instruction
9738   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9739          "unexpected number of operands");
9740   DebugLoc dl = bInstr->getDebugLoc();
9741   MachineOperand& destOper = bInstr->getOperand(0);
9742   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9743   int numArgs = bInstr->getNumOperands() - 1;
9744   for (int i=0; i < numArgs; ++i)
9745     argOpers[i] = &bInstr->getOperand(i+1);
9746
9747   // x86 address has 4 operands: base, index, scale, and displacement
9748   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9749   int valArgIndx = lastAddrIndx + 1;
9750
9751   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9752   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9753   for (int i=0; i <= lastAddrIndx; ++i)
9754     (*MIB).addOperand(*argOpers[i]);
9755
9756   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9757   if (invSrc) {
9758     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9759   }
9760   else
9761     tt = t1;
9762
9763   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9764   assert((argOpers[valArgIndx]->isReg() ||
9765           argOpers[valArgIndx]->isImm()) &&
9766          "invalid operand");
9767   if (argOpers[valArgIndx]->isReg())
9768     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9769   else
9770     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9771   MIB.addReg(tt);
9772   (*MIB).addOperand(*argOpers[valArgIndx]);
9773
9774   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9775   MIB.addReg(t1);
9776
9777   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9778   for (int i=0; i <= lastAddrIndx; ++i)
9779     (*MIB).addOperand(*argOpers[i]);
9780   MIB.addReg(t2);
9781   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9782   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9783                     bInstr->memoperands_end());
9784
9785   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9786   MIB.addReg(EAXreg);
9787
9788   // insert branch
9789   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9790
9791   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9792   return nextMBB;
9793 }
9794
9795 // private utility function:  64 bit atomics on 32 bit host.
9796 MachineBasicBlock *
9797 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9798                                                        MachineBasicBlock *MBB,
9799                                                        unsigned regOpcL,
9800                                                        unsigned regOpcH,
9801                                                        unsigned immOpcL,
9802                                                        unsigned immOpcH,
9803                                                        bool invSrc) const {
9804   // For the atomic bitwise operator, we generate
9805   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9806   //     ld t1,t2 = [bitinstr.addr]
9807   //   newMBB:
9808   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9809   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9810   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9811   //     mov ECX, EBX <- t5, t6
9812   //     mov EAX, EDX <- t1, t2
9813   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9814   //     mov t3, t4 <- EAX, EDX
9815   //     bz  newMBB
9816   //     result in out1, out2
9817   //     fallthrough -->nextMBB
9818
9819   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9820   const unsigned LoadOpc = X86::MOV32rm;
9821   const unsigned NotOpc = X86::NOT32r;
9822   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9823   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9824   MachineFunction::iterator MBBIter = MBB;
9825   ++MBBIter;
9826
9827   /// First build the CFG
9828   MachineFunction *F = MBB->getParent();
9829   MachineBasicBlock *thisMBB = MBB;
9830   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9831   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9832   F->insert(MBBIter, newMBB);
9833   F->insert(MBBIter, nextMBB);
9834
9835   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9836   nextMBB->splice(nextMBB->begin(), thisMBB,
9837                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9838                   thisMBB->end());
9839   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9840
9841   // Update thisMBB to fall through to newMBB
9842   thisMBB->addSuccessor(newMBB);
9843
9844   // newMBB jumps to itself and fall through to nextMBB
9845   newMBB->addSuccessor(nextMBB);
9846   newMBB->addSuccessor(newMBB);
9847
9848   DebugLoc dl = bInstr->getDebugLoc();
9849   // Insert instructions into newMBB based on incoming instruction
9850   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9851   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9852          "unexpected number of operands");
9853   MachineOperand& dest1Oper = bInstr->getOperand(0);
9854   MachineOperand& dest2Oper = bInstr->getOperand(1);
9855   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9856   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9857     argOpers[i] = &bInstr->getOperand(i+2);
9858
9859     // We use some of the operands multiple times, so conservatively just
9860     // clear any kill flags that might be present.
9861     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9862       argOpers[i]->setIsKill(false);
9863   }
9864
9865   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9866   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9867
9868   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9869   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9870   for (int i=0; i <= lastAddrIndx; ++i)
9871     (*MIB).addOperand(*argOpers[i]);
9872   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9873   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9874   // add 4 to displacement.
9875   for (int i=0; i <= lastAddrIndx-2; ++i)
9876     (*MIB).addOperand(*argOpers[i]);
9877   MachineOperand newOp3 = *(argOpers[3]);
9878   if (newOp3.isImm())
9879     newOp3.setImm(newOp3.getImm()+4);
9880   else
9881     newOp3.setOffset(newOp3.getOffset()+4);
9882   (*MIB).addOperand(newOp3);
9883   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9884
9885   // t3/4 are defined later, at the bottom of the loop
9886   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9887   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9888   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9889     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9890   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9891     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9892
9893   // The subsequent operations should be using the destination registers of
9894   //the PHI instructions.
9895   if (invSrc) {
9896     t1 = F->getRegInfo().createVirtualRegister(RC);
9897     t2 = F->getRegInfo().createVirtualRegister(RC);
9898     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9899     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9900   } else {
9901     t1 = dest1Oper.getReg();
9902     t2 = dest2Oper.getReg();
9903   }
9904
9905   int valArgIndx = lastAddrIndx + 1;
9906   assert((argOpers[valArgIndx]->isReg() ||
9907           argOpers[valArgIndx]->isImm()) &&
9908          "invalid operand");
9909   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9910   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9911   if (argOpers[valArgIndx]->isReg())
9912     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9913   else
9914     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9915   if (regOpcL != X86::MOV32rr)
9916     MIB.addReg(t1);
9917   (*MIB).addOperand(*argOpers[valArgIndx]);
9918   assert(argOpers[valArgIndx + 1]->isReg() ==
9919          argOpers[valArgIndx]->isReg());
9920   assert(argOpers[valArgIndx + 1]->isImm() ==
9921          argOpers[valArgIndx]->isImm());
9922   if (argOpers[valArgIndx + 1]->isReg())
9923     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9924   else
9925     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9926   if (regOpcH != X86::MOV32rr)
9927     MIB.addReg(t2);
9928   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9929
9930   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9931   MIB.addReg(t1);
9932   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9933   MIB.addReg(t2);
9934
9935   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9936   MIB.addReg(t5);
9937   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9938   MIB.addReg(t6);
9939
9940   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9941   for (int i=0; i <= lastAddrIndx; ++i)
9942     (*MIB).addOperand(*argOpers[i]);
9943
9944   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9945   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9946                     bInstr->memoperands_end());
9947
9948   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9949   MIB.addReg(X86::EAX);
9950   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9951   MIB.addReg(X86::EDX);
9952
9953   // insert branch
9954   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9955
9956   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9957   return nextMBB;
9958 }
9959
9960 // private utility function
9961 MachineBasicBlock *
9962 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9963                                                       MachineBasicBlock *MBB,
9964                                                       unsigned cmovOpc) const {
9965   // For the atomic min/max operator, we generate
9966   //   thisMBB:
9967   //   newMBB:
9968   //     ld t1 = [min/max.addr]
9969   //     mov t2 = [min/max.val]
9970   //     cmp  t1, t2
9971   //     cmov[cond] t2 = t1
9972   //     mov EAX = t1
9973   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9974   //     bz   newMBB
9975   //     fallthrough -->nextMBB
9976   //
9977   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9978   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9979   MachineFunction::iterator MBBIter = MBB;
9980   ++MBBIter;
9981
9982   /// First build the CFG
9983   MachineFunction *F = MBB->getParent();
9984   MachineBasicBlock *thisMBB = MBB;
9985   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9986   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9987   F->insert(MBBIter, newMBB);
9988   F->insert(MBBIter, nextMBB);
9989
9990   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9991   nextMBB->splice(nextMBB->begin(), thisMBB,
9992                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9993                   thisMBB->end());
9994   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9995
9996   // Update thisMBB to fall through to newMBB
9997   thisMBB->addSuccessor(newMBB);
9998
9999   // newMBB jumps to newMBB and fall through to nextMBB
10000   newMBB->addSuccessor(nextMBB);
10001   newMBB->addSuccessor(newMBB);
10002
10003   DebugLoc dl = mInstr->getDebugLoc();
10004   // Insert instructions into newMBB based on incoming instruction
10005   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10006          "unexpected number of operands");
10007   MachineOperand& destOper = mInstr->getOperand(0);
10008   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10009   int numArgs = mInstr->getNumOperands() - 1;
10010   for (int i=0; i < numArgs; ++i)
10011     argOpers[i] = &mInstr->getOperand(i+1);
10012
10013   // x86 address has 4 operands: base, index, scale, and displacement
10014   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10015   int valArgIndx = lastAddrIndx + 1;
10016
10017   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10018   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10019   for (int i=0; i <= lastAddrIndx; ++i)
10020     (*MIB).addOperand(*argOpers[i]);
10021
10022   // We only support register and immediate values
10023   assert((argOpers[valArgIndx]->isReg() ||
10024           argOpers[valArgIndx]->isImm()) &&
10025          "invalid operand");
10026
10027   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10028   if (argOpers[valArgIndx]->isReg())
10029     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10030   else
10031     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10032   (*MIB).addOperand(*argOpers[valArgIndx]);
10033
10034   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10035   MIB.addReg(t1);
10036
10037   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10038   MIB.addReg(t1);
10039   MIB.addReg(t2);
10040
10041   // Generate movc
10042   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10043   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10044   MIB.addReg(t2);
10045   MIB.addReg(t1);
10046
10047   // Cmp and exchange if none has modified the memory location
10048   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10049   for (int i=0; i <= lastAddrIndx; ++i)
10050     (*MIB).addOperand(*argOpers[i]);
10051   MIB.addReg(t3);
10052   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10053   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10054                     mInstr->memoperands_end());
10055
10056   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10057   MIB.addReg(X86::EAX);
10058
10059   // insert branch
10060   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10061
10062   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10063   return nextMBB;
10064 }
10065
10066 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10067 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10068 // in the .td file.
10069 MachineBasicBlock *
10070 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10071                             unsigned numArgs, bool memArg) const {
10072   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10073          "Target must have SSE4.2 or AVX features enabled");
10074
10075   DebugLoc dl = MI->getDebugLoc();
10076   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10077   unsigned Opc;
10078   if (!Subtarget->hasAVX()) {
10079     if (memArg)
10080       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10081     else
10082       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10083   } else {
10084     if (memArg)
10085       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10086     else
10087       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10088   }
10089
10090   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10091   for (unsigned i = 0; i < numArgs; ++i) {
10092     MachineOperand &Op = MI->getOperand(i+1);
10093     if (!(Op.isReg() && Op.isImplicit()))
10094       MIB.addOperand(Op);
10095   }
10096   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10097     .addReg(X86::XMM0);
10098
10099   MI->eraseFromParent();
10100   return BB;
10101 }
10102
10103 MachineBasicBlock *
10104 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10105   DebugLoc dl = MI->getDebugLoc();
10106   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10107
10108   // Address into RAX/EAX, other two args into ECX, EDX.
10109   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10110   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10111   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10112   for (int i = 0; i < X86::AddrNumOperands; ++i)
10113     MIB.addOperand(MI->getOperand(i));
10114
10115   unsigned ValOps = X86::AddrNumOperands;
10116   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10117     .addReg(MI->getOperand(ValOps).getReg());
10118   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10119     .addReg(MI->getOperand(ValOps+1).getReg());
10120
10121   // The instruction doesn't actually take any operands though.
10122   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10123
10124   MI->eraseFromParent(); // The pseudo is gone now.
10125   return BB;
10126 }
10127
10128 MachineBasicBlock *
10129 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10130   DebugLoc dl = MI->getDebugLoc();
10131   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10132
10133   // First arg in ECX, the second in EAX.
10134   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10135     .addReg(MI->getOperand(0).getReg());
10136   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10137     .addReg(MI->getOperand(1).getReg());
10138
10139   // The instruction doesn't actually take any operands though.
10140   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10141
10142   MI->eraseFromParent(); // The pseudo is gone now.
10143   return BB;
10144 }
10145
10146 MachineBasicBlock *
10147 X86TargetLowering::EmitVAARG64WithCustomInserter(
10148                    MachineInstr *MI,
10149                    MachineBasicBlock *MBB) const {
10150   // Emit va_arg instruction on X86-64.
10151
10152   // Operands to this pseudo-instruction:
10153   // 0  ) Output        : destination address (reg)
10154   // 1-5) Input         : va_list address (addr, i64mem)
10155   // 6  ) ArgSize       : Size (in bytes) of vararg type
10156   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10157   // 8  ) Align         : Alignment of type
10158   // 9  ) EFLAGS (implicit-def)
10159
10160   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10161   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10162
10163   unsigned DestReg = MI->getOperand(0).getReg();
10164   MachineOperand &Base = MI->getOperand(1);
10165   MachineOperand &Scale = MI->getOperand(2);
10166   MachineOperand &Index = MI->getOperand(3);
10167   MachineOperand &Disp = MI->getOperand(4);
10168   MachineOperand &Segment = MI->getOperand(5);
10169   unsigned ArgSize = MI->getOperand(6).getImm();
10170   unsigned ArgMode = MI->getOperand(7).getImm();
10171   unsigned Align = MI->getOperand(8).getImm();
10172
10173   // Memory Reference
10174   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10175   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10176   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10177
10178   // Machine Information
10179   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10180   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10181   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10182   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10183   DebugLoc DL = MI->getDebugLoc();
10184
10185   // struct va_list {
10186   //   i32   gp_offset
10187   //   i32   fp_offset
10188   //   i64   overflow_area (address)
10189   //   i64   reg_save_area (address)
10190   // }
10191   // sizeof(va_list) = 24
10192   // alignment(va_list) = 8
10193
10194   unsigned TotalNumIntRegs = 6;
10195   unsigned TotalNumXMMRegs = 8;
10196   bool UseGPOffset = (ArgMode == 1);
10197   bool UseFPOffset = (ArgMode == 2);
10198   unsigned MaxOffset = TotalNumIntRegs * 8 +
10199                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10200
10201   /* Align ArgSize to a multiple of 8 */
10202   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10203   bool NeedsAlign = (Align > 8);
10204
10205   MachineBasicBlock *thisMBB = MBB;
10206   MachineBasicBlock *overflowMBB;
10207   MachineBasicBlock *offsetMBB;
10208   MachineBasicBlock *endMBB;
10209
10210   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10211   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10212   unsigned OffsetReg = 0;
10213
10214   if (!UseGPOffset && !UseFPOffset) {
10215     // If we only pull from the overflow region, we don't create a branch.
10216     // We don't need to alter control flow.
10217     OffsetDestReg = 0; // unused
10218     OverflowDestReg = DestReg;
10219
10220     offsetMBB = NULL;
10221     overflowMBB = thisMBB;
10222     endMBB = thisMBB;
10223   } else {
10224     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10225     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10226     // If not, pull from overflow_area. (branch to overflowMBB)
10227     //
10228     //       thisMBB
10229     //         |     .
10230     //         |        .
10231     //     offsetMBB   overflowMBB
10232     //         |        .
10233     //         |     .
10234     //        endMBB
10235
10236     // Registers for the PHI in endMBB
10237     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10238     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10239
10240     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10241     MachineFunction *MF = MBB->getParent();
10242     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10243     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10244     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10245
10246     MachineFunction::iterator MBBIter = MBB;
10247     ++MBBIter;
10248
10249     // Insert the new basic blocks
10250     MF->insert(MBBIter, offsetMBB);
10251     MF->insert(MBBIter, overflowMBB);
10252     MF->insert(MBBIter, endMBB);
10253
10254     // Transfer the remainder of MBB and its successor edges to endMBB.
10255     endMBB->splice(endMBB->begin(), thisMBB,
10256                     llvm::next(MachineBasicBlock::iterator(MI)),
10257                     thisMBB->end());
10258     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10259
10260     // Make offsetMBB and overflowMBB successors of thisMBB
10261     thisMBB->addSuccessor(offsetMBB);
10262     thisMBB->addSuccessor(overflowMBB);
10263
10264     // endMBB is a successor of both offsetMBB and overflowMBB
10265     offsetMBB->addSuccessor(endMBB);
10266     overflowMBB->addSuccessor(endMBB);
10267
10268     // Load the offset value into a register
10269     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10270     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10271       .addOperand(Base)
10272       .addOperand(Scale)
10273       .addOperand(Index)
10274       .addDisp(Disp, UseFPOffset ? 4 : 0)
10275       .addOperand(Segment)
10276       .setMemRefs(MMOBegin, MMOEnd);
10277
10278     // Check if there is enough room left to pull this argument.
10279     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10280       .addReg(OffsetReg)
10281       .addImm(MaxOffset + 8 - ArgSizeA8);
10282
10283     // Branch to "overflowMBB" if offset >= max
10284     // Fall through to "offsetMBB" otherwise
10285     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10286       .addMBB(overflowMBB);
10287   }
10288
10289   // In offsetMBB, emit code to use the reg_save_area.
10290   if (offsetMBB) {
10291     assert(OffsetReg != 0);
10292
10293     // Read the reg_save_area address.
10294     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10295     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10296       .addOperand(Base)
10297       .addOperand(Scale)
10298       .addOperand(Index)
10299       .addDisp(Disp, 16)
10300       .addOperand(Segment)
10301       .setMemRefs(MMOBegin, MMOEnd);
10302
10303     // Zero-extend the offset
10304     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10305       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10306         .addImm(0)
10307         .addReg(OffsetReg)
10308         .addImm(X86::sub_32bit);
10309
10310     // Add the offset to the reg_save_area to get the final address.
10311     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10312       .addReg(OffsetReg64)
10313       .addReg(RegSaveReg);
10314
10315     // Compute the offset for the next argument
10316     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10317     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10318       .addReg(OffsetReg)
10319       .addImm(UseFPOffset ? 16 : 8);
10320
10321     // Store it back into the va_list.
10322     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10323       .addOperand(Base)
10324       .addOperand(Scale)
10325       .addOperand(Index)
10326       .addDisp(Disp, UseFPOffset ? 4 : 0)
10327       .addOperand(Segment)
10328       .addReg(NextOffsetReg)
10329       .setMemRefs(MMOBegin, MMOEnd);
10330
10331     // Jump to endMBB
10332     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10333       .addMBB(endMBB);
10334   }
10335
10336   //
10337   // Emit code to use overflow area
10338   //
10339
10340   // Load the overflow_area address into a register.
10341   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10342   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10343     .addOperand(Base)
10344     .addOperand(Scale)
10345     .addOperand(Index)
10346     .addDisp(Disp, 8)
10347     .addOperand(Segment)
10348     .setMemRefs(MMOBegin, MMOEnd);
10349
10350   // If we need to align it, do so. Otherwise, just copy the address
10351   // to OverflowDestReg.
10352   if (NeedsAlign) {
10353     // Align the overflow address
10354     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10355     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10356
10357     // aligned_addr = (addr + (align-1)) & ~(align-1)
10358     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10359       .addReg(OverflowAddrReg)
10360       .addImm(Align-1);
10361
10362     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10363       .addReg(TmpReg)
10364       .addImm(~(uint64_t)(Align-1));
10365   } else {
10366     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10367       .addReg(OverflowAddrReg);
10368   }
10369
10370   // Compute the next overflow address after this argument.
10371   // (the overflow address should be kept 8-byte aligned)
10372   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10373   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10374     .addReg(OverflowDestReg)
10375     .addImm(ArgSizeA8);
10376
10377   // Store the new overflow address.
10378   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10379     .addOperand(Base)
10380     .addOperand(Scale)
10381     .addOperand(Index)
10382     .addDisp(Disp, 8)
10383     .addOperand(Segment)
10384     .addReg(NextAddrReg)
10385     .setMemRefs(MMOBegin, MMOEnd);
10386
10387   // If we branched, emit the PHI to the front of endMBB.
10388   if (offsetMBB) {
10389     BuildMI(*endMBB, endMBB->begin(), DL,
10390             TII->get(X86::PHI), DestReg)
10391       .addReg(OffsetDestReg).addMBB(offsetMBB)
10392       .addReg(OverflowDestReg).addMBB(overflowMBB);
10393   }
10394
10395   // Erase the pseudo instruction
10396   MI->eraseFromParent();
10397
10398   return endMBB;
10399 }
10400
10401 MachineBasicBlock *
10402 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10403                                                  MachineInstr *MI,
10404                                                  MachineBasicBlock *MBB) const {
10405   // Emit code to save XMM registers to the stack. The ABI says that the
10406   // number of registers to save is given in %al, so it's theoretically
10407   // possible to do an indirect jump trick to avoid saving all of them,
10408   // however this code takes a simpler approach and just executes all
10409   // of the stores if %al is non-zero. It's less code, and it's probably
10410   // easier on the hardware branch predictor, and stores aren't all that
10411   // expensive anyway.
10412
10413   // Create the new basic blocks. One block contains all the XMM stores,
10414   // and one block is the final destination regardless of whether any
10415   // stores were performed.
10416   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10417   MachineFunction *F = MBB->getParent();
10418   MachineFunction::iterator MBBIter = MBB;
10419   ++MBBIter;
10420   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10421   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10422   F->insert(MBBIter, XMMSaveMBB);
10423   F->insert(MBBIter, EndMBB);
10424
10425   // Transfer the remainder of MBB and its successor edges to EndMBB.
10426   EndMBB->splice(EndMBB->begin(), MBB,
10427                  llvm::next(MachineBasicBlock::iterator(MI)),
10428                  MBB->end());
10429   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10430
10431   // The original block will now fall through to the XMM save block.
10432   MBB->addSuccessor(XMMSaveMBB);
10433   // The XMMSaveMBB will fall through to the end block.
10434   XMMSaveMBB->addSuccessor(EndMBB);
10435
10436   // Now add the instructions.
10437   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10438   DebugLoc DL = MI->getDebugLoc();
10439
10440   unsigned CountReg = MI->getOperand(0).getReg();
10441   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10442   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10443
10444   if (!Subtarget->isTargetWin64()) {
10445     // If %al is 0, branch around the XMM save block.
10446     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10447     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10448     MBB->addSuccessor(EndMBB);
10449   }
10450
10451   // In the XMM save block, save all the XMM argument registers.
10452   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10453     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10454     MachineMemOperand *MMO =
10455       F->getMachineMemOperand(
10456           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10457         MachineMemOperand::MOStore,
10458         /*Size=*/16, /*Align=*/16);
10459     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10460       .addFrameIndex(RegSaveFrameIndex)
10461       .addImm(/*Scale=*/1)
10462       .addReg(/*IndexReg=*/0)
10463       .addImm(/*Disp=*/Offset)
10464       .addReg(/*Segment=*/0)
10465       .addReg(MI->getOperand(i).getReg())
10466       .addMemOperand(MMO);
10467   }
10468
10469   MI->eraseFromParent();   // The pseudo instruction is gone now.
10470
10471   return EndMBB;
10472 }
10473
10474 MachineBasicBlock *
10475 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10476                                      MachineBasicBlock *BB) const {
10477   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10478   DebugLoc DL = MI->getDebugLoc();
10479
10480   // To "insert" a SELECT_CC instruction, we actually have to insert the
10481   // diamond control-flow pattern.  The incoming instruction knows the
10482   // destination vreg to set, the condition code register to branch on, the
10483   // true/false values to select between, and a branch opcode to use.
10484   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10485   MachineFunction::iterator It = BB;
10486   ++It;
10487
10488   //  thisMBB:
10489   //  ...
10490   //   TrueVal = ...
10491   //   cmpTY ccX, r1, r2
10492   //   bCC copy1MBB
10493   //   fallthrough --> copy0MBB
10494   MachineBasicBlock *thisMBB = BB;
10495   MachineFunction *F = BB->getParent();
10496   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10497   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10498   F->insert(It, copy0MBB);
10499   F->insert(It, sinkMBB);
10500
10501   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10502   // live into the sink and copy blocks.
10503   const MachineFunction *MF = BB->getParent();
10504   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10505   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10506
10507   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10508     const MachineOperand &MO = MI->getOperand(I);
10509     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10510     unsigned Reg = MO.getReg();
10511     if (Reg != X86::EFLAGS) continue;
10512     copy0MBB->addLiveIn(Reg);
10513     sinkMBB->addLiveIn(Reg);
10514   }
10515
10516   // Transfer the remainder of BB and its successor edges to sinkMBB.
10517   sinkMBB->splice(sinkMBB->begin(), BB,
10518                   llvm::next(MachineBasicBlock::iterator(MI)),
10519                   BB->end());
10520   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10521
10522   // Add the true and fallthrough blocks as its successors.
10523   BB->addSuccessor(copy0MBB);
10524   BB->addSuccessor(sinkMBB);
10525
10526   // Create the conditional branch instruction.
10527   unsigned Opc =
10528     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10529   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10530
10531   //  copy0MBB:
10532   //   %FalseValue = ...
10533   //   # fallthrough to sinkMBB
10534   copy0MBB->addSuccessor(sinkMBB);
10535
10536   //  sinkMBB:
10537   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10538   //  ...
10539   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10540           TII->get(X86::PHI), MI->getOperand(0).getReg())
10541     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10542     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10543
10544   MI->eraseFromParent();   // The pseudo instruction is gone now.
10545   return sinkMBB;
10546 }
10547
10548 MachineBasicBlock *
10549 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10550                                           MachineBasicBlock *BB) const {
10551   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10552   DebugLoc DL = MI->getDebugLoc();
10553
10554   assert(!Subtarget->isTargetEnvMacho());
10555
10556   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10557   // non-trivial part is impdef of ESP.
10558
10559   if (Subtarget->isTargetWin64()) {
10560     if (Subtarget->isTargetCygMing()) {
10561       // ___chkstk(Mingw64):
10562       // Clobbers R10, R11, RAX and EFLAGS.
10563       // Updates RSP.
10564       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10565         .addExternalSymbol("___chkstk")
10566         .addReg(X86::RAX, RegState::Implicit)
10567         .addReg(X86::RSP, RegState::Implicit)
10568         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10569         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10570         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10571     } else {
10572       // __chkstk(MSVCRT): does not update stack pointer.
10573       // Clobbers R10, R11 and EFLAGS.
10574       // FIXME: RAX(allocated size) might be reused and not killed.
10575       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10576         .addExternalSymbol("__chkstk")
10577         .addReg(X86::RAX, RegState::Implicit)
10578         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10579       // RAX has the offset to subtracted from RSP.
10580       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10581         .addReg(X86::RSP)
10582         .addReg(X86::RAX);
10583     }
10584   } else {
10585     const char *StackProbeSymbol =
10586       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10587
10588     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10589       .addExternalSymbol(StackProbeSymbol)
10590       .addReg(X86::EAX, RegState::Implicit)
10591       .addReg(X86::ESP, RegState::Implicit)
10592       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10593       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10594       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10595   }
10596
10597   MI->eraseFromParent();   // The pseudo instruction is gone now.
10598   return BB;
10599 }
10600
10601 MachineBasicBlock *
10602 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10603                                       MachineBasicBlock *BB) const {
10604   // This is pretty easy.  We're taking the value that we received from
10605   // our load from the relocation, sticking it in either RDI (x86-64)
10606   // or EAX and doing an indirect call.  The return value will then
10607   // be in the normal return register.
10608   const X86InstrInfo *TII
10609     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10610   DebugLoc DL = MI->getDebugLoc();
10611   MachineFunction *F = BB->getParent();
10612
10613   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10614   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10615
10616   if (Subtarget->is64Bit()) {
10617     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10618                                       TII->get(X86::MOV64rm), X86::RDI)
10619     .addReg(X86::RIP)
10620     .addImm(0).addReg(0)
10621     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10622                       MI->getOperand(3).getTargetFlags())
10623     .addReg(0);
10624     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10625     addDirectMem(MIB, X86::RDI);
10626   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10627     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10628                                       TII->get(X86::MOV32rm), X86::EAX)
10629     .addReg(0)
10630     .addImm(0).addReg(0)
10631     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10632                       MI->getOperand(3).getTargetFlags())
10633     .addReg(0);
10634     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10635     addDirectMem(MIB, X86::EAX);
10636   } else {
10637     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10638                                       TII->get(X86::MOV32rm), X86::EAX)
10639     .addReg(TII->getGlobalBaseReg(F))
10640     .addImm(0).addReg(0)
10641     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10642                       MI->getOperand(3).getTargetFlags())
10643     .addReg(0);
10644     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10645     addDirectMem(MIB, X86::EAX);
10646   }
10647
10648   MI->eraseFromParent(); // The pseudo instruction is gone now.
10649   return BB;
10650 }
10651
10652 MachineBasicBlock *
10653 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10654                                                MachineBasicBlock *BB) const {
10655   switch (MI->getOpcode()) {
10656   default: assert(false && "Unexpected instr type to insert");
10657   case X86::TAILJMPd64:
10658   case X86::TAILJMPr64:
10659   case X86::TAILJMPm64:
10660     assert(!"TAILJMP64 would not be touched here.");
10661   case X86::TCRETURNdi64:
10662   case X86::TCRETURNri64:
10663   case X86::TCRETURNmi64:
10664     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10665     // On AMD64, additional defs should be added before register allocation.
10666     if (!Subtarget->isTargetWin64()) {
10667       MI->addRegisterDefined(X86::RSI);
10668       MI->addRegisterDefined(X86::RDI);
10669       MI->addRegisterDefined(X86::XMM6);
10670       MI->addRegisterDefined(X86::XMM7);
10671       MI->addRegisterDefined(X86::XMM8);
10672       MI->addRegisterDefined(X86::XMM9);
10673       MI->addRegisterDefined(X86::XMM10);
10674       MI->addRegisterDefined(X86::XMM11);
10675       MI->addRegisterDefined(X86::XMM12);
10676       MI->addRegisterDefined(X86::XMM13);
10677       MI->addRegisterDefined(X86::XMM14);
10678       MI->addRegisterDefined(X86::XMM15);
10679     }
10680     return BB;
10681   case X86::WIN_ALLOCA:
10682     return EmitLoweredWinAlloca(MI, BB);
10683   case X86::TLSCall_32:
10684   case X86::TLSCall_64:
10685     return EmitLoweredTLSCall(MI, BB);
10686   case X86::CMOV_GR8:
10687   case X86::CMOV_FR32:
10688   case X86::CMOV_FR64:
10689   case X86::CMOV_V4F32:
10690   case X86::CMOV_V2F64:
10691   case X86::CMOV_V2I64:
10692   case X86::CMOV_GR16:
10693   case X86::CMOV_GR32:
10694   case X86::CMOV_RFP32:
10695   case X86::CMOV_RFP64:
10696   case X86::CMOV_RFP80:
10697     return EmitLoweredSelect(MI, BB);
10698
10699   case X86::FP32_TO_INT16_IN_MEM:
10700   case X86::FP32_TO_INT32_IN_MEM:
10701   case X86::FP32_TO_INT64_IN_MEM:
10702   case X86::FP64_TO_INT16_IN_MEM:
10703   case X86::FP64_TO_INT32_IN_MEM:
10704   case X86::FP64_TO_INT64_IN_MEM:
10705   case X86::FP80_TO_INT16_IN_MEM:
10706   case X86::FP80_TO_INT32_IN_MEM:
10707   case X86::FP80_TO_INT64_IN_MEM: {
10708     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10709     DebugLoc DL = MI->getDebugLoc();
10710
10711     // Change the floating point control register to use "round towards zero"
10712     // mode when truncating to an integer value.
10713     MachineFunction *F = BB->getParent();
10714     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10715     addFrameReference(BuildMI(*BB, MI, DL,
10716                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10717
10718     // Load the old value of the high byte of the control word...
10719     unsigned OldCW =
10720       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10721     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10722                       CWFrameIdx);
10723
10724     // Set the high part to be round to zero...
10725     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10726       .addImm(0xC7F);
10727
10728     // Reload the modified control word now...
10729     addFrameReference(BuildMI(*BB, MI, DL,
10730                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10731
10732     // Restore the memory image of control word to original value
10733     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10734       .addReg(OldCW);
10735
10736     // Get the X86 opcode to use.
10737     unsigned Opc;
10738     switch (MI->getOpcode()) {
10739     default: llvm_unreachable("illegal opcode!");
10740     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10741     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10742     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10743     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10744     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10745     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10746     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10747     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10748     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10749     }
10750
10751     X86AddressMode AM;
10752     MachineOperand &Op = MI->getOperand(0);
10753     if (Op.isReg()) {
10754       AM.BaseType = X86AddressMode::RegBase;
10755       AM.Base.Reg = Op.getReg();
10756     } else {
10757       AM.BaseType = X86AddressMode::FrameIndexBase;
10758       AM.Base.FrameIndex = Op.getIndex();
10759     }
10760     Op = MI->getOperand(1);
10761     if (Op.isImm())
10762       AM.Scale = Op.getImm();
10763     Op = MI->getOperand(2);
10764     if (Op.isImm())
10765       AM.IndexReg = Op.getImm();
10766     Op = MI->getOperand(3);
10767     if (Op.isGlobal()) {
10768       AM.GV = Op.getGlobal();
10769     } else {
10770       AM.Disp = Op.getImm();
10771     }
10772     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10773                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10774
10775     // Reload the original control word now.
10776     addFrameReference(BuildMI(*BB, MI, DL,
10777                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10778
10779     MI->eraseFromParent();   // The pseudo instruction is gone now.
10780     return BB;
10781   }
10782     // String/text processing lowering.
10783   case X86::PCMPISTRM128REG:
10784   case X86::VPCMPISTRM128REG:
10785     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10786   case X86::PCMPISTRM128MEM:
10787   case X86::VPCMPISTRM128MEM:
10788     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10789   case X86::PCMPESTRM128REG:
10790   case X86::VPCMPESTRM128REG:
10791     return EmitPCMP(MI, BB, 5, false /* in mem */);
10792   case X86::PCMPESTRM128MEM:
10793   case X86::VPCMPESTRM128MEM:
10794     return EmitPCMP(MI, BB, 5, true /* in mem */);
10795
10796     // Thread synchronization.
10797   case X86::MONITOR:
10798     return EmitMonitor(MI, BB);
10799   case X86::MWAIT:
10800     return EmitMwait(MI, BB);
10801
10802     // Atomic Lowering.
10803   case X86::ATOMAND32:
10804     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10805                                                X86::AND32ri, X86::MOV32rm,
10806                                                X86::LCMPXCHG32,
10807                                                X86::NOT32r, X86::EAX,
10808                                                X86::GR32RegisterClass);
10809   case X86::ATOMOR32:
10810     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10811                                                X86::OR32ri, X86::MOV32rm,
10812                                                X86::LCMPXCHG32,
10813                                                X86::NOT32r, X86::EAX,
10814                                                X86::GR32RegisterClass);
10815   case X86::ATOMXOR32:
10816     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10817                                                X86::XOR32ri, X86::MOV32rm,
10818                                                X86::LCMPXCHG32,
10819                                                X86::NOT32r, X86::EAX,
10820                                                X86::GR32RegisterClass);
10821   case X86::ATOMNAND32:
10822     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10823                                                X86::AND32ri, X86::MOV32rm,
10824                                                X86::LCMPXCHG32,
10825                                                X86::NOT32r, X86::EAX,
10826                                                X86::GR32RegisterClass, true);
10827   case X86::ATOMMIN32:
10828     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10829   case X86::ATOMMAX32:
10830     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10831   case X86::ATOMUMIN32:
10832     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10833   case X86::ATOMUMAX32:
10834     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10835
10836   case X86::ATOMAND16:
10837     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10838                                                X86::AND16ri, X86::MOV16rm,
10839                                                X86::LCMPXCHG16,
10840                                                X86::NOT16r, X86::AX,
10841                                                X86::GR16RegisterClass);
10842   case X86::ATOMOR16:
10843     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10844                                                X86::OR16ri, X86::MOV16rm,
10845                                                X86::LCMPXCHG16,
10846                                                X86::NOT16r, X86::AX,
10847                                                X86::GR16RegisterClass);
10848   case X86::ATOMXOR16:
10849     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10850                                                X86::XOR16ri, X86::MOV16rm,
10851                                                X86::LCMPXCHG16,
10852                                                X86::NOT16r, X86::AX,
10853                                                X86::GR16RegisterClass);
10854   case X86::ATOMNAND16:
10855     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10856                                                X86::AND16ri, X86::MOV16rm,
10857                                                X86::LCMPXCHG16,
10858                                                X86::NOT16r, X86::AX,
10859                                                X86::GR16RegisterClass, true);
10860   case X86::ATOMMIN16:
10861     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10862   case X86::ATOMMAX16:
10863     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10864   case X86::ATOMUMIN16:
10865     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10866   case X86::ATOMUMAX16:
10867     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10868
10869   case X86::ATOMAND8:
10870     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10871                                                X86::AND8ri, X86::MOV8rm,
10872                                                X86::LCMPXCHG8,
10873                                                X86::NOT8r, X86::AL,
10874                                                X86::GR8RegisterClass);
10875   case X86::ATOMOR8:
10876     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10877                                                X86::OR8ri, X86::MOV8rm,
10878                                                X86::LCMPXCHG8,
10879                                                X86::NOT8r, X86::AL,
10880                                                X86::GR8RegisterClass);
10881   case X86::ATOMXOR8:
10882     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10883                                                X86::XOR8ri, X86::MOV8rm,
10884                                                X86::LCMPXCHG8,
10885                                                X86::NOT8r, X86::AL,
10886                                                X86::GR8RegisterClass);
10887   case X86::ATOMNAND8:
10888     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10889                                                X86::AND8ri, X86::MOV8rm,
10890                                                X86::LCMPXCHG8,
10891                                                X86::NOT8r, X86::AL,
10892                                                X86::GR8RegisterClass, true);
10893   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10894   // This group is for 64-bit host.
10895   case X86::ATOMAND64:
10896     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10897                                                X86::AND64ri32, X86::MOV64rm,
10898                                                X86::LCMPXCHG64,
10899                                                X86::NOT64r, X86::RAX,
10900                                                X86::GR64RegisterClass);
10901   case X86::ATOMOR64:
10902     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10903                                                X86::OR64ri32, X86::MOV64rm,
10904                                                X86::LCMPXCHG64,
10905                                                X86::NOT64r, X86::RAX,
10906                                                X86::GR64RegisterClass);
10907   case X86::ATOMXOR64:
10908     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10909                                                X86::XOR64ri32, X86::MOV64rm,
10910                                                X86::LCMPXCHG64,
10911                                                X86::NOT64r, X86::RAX,
10912                                                X86::GR64RegisterClass);
10913   case X86::ATOMNAND64:
10914     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10915                                                X86::AND64ri32, X86::MOV64rm,
10916                                                X86::LCMPXCHG64,
10917                                                X86::NOT64r, X86::RAX,
10918                                                X86::GR64RegisterClass, true);
10919   case X86::ATOMMIN64:
10920     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10921   case X86::ATOMMAX64:
10922     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10923   case X86::ATOMUMIN64:
10924     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10925   case X86::ATOMUMAX64:
10926     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10927
10928   // This group does 64-bit operations on a 32-bit host.
10929   case X86::ATOMAND6432:
10930     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10931                                                X86::AND32rr, X86::AND32rr,
10932                                                X86::AND32ri, X86::AND32ri,
10933                                                false);
10934   case X86::ATOMOR6432:
10935     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10936                                                X86::OR32rr, X86::OR32rr,
10937                                                X86::OR32ri, X86::OR32ri,
10938                                                false);
10939   case X86::ATOMXOR6432:
10940     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10941                                                X86::XOR32rr, X86::XOR32rr,
10942                                                X86::XOR32ri, X86::XOR32ri,
10943                                                false);
10944   case X86::ATOMNAND6432:
10945     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10946                                                X86::AND32rr, X86::AND32rr,
10947                                                X86::AND32ri, X86::AND32ri,
10948                                                true);
10949   case X86::ATOMADD6432:
10950     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10951                                                X86::ADD32rr, X86::ADC32rr,
10952                                                X86::ADD32ri, X86::ADC32ri,
10953                                                false);
10954   case X86::ATOMSUB6432:
10955     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10956                                                X86::SUB32rr, X86::SBB32rr,
10957                                                X86::SUB32ri, X86::SBB32ri,
10958                                                false);
10959   case X86::ATOMSWAP6432:
10960     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10961                                                X86::MOV32rr, X86::MOV32rr,
10962                                                X86::MOV32ri, X86::MOV32ri,
10963                                                false);
10964   case X86::VASTART_SAVE_XMM_REGS:
10965     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10966
10967   case X86::VAARG_64:
10968     return EmitVAARG64WithCustomInserter(MI, BB);
10969   }
10970 }
10971
10972 //===----------------------------------------------------------------------===//
10973 //                           X86 Optimization Hooks
10974 //===----------------------------------------------------------------------===//
10975
10976 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10977                                                        const APInt &Mask,
10978                                                        APInt &KnownZero,
10979                                                        APInt &KnownOne,
10980                                                        const SelectionDAG &DAG,
10981                                                        unsigned Depth) const {
10982   unsigned Opc = Op.getOpcode();
10983   assert((Opc >= ISD::BUILTIN_OP_END ||
10984           Opc == ISD::INTRINSIC_WO_CHAIN ||
10985           Opc == ISD::INTRINSIC_W_CHAIN ||
10986           Opc == ISD::INTRINSIC_VOID) &&
10987          "Should use MaskedValueIsZero if you don't know whether Op"
10988          " is a target node!");
10989
10990   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10991   switch (Opc) {
10992   default: break;
10993   case X86ISD::ADD:
10994   case X86ISD::SUB:
10995   case X86ISD::ADC:
10996   case X86ISD::SBB:
10997   case X86ISD::SMUL:
10998   case X86ISD::UMUL:
10999   case X86ISD::INC:
11000   case X86ISD::DEC:
11001   case X86ISD::OR:
11002   case X86ISD::XOR:
11003   case X86ISD::AND:
11004     // These nodes' second result is a boolean.
11005     if (Op.getResNo() == 0)
11006       break;
11007     // Fallthrough
11008   case X86ISD::SETCC:
11009     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11010                                        Mask.getBitWidth() - 1);
11011     break;
11012   }
11013 }
11014
11015 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11016                                                          unsigned Depth) const {
11017   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11018   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11019     return Op.getValueType().getScalarType().getSizeInBits();
11020
11021   // Fallback case.
11022   return 1;
11023 }
11024
11025 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11026 /// node is a GlobalAddress + offset.
11027 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11028                                        const GlobalValue* &GA,
11029                                        int64_t &Offset) const {
11030   if (N->getOpcode() == X86ISD::Wrapper) {
11031     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11032       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11033       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11034       return true;
11035     }
11036   }
11037   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11038 }
11039
11040 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11041 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11042 /// if the load addresses are consecutive, non-overlapping, and in the right
11043 /// order.
11044 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11045                                      TargetLowering::DAGCombinerInfo &DCI) {
11046   DebugLoc dl = N->getDebugLoc();
11047   EVT VT = N->getValueType(0);
11048
11049   if (VT.getSizeInBits() != 128)
11050     return SDValue();
11051
11052   // Don't create instructions with illegal types after legalize types has run.
11053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11054   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11055     return SDValue();
11056
11057   SmallVector<SDValue, 16> Elts;
11058   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11059     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11060
11061   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11062 }
11063
11064 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11065 /// generation and convert it from being a bunch of shuffles and extracts
11066 /// to a simple store and scalar loads to extract the elements.
11067 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11068                                                 const TargetLowering &TLI) {
11069   SDValue InputVector = N->getOperand(0);
11070
11071   // Only operate on vectors of 4 elements, where the alternative shuffling
11072   // gets to be more expensive.
11073   if (InputVector.getValueType() != MVT::v4i32)
11074     return SDValue();
11075
11076   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11077   // single use which is a sign-extend or zero-extend, and all elements are
11078   // used.
11079   SmallVector<SDNode *, 4> Uses;
11080   unsigned ExtractedElements = 0;
11081   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11082        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11083     if (UI.getUse().getResNo() != InputVector.getResNo())
11084       return SDValue();
11085
11086     SDNode *Extract = *UI;
11087     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11088       return SDValue();
11089
11090     if (Extract->getValueType(0) != MVT::i32)
11091       return SDValue();
11092     if (!Extract->hasOneUse())
11093       return SDValue();
11094     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11095         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11096       return SDValue();
11097     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11098       return SDValue();
11099
11100     // Record which element was extracted.
11101     ExtractedElements |=
11102       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11103
11104     Uses.push_back(Extract);
11105   }
11106
11107   // If not all the elements were used, this may not be worthwhile.
11108   if (ExtractedElements != 15)
11109     return SDValue();
11110
11111   // Ok, we've now decided to do the transformation.
11112   DebugLoc dl = InputVector.getDebugLoc();
11113
11114   // Store the value to a temporary stack slot.
11115   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11116   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11117                             MachinePointerInfo(), false, false, 0);
11118
11119   // Replace each use (extract) with a load of the appropriate element.
11120   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11121        UE = Uses.end(); UI != UE; ++UI) {
11122     SDNode *Extract = *UI;
11123
11124     // cOMpute the element's address.
11125     SDValue Idx = Extract->getOperand(1);
11126     unsigned EltSize =
11127         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11128     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11129     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11130
11131     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11132                                      StackPtr, OffsetVal);
11133
11134     // Load the scalar.
11135     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11136                                      ScalarAddr, MachinePointerInfo(),
11137                                      false, false, 0);
11138
11139     // Replace the exact with the load.
11140     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11141   }
11142
11143   // The replacement was made in place; don't return anything.
11144   return SDValue();
11145 }
11146
11147 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11148 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11149                                     const X86Subtarget *Subtarget) {
11150   DebugLoc DL = N->getDebugLoc();
11151   SDValue Cond = N->getOperand(0);
11152   // Get the LHS/RHS of the select.
11153   SDValue LHS = N->getOperand(1);
11154   SDValue RHS = N->getOperand(2);
11155
11156   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11157   // instructions match the semantics of the common C idiom x<y?x:y but not
11158   // x<=y?x:y, because of how they handle negative zero (which can be
11159   // ignored in unsafe-math mode).
11160   if (Subtarget->hasSSE2() &&
11161       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11162       Cond.getOpcode() == ISD::SETCC) {
11163     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11164
11165     unsigned Opcode = 0;
11166     // Check for x CC y ? x : y.
11167     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11168         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11169       switch (CC) {
11170       default: break;
11171       case ISD::SETULT:
11172         // Converting this to a min would handle NaNs incorrectly, and swapping
11173         // the operands would cause it to handle comparisons between positive
11174         // and negative zero incorrectly.
11175         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11176           if (!UnsafeFPMath &&
11177               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11178             break;
11179           std::swap(LHS, RHS);
11180         }
11181         Opcode = X86ISD::FMIN;
11182         break;
11183       case ISD::SETOLE:
11184         // Converting this to a min would handle comparisons between positive
11185         // and negative zero incorrectly.
11186         if (!UnsafeFPMath &&
11187             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11188           break;
11189         Opcode = X86ISD::FMIN;
11190         break;
11191       case ISD::SETULE:
11192         // Converting this to a min would handle both negative zeros and NaNs
11193         // incorrectly, but we can swap the operands to fix both.
11194         std::swap(LHS, RHS);
11195       case ISD::SETOLT:
11196       case ISD::SETLT:
11197       case ISD::SETLE:
11198         Opcode = X86ISD::FMIN;
11199         break;
11200
11201       case ISD::SETOGE:
11202         // Converting this to a max would handle comparisons between positive
11203         // and negative zero incorrectly.
11204         if (!UnsafeFPMath &&
11205             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11206           break;
11207         Opcode = X86ISD::FMAX;
11208         break;
11209       case ISD::SETUGT:
11210         // Converting this to a max would handle NaNs incorrectly, and swapping
11211         // the operands would cause it to handle comparisons between positive
11212         // and negative zero incorrectly.
11213         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11214           if (!UnsafeFPMath &&
11215               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11216             break;
11217           std::swap(LHS, RHS);
11218         }
11219         Opcode = X86ISD::FMAX;
11220         break;
11221       case ISD::SETUGE:
11222         // Converting this to a max would handle both negative zeros and NaNs
11223         // incorrectly, but we can swap the operands to fix both.
11224         std::swap(LHS, RHS);
11225       case ISD::SETOGT:
11226       case ISD::SETGT:
11227       case ISD::SETGE:
11228         Opcode = X86ISD::FMAX;
11229         break;
11230       }
11231     // Check for x CC y ? y : x -- a min/max with reversed arms.
11232     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11233                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11234       switch (CC) {
11235       default: break;
11236       case ISD::SETOGE:
11237         // Converting this to a min would handle comparisons between positive
11238         // and negative zero incorrectly, and swapping the operands would
11239         // cause it to handle NaNs incorrectly.
11240         if (!UnsafeFPMath &&
11241             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11242           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11243             break;
11244           std::swap(LHS, RHS);
11245         }
11246         Opcode = X86ISD::FMIN;
11247         break;
11248       case ISD::SETUGT:
11249         // Converting this to a min would handle NaNs incorrectly.
11250         if (!UnsafeFPMath &&
11251             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11252           break;
11253         Opcode = X86ISD::FMIN;
11254         break;
11255       case ISD::SETUGE:
11256         // Converting this to a min would handle both negative zeros and NaNs
11257         // incorrectly, but we can swap the operands to fix both.
11258         std::swap(LHS, RHS);
11259       case ISD::SETOGT:
11260       case ISD::SETGT:
11261       case ISD::SETGE:
11262         Opcode = X86ISD::FMIN;
11263         break;
11264
11265       case ISD::SETULT:
11266         // Converting this to a max would handle NaNs incorrectly.
11267         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11268           break;
11269         Opcode = X86ISD::FMAX;
11270         break;
11271       case ISD::SETOLE:
11272         // Converting this to a max would handle comparisons between positive
11273         // and negative zero incorrectly, and swapping the operands would
11274         // cause it to handle NaNs incorrectly.
11275         if (!UnsafeFPMath &&
11276             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11277           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11278             break;
11279           std::swap(LHS, RHS);
11280         }
11281         Opcode = X86ISD::FMAX;
11282         break;
11283       case ISD::SETULE:
11284         // Converting this to a max would handle both negative zeros and NaNs
11285         // incorrectly, but we can swap the operands to fix both.
11286         std::swap(LHS, RHS);
11287       case ISD::SETOLT:
11288       case ISD::SETLT:
11289       case ISD::SETLE:
11290         Opcode = X86ISD::FMAX;
11291         break;
11292       }
11293     }
11294
11295     if (Opcode)
11296       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11297   }
11298
11299   // If this is a select between two integer constants, try to do some
11300   // optimizations.
11301   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11302     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11303       // Don't do this for crazy integer types.
11304       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11305         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11306         // so that TrueC (the true value) is larger than FalseC.
11307         bool NeedsCondInvert = false;
11308
11309         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11310             // Efficiently invertible.
11311             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11312              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11313               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11314           NeedsCondInvert = true;
11315           std::swap(TrueC, FalseC);
11316         }
11317
11318         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11319         if (FalseC->getAPIntValue() == 0 &&
11320             TrueC->getAPIntValue().isPowerOf2()) {
11321           if (NeedsCondInvert) // Invert the condition if needed.
11322             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11323                                DAG.getConstant(1, Cond.getValueType()));
11324
11325           // Zero extend the condition if needed.
11326           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11327
11328           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11329           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11330                              DAG.getConstant(ShAmt, MVT::i8));
11331         }
11332
11333         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11334         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11335           if (NeedsCondInvert) // Invert the condition if needed.
11336             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11337                                DAG.getConstant(1, Cond.getValueType()));
11338
11339           // Zero extend the condition if needed.
11340           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11341                              FalseC->getValueType(0), Cond);
11342           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11343                              SDValue(FalseC, 0));
11344         }
11345
11346         // Optimize cases that will turn into an LEA instruction.  This requires
11347         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11348         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11349           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11350           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11351
11352           bool isFastMultiplier = false;
11353           if (Diff < 10) {
11354             switch ((unsigned char)Diff) {
11355               default: break;
11356               case 1:  // result = add base, cond
11357               case 2:  // result = lea base(    , cond*2)
11358               case 3:  // result = lea base(cond, cond*2)
11359               case 4:  // result = lea base(    , cond*4)
11360               case 5:  // result = lea base(cond, cond*4)
11361               case 8:  // result = lea base(    , cond*8)
11362               case 9:  // result = lea base(cond, cond*8)
11363                 isFastMultiplier = true;
11364                 break;
11365             }
11366           }
11367
11368           if (isFastMultiplier) {
11369             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11370             if (NeedsCondInvert) // Invert the condition if needed.
11371               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11372                                  DAG.getConstant(1, Cond.getValueType()));
11373
11374             // Zero extend the condition if needed.
11375             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11376                                Cond);
11377             // Scale the condition by the difference.
11378             if (Diff != 1)
11379               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11380                                  DAG.getConstant(Diff, Cond.getValueType()));
11381
11382             // Add the base if non-zero.
11383             if (FalseC->getAPIntValue() != 0)
11384               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11385                                  SDValue(FalseC, 0));
11386             return Cond;
11387           }
11388         }
11389       }
11390   }
11391
11392   return SDValue();
11393 }
11394
11395 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11396 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11397                                   TargetLowering::DAGCombinerInfo &DCI) {
11398   DebugLoc DL = N->getDebugLoc();
11399
11400   // If the flag operand isn't dead, don't touch this CMOV.
11401   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11402     return SDValue();
11403
11404   SDValue FalseOp = N->getOperand(0);
11405   SDValue TrueOp = N->getOperand(1);
11406   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11407   SDValue Cond = N->getOperand(3);
11408   if (CC == X86::COND_E || CC == X86::COND_NE) {
11409     switch (Cond.getOpcode()) {
11410     default: break;
11411     case X86ISD::BSR:
11412     case X86ISD::BSF:
11413       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11414       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11415         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11416     }
11417   }
11418
11419   // If this is a select between two integer constants, try to do some
11420   // optimizations.  Note that the operands are ordered the opposite of SELECT
11421   // operands.
11422   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11423     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11424       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11425       // larger than FalseC (the false value).
11426       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11427         CC = X86::GetOppositeBranchCondition(CC);
11428         std::swap(TrueC, FalseC);
11429       }
11430
11431       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11432       // This is efficient for any integer data type (including i8/i16) and
11433       // shift amount.
11434       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11435         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11436                            DAG.getConstant(CC, MVT::i8), Cond);
11437
11438         // Zero extend the condition if needed.
11439         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11440
11441         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11442         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11443                            DAG.getConstant(ShAmt, MVT::i8));
11444         if (N->getNumValues() == 2)  // Dead flag value?
11445           return DCI.CombineTo(N, Cond, SDValue());
11446         return Cond;
11447       }
11448
11449       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11450       // for any integer data type, including i8/i16.
11451       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11452         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11453                            DAG.getConstant(CC, MVT::i8), Cond);
11454
11455         // Zero extend the condition if needed.
11456         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11457                            FalseC->getValueType(0), Cond);
11458         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11459                            SDValue(FalseC, 0));
11460
11461         if (N->getNumValues() == 2)  // Dead flag value?
11462           return DCI.CombineTo(N, Cond, SDValue());
11463         return Cond;
11464       }
11465
11466       // Optimize cases that will turn into an LEA instruction.  This requires
11467       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11468       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11469         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11470         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11471
11472         bool isFastMultiplier = false;
11473         if (Diff < 10) {
11474           switch ((unsigned char)Diff) {
11475           default: break;
11476           case 1:  // result = add base, cond
11477           case 2:  // result = lea base(    , cond*2)
11478           case 3:  // result = lea base(cond, cond*2)
11479           case 4:  // result = lea base(    , cond*4)
11480           case 5:  // result = lea base(cond, cond*4)
11481           case 8:  // result = lea base(    , cond*8)
11482           case 9:  // result = lea base(cond, cond*8)
11483             isFastMultiplier = true;
11484             break;
11485           }
11486         }
11487
11488         if (isFastMultiplier) {
11489           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11490           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11491                              DAG.getConstant(CC, MVT::i8), Cond);
11492           // Zero extend the condition if needed.
11493           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11494                              Cond);
11495           // Scale the condition by the difference.
11496           if (Diff != 1)
11497             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11498                                DAG.getConstant(Diff, Cond.getValueType()));
11499
11500           // Add the base if non-zero.
11501           if (FalseC->getAPIntValue() != 0)
11502             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11503                                SDValue(FalseC, 0));
11504           if (N->getNumValues() == 2)  // Dead flag value?
11505             return DCI.CombineTo(N, Cond, SDValue());
11506           return Cond;
11507         }
11508       }
11509     }
11510   }
11511   return SDValue();
11512 }
11513
11514
11515 /// PerformMulCombine - Optimize a single multiply with constant into two
11516 /// in order to implement it with two cheaper instructions, e.g.
11517 /// LEA + SHL, LEA + LEA.
11518 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11519                                  TargetLowering::DAGCombinerInfo &DCI) {
11520   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11521     return SDValue();
11522
11523   EVT VT = N->getValueType(0);
11524   if (VT != MVT::i64)
11525     return SDValue();
11526
11527   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11528   if (!C)
11529     return SDValue();
11530   uint64_t MulAmt = C->getZExtValue();
11531   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11532     return SDValue();
11533
11534   uint64_t MulAmt1 = 0;
11535   uint64_t MulAmt2 = 0;
11536   if ((MulAmt % 9) == 0) {
11537     MulAmt1 = 9;
11538     MulAmt2 = MulAmt / 9;
11539   } else if ((MulAmt % 5) == 0) {
11540     MulAmt1 = 5;
11541     MulAmt2 = MulAmt / 5;
11542   } else if ((MulAmt % 3) == 0) {
11543     MulAmt1 = 3;
11544     MulAmt2 = MulAmt / 3;
11545   }
11546   if (MulAmt2 &&
11547       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11548     DebugLoc DL = N->getDebugLoc();
11549
11550     if (isPowerOf2_64(MulAmt2) &&
11551         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11552       // If second multiplifer is pow2, issue it first. We want the multiply by
11553       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11554       // is an add.
11555       std::swap(MulAmt1, MulAmt2);
11556
11557     SDValue NewMul;
11558     if (isPowerOf2_64(MulAmt1))
11559       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11560                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11561     else
11562       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11563                            DAG.getConstant(MulAmt1, VT));
11564
11565     if (isPowerOf2_64(MulAmt2))
11566       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11567                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11568     else
11569       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11570                            DAG.getConstant(MulAmt2, VT));
11571
11572     // Do not add new nodes to DAG combiner worklist.
11573     DCI.CombineTo(N, NewMul, false);
11574   }
11575   return SDValue();
11576 }
11577
11578 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11579   SDValue N0 = N->getOperand(0);
11580   SDValue N1 = N->getOperand(1);
11581   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11582   EVT VT = N0.getValueType();
11583
11584   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11585   // since the result of setcc_c is all zero's or all ones.
11586   if (N1C && N0.getOpcode() == ISD::AND &&
11587       N0.getOperand(1).getOpcode() == ISD::Constant) {
11588     SDValue N00 = N0.getOperand(0);
11589     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11590         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11591           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11592          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11593       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11594       APInt ShAmt = N1C->getAPIntValue();
11595       Mask = Mask.shl(ShAmt);
11596       if (Mask != 0)
11597         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11598                            N00, DAG.getConstant(Mask, VT));
11599     }
11600   }
11601
11602   return SDValue();
11603 }
11604
11605 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11606 ///                       when possible.
11607 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11608                                    const X86Subtarget *Subtarget) {
11609   EVT VT = N->getValueType(0);
11610   if (!VT.isVector() && VT.isInteger() &&
11611       N->getOpcode() == ISD::SHL)
11612     return PerformSHLCombine(N, DAG);
11613
11614   // On X86 with SSE2 support, we can transform this to a vector shift if
11615   // all elements are shifted by the same amount.  We can't do this in legalize
11616   // because the a constant vector is typically transformed to a constant pool
11617   // so we have no knowledge of the shift amount.
11618   if (!Subtarget->hasSSE2())
11619     return SDValue();
11620
11621   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11622     return SDValue();
11623
11624   SDValue ShAmtOp = N->getOperand(1);
11625   EVT EltVT = VT.getVectorElementType();
11626   DebugLoc DL = N->getDebugLoc();
11627   SDValue BaseShAmt = SDValue();
11628   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11629     unsigned NumElts = VT.getVectorNumElements();
11630     unsigned i = 0;
11631     for (; i != NumElts; ++i) {
11632       SDValue Arg = ShAmtOp.getOperand(i);
11633       if (Arg.getOpcode() == ISD::UNDEF) continue;
11634       BaseShAmt = Arg;
11635       break;
11636     }
11637     for (; i != NumElts; ++i) {
11638       SDValue Arg = ShAmtOp.getOperand(i);
11639       if (Arg.getOpcode() == ISD::UNDEF) continue;
11640       if (Arg != BaseShAmt) {
11641         return SDValue();
11642       }
11643     }
11644   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11645              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11646     SDValue InVec = ShAmtOp.getOperand(0);
11647     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11648       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11649       unsigned i = 0;
11650       for (; i != NumElts; ++i) {
11651         SDValue Arg = InVec.getOperand(i);
11652         if (Arg.getOpcode() == ISD::UNDEF) continue;
11653         BaseShAmt = Arg;
11654         break;
11655       }
11656     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11657        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11658          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11659          if (C->getZExtValue() == SplatIdx)
11660            BaseShAmt = InVec.getOperand(1);
11661        }
11662     }
11663     if (BaseShAmt.getNode() == 0)
11664       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11665                               DAG.getIntPtrConstant(0));
11666   } else
11667     return SDValue();
11668
11669   // The shift amount is an i32.
11670   if (EltVT.bitsGT(MVT::i32))
11671     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11672   else if (EltVT.bitsLT(MVT::i32))
11673     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11674
11675   // The shift amount is identical so we can do a vector shift.
11676   SDValue  ValOp = N->getOperand(0);
11677   switch (N->getOpcode()) {
11678   default:
11679     llvm_unreachable("Unknown shift opcode!");
11680     break;
11681   case ISD::SHL:
11682     if (VT == MVT::v2i64)
11683       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11684                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11685                          ValOp, BaseShAmt);
11686     if (VT == MVT::v4i32)
11687       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11688                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11689                          ValOp, BaseShAmt);
11690     if (VT == MVT::v8i16)
11691       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11692                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11693                          ValOp, BaseShAmt);
11694     break;
11695   case ISD::SRA:
11696     if (VT == MVT::v4i32)
11697       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11698                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11699                          ValOp, BaseShAmt);
11700     if (VT == MVT::v8i16)
11701       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11702                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11703                          ValOp, BaseShAmt);
11704     break;
11705   case ISD::SRL:
11706     if (VT == MVT::v2i64)
11707       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11708                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11709                          ValOp, BaseShAmt);
11710     if (VT == MVT::v4i32)
11711       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11712                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11713                          ValOp, BaseShAmt);
11714     if (VT ==  MVT::v8i16)
11715       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11716                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11717                          ValOp, BaseShAmt);
11718     break;
11719   }
11720   return SDValue();
11721 }
11722
11723
11724 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11725 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11726 // and friends.  Likewise for OR -> CMPNEQSS.
11727 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11728                             TargetLowering::DAGCombinerInfo &DCI,
11729                             const X86Subtarget *Subtarget) {
11730   unsigned opcode;
11731
11732   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11733   // we're requiring SSE2 for both.
11734   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11735     SDValue N0 = N->getOperand(0);
11736     SDValue N1 = N->getOperand(1);
11737     SDValue CMP0 = N0->getOperand(1);
11738     SDValue CMP1 = N1->getOperand(1);
11739     DebugLoc DL = N->getDebugLoc();
11740
11741     // The SETCCs should both refer to the same CMP.
11742     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11743       return SDValue();
11744
11745     SDValue CMP00 = CMP0->getOperand(0);
11746     SDValue CMP01 = CMP0->getOperand(1);
11747     EVT     VT    = CMP00.getValueType();
11748
11749     if (VT == MVT::f32 || VT == MVT::f64) {
11750       bool ExpectingFlags = false;
11751       // Check for any users that want flags:
11752       for (SDNode::use_iterator UI = N->use_begin(),
11753              UE = N->use_end();
11754            !ExpectingFlags && UI != UE; ++UI)
11755         switch (UI->getOpcode()) {
11756         default:
11757         case ISD::BR_CC:
11758         case ISD::BRCOND:
11759         case ISD::SELECT:
11760           ExpectingFlags = true;
11761           break;
11762         case ISD::CopyToReg:
11763         case ISD::SIGN_EXTEND:
11764         case ISD::ZERO_EXTEND:
11765         case ISD::ANY_EXTEND:
11766           break;
11767         }
11768
11769       if (!ExpectingFlags) {
11770         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11771         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11772
11773         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11774           X86::CondCode tmp = cc0;
11775           cc0 = cc1;
11776           cc1 = tmp;
11777         }
11778
11779         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11780             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11781           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11782           X86ISD::NodeType NTOperator = is64BitFP ?
11783             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11784           // FIXME: need symbolic constants for these magic numbers.
11785           // See X86ATTInstPrinter.cpp:printSSECC().
11786           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11787           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11788                                               DAG.getConstant(x86cc, MVT::i8));
11789           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11790                                               OnesOrZeroesF);
11791           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11792                                       DAG.getConstant(1, MVT::i32));
11793           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11794           return OneBitOfTruth;
11795         }
11796       }
11797     }
11798   }
11799   return SDValue();
11800 }
11801
11802 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11803                                  TargetLowering::DAGCombinerInfo &DCI,
11804                                  const X86Subtarget *Subtarget) {
11805   if (DCI.isBeforeLegalizeOps())
11806     return SDValue();
11807
11808   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11809   if (R.getNode())
11810     return R;
11811
11812   // Want to form PANDN nodes, in the hopes of then easily combining them with
11813   // OR and AND nodes to form PBLEND/PSIGN.
11814   EVT VT = N->getValueType(0);
11815   if (VT != MVT::v2i64)
11816     return SDValue();
11817
11818   SDValue N0 = N->getOperand(0);
11819   SDValue N1 = N->getOperand(1);
11820   DebugLoc DL = N->getDebugLoc();
11821
11822   // Check LHS for vnot
11823   if (N0.getOpcode() == ISD::XOR &&
11824       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11825     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11826
11827   // Check RHS for vnot
11828   if (N1.getOpcode() == ISD::XOR &&
11829       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11830     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11831
11832   return SDValue();
11833 }
11834
11835 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11836                                 TargetLowering::DAGCombinerInfo &DCI,
11837                                 const X86Subtarget *Subtarget) {
11838   if (DCI.isBeforeLegalizeOps())
11839     return SDValue();
11840
11841   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11842   if (R.getNode())
11843     return R;
11844
11845   EVT VT = N->getValueType(0);
11846   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11847     return SDValue();
11848
11849   SDValue N0 = N->getOperand(0);
11850   SDValue N1 = N->getOperand(1);
11851
11852   // look for psign/blend
11853   if (Subtarget->hasSSSE3()) {
11854     if (VT == MVT::v2i64) {
11855       // Canonicalize pandn to RHS
11856       if (N0.getOpcode() == X86ISD::PANDN)
11857         std::swap(N0, N1);
11858       // or (and (m, x), (pandn m, y))
11859       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11860         SDValue Mask = N1.getOperand(0);
11861         SDValue X    = N1.getOperand(1);
11862         SDValue Y;
11863         if (N0.getOperand(0) == Mask)
11864           Y = N0.getOperand(1);
11865         if (N0.getOperand(1) == Mask)
11866           Y = N0.getOperand(0);
11867
11868         // Check to see if the mask appeared in both the AND and PANDN and
11869         if (!Y.getNode())
11870           return SDValue();
11871
11872         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11873         if (Mask.getOpcode() != ISD::BITCAST ||
11874             X.getOpcode() != ISD::BITCAST ||
11875             Y.getOpcode() != ISD::BITCAST)
11876           return SDValue();
11877
11878         // Look through mask bitcast.
11879         Mask = Mask.getOperand(0);
11880         EVT MaskVT = Mask.getValueType();
11881
11882         // Validate that the Mask operand is a vector sra node.  The sra node
11883         // will be an intrinsic.
11884         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11885           return SDValue();
11886
11887         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11888         // there is no psrai.b
11889         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11890         case Intrinsic::x86_sse2_psrai_w:
11891         case Intrinsic::x86_sse2_psrai_d:
11892           break;
11893         default: return SDValue();
11894         }
11895
11896         // Check that the SRA is all signbits.
11897         SDValue SraC = Mask.getOperand(2);
11898         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11899         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11900         if ((SraAmt + 1) != EltBits)
11901           return SDValue();
11902
11903         DebugLoc DL = N->getDebugLoc();
11904
11905         // Now we know we at least have a plendvb with the mask val.  See if
11906         // we can form a psignb/w/d.
11907         // psign = x.type == y.type == mask.type && y = sub(0, x);
11908         X = X.getOperand(0);
11909         Y = Y.getOperand(0);
11910         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11911             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11912             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11913           unsigned Opc = 0;
11914           switch (EltBits) {
11915           case 8: Opc = X86ISD::PSIGNB; break;
11916           case 16: Opc = X86ISD::PSIGNW; break;
11917           case 32: Opc = X86ISD::PSIGND; break;
11918           default: break;
11919           }
11920           if (Opc) {
11921             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11922             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11923           }
11924         }
11925         // PBLENDVB only available on SSE 4.1
11926         if (!Subtarget->hasSSE41())
11927           return SDValue();
11928
11929         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11930         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11931         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11932         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11933         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11934       }
11935     }
11936   }
11937
11938   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11939   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11940     std::swap(N0, N1);
11941   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11942     return SDValue();
11943   if (!N0.hasOneUse() || !N1.hasOneUse())
11944     return SDValue();
11945
11946   SDValue ShAmt0 = N0.getOperand(1);
11947   if (ShAmt0.getValueType() != MVT::i8)
11948     return SDValue();
11949   SDValue ShAmt1 = N1.getOperand(1);
11950   if (ShAmt1.getValueType() != MVT::i8)
11951     return SDValue();
11952   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11953     ShAmt0 = ShAmt0.getOperand(0);
11954   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11955     ShAmt1 = ShAmt1.getOperand(0);
11956
11957   DebugLoc DL = N->getDebugLoc();
11958   unsigned Opc = X86ISD::SHLD;
11959   SDValue Op0 = N0.getOperand(0);
11960   SDValue Op1 = N1.getOperand(0);
11961   if (ShAmt0.getOpcode() == ISD::SUB) {
11962     Opc = X86ISD::SHRD;
11963     std::swap(Op0, Op1);
11964     std::swap(ShAmt0, ShAmt1);
11965   }
11966
11967   unsigned Bits = VT.getSizeInBits();
11968   if (ShAmt1.getOpcode() == ISD::SUB) {
11969     SDValue Sum = ShAmt1.getOperand(0);
11970     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11971       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11972       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11973         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11974       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11975         return DAG.getNode(Opc, DL, VT,
11976                            Op0, Op1,
11977                            DAG.getNode(ISD::TRUNCATE, DL,
11978                                        MVT::i8, ShAmt0));
11979     }
11980   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11981     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11982     if (ShAmt0C &&
11983         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11984       return DAG.getNode(Opc, DL, VT,
11985                          N0.getOperand(0), N1.getOperand(0),
11986                          DAG.getNode(ISD::TRUNCATE, DL,
11987                                        MVT::i8, ShAmt0));
11988   }
11989
11990   return SDValue();
11991 }
11992
11993 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11994 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11995                                    const X86Subtarget *Subtarget) {
11996   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11997   // the FP state in cases where an emms may be missing.
11998   // A preferable solution to the general problem is to figure out the right
11999   // places to insert EMMS.  This qualifies as a quick hack.
12000
12001   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12002   StoreSDNode *St = cast<StoreSDNode>(N);
12003   EVT VT = St->getValue().getValueType();
12004   if (VT.getSizeInBits() != 64)
12005     return SDValue();
12006
12007   const Function *F = DAG.getMachineFunction().getFunction();
12008   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12009   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12010     && Subtarget->hasSSE2();
12011   if ((VT.isVector() ||
12012        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12013       isa<LoadSDNode>(St->getValue()) &&
12014       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12015       St->getChain().hasOneUse() && !St->isVolatile()) {
12016     SDNode* LdVal = St->getValue().getNode();
12017     LoadSDNode *Ld = 0;
12018     int TokenFactorIndex = -1;
12019     SmallVector<SDValue, 8> Ops;
12020     SDNode* ChainVal = St->getChain().getNode();
12021     // Must be a store of a load.  We currently handle two cases:  the load
12022     // is a direct child, and it's under an intervening TokenFactor.  It is
12023     // possible to dig deeper under nested TokenFactors.
12024     if (ChainVal == LdVal)
12025       Ld = cast<LoadSDNode>(St->getChain());
12026     else if (St->getValue().hasOneUse() &&
12027              ChainVal->getOpcode() == ISD::TokenFactor) {
12028       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12029         if (ChainVal->getOperand(i).getNode() == LdVal) {
12030           TokenFactorIndex = i;
12031           Ld = cast<LoadSDNode>(St->getValue());
12032         } else
12033           Ops.push_back(ChainVal->getOperand(i));
12034       }
12035     }
12036
12037     if (!Ld || !ISD::isNormalLoad(Ld))
12038       return SDValue();
12039
12040     // If this is not the MMX case, i.e. we are just turning i64 load/store
12041     // into f64 load/store, avoid the transformation if there are multiple
12042     // uses of the loaded value.
12043     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12044       return SDValue();
12045
12046     DebugLoc LdDL = Ld->getDebugLoc();
12047     DebugLoc StDL = N->getDebugLoc();
12048     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12049     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12050     // pair instead.
12051     if (Subtarget->is64Bit() || F64IsLegal) {
12052       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12053       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12054                                   Ld->getPointerInfo(), Ld->isVolatile(),
12055                                   Ld->isNonTemporal(), Ld->getAlignment());
12056       SDValue NewChain = NewLd.getValue(1);
12057       if (TokenFactorIndex != -1) {
12058         Ops.push_back(NewChain);
12059         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12060                                Ops.size());
12061       }
12062       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12063                           St->getPointerInfo(),
12064                           St->isVolatile(), St->isNonTemporal(),
12065                           St->getAlignment());
12066     }
12067
12068     // Otherwise, lower to two pairs of 32-bit loads / stores.
12069     SDValue LoAddr = Ld->getBasePtr();
12070     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12071                                  DAG.getConstant(4, MVT::i32));
12072
12073     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12074                                Ld->getPointerInfo(),
12075                                Ld->isVolatile(), Ld->isNonTemporal(),
12076                                Ld->getAlignment());
12077     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12078                                Ld->getPointerInfo().getWithOffset(4),
12079                                Ld->isVolatile(), Ld->isNonTemporal(),
12080                                MinAlign(Ld->getAlignment(), 4));
12081
12082     SDValue NewChain = LoLd.getValue(1);
12083     if (TokenFactorIndex != -1) {
12084       Ops.push_back(LoLd);
12085       Ops.push_back(HiLd);
12086       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12087                              Ops.size());
12088     }
12089
12090     LoAddr = St->getBasePtr();
12091     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12092                          DAG.getConstant(4, MVT::i32));
12093
12094     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12095                                 St->getPointerInfo(),
12096                                 St->isVolatile(), St->isNonTemporal(),
12097                                 St->getAlignment());
12098     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12099                                 St->getPointerInfo().getWithOffset(4),
12100                                 St->isVolatile(),
12101                                 St->isNonTemporal(),
12102                                 MinAlign(St->getAlignment(), 4));
12103     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12104   }
12105   return SDValue();
12106 }
12107
12108 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12109 /// X86ISD::FXOR nodes.
12110 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12111   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12112   // F[X]OR(0.0, x) -> x
12113   // F[X]OR(x, 0.0) -> x
12114   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12115     if (C->getValueAPF().isPosZero())
12116       return N->getOperand(1);
12117   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12118     if (C->getValueAPF().isPosZero())
12119       return N->getOperand(0);
12120   return SDValue();
12121 }
12122
12123 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12124 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12125   // FAND(0.0, x) -> 0.0
12126   // FAND(x, 0.0) -> 0.0
12127   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12128     if (C->getValueAPF().isPosZero())
12129       return N->getOperand(0);
12130   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12131     if (C->getValueAPF().isPosZero())
12132       return N->getOperand(1);
12133   return SDValue();
12134 }
12135
12136 static SDValue PerformBTCombine(SDNode *N,
12137                                 SelectionDAG &DAG,
12138                                 TargetLowering::DAGCombinerInfo &DCI) {
12139   // BT ignores high bits in the bit index operand.
12140   SDValue Op1 = N->getOperand(1);
12141   if (Op1.hasOneUse()) {
12142     unsigned BitWidth = Op1.getValueSizeInBits();
12143     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12144     APInt KnownZero, KnownOne;
12145     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12146                                           !DCI.isBeforeLegalizeOps());
12147     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12148     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12149         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12150       DCI.CommitTargetLoweringOpt(TLO);
12151   }
12152   return SDValue();
12153 }
12154
12155 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12156   SDValue Op = N->getOperand(0);
12157   if (Op.getOpcode() == ISD::BITCAST)
12158     Op = Op.getOperand(0);
12159   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12160   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12161       VT.getVectorElementType().getSizeInBits() ==
12162       OpVT.getVectorElementType().getSizeInBits()) {
12163     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12164   }
12165   return SDValue();
12166 }
12167
12168 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12169   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12170   //           (and (i32 x86isd::setcc_carry), 1)
12171   // This eliminates the zext. This transformation is necessary because
12172   // ISD::SETCC is always legalized to i8.
12173   DebugLoc dl = N->getDebugLoc();
12174   SDValue N0 = N->getOperand(0);
12175   EVT VT = N->getValueType(0);
12176   if (N0.getOpcode() == ISD::AND &&
12177       N0.hasOneUse() &&
12178       N0.getOperand(0).hasOneUse()) {
12179     SDValue N00 = N0.getOperand(0);
12180     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12181       return SDValue();
12182     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12183     if (!C || C->getZExtValue() != 1)
12184       return SDValue();
12185     return DAG.getNode(ISD::AND, dl, VT,
12186                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12187                                    N00.getOperand(0), N00.getOperand(1)),
12188                        DAG.getConstant(1, VT));
12189   }
12190
12191   return SDValue();
12192 }
12193
12194 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12195 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12196   unsigned X86CC = N->getConstantOperandVal(0);
12197   SDValue EFLAG = N->getOperand(1);
12198   DebugLoc DL = N->getDebugLoc();
12199
12200   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12201   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12202   // cases.
12203   if (X86CC == X86::COND_B)
12204     return DAG.getNode(ISD::AND, DL, MVT::i8,
12205                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12206                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12207                        DAG.getConstant(1, MVT::i8));
12208
12209   return SDValue();
12210 }
12211
12212 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12213                                         const X86TargetLowering *XTLI) {
12214   SDValue Op0 = N->getOperand(0);
12215   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12216   // a 32-bit target where SSE doesn't support i64->FP operations.
12217   if (Op0.getOpcode() == ISD::LOAD) {
12218     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12219     EVT VT = Ld->getValueType(0);
12220     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12221         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12222         !XTLI->getSubtarget()->is64Bit() &&
12223         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12224       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12225                                           Ld->getChain(), Op0, DAG);
12226       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12227       return FILDChain;
12228     }
12229   }
12230   return SDValue();
12231 }
12232
12233 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12234 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12235                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12236   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12237   // the result is either zero or one (depending on the input carry bit).
12238   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12239   if (X86::isZeroNode(N->getOperand(0)) &&
12240       X86::isZeroNode(N->getOperand(1)) &&
12241       // We don't have a good way to replace an EFLAGS use, so only do this when
12242       // dead right now.
12243       SDValue(N, 1).use_empty()) {
12244     DebugLoc DL = N->getDebugLoc();
12245     EVT VT = N->getValueType(0);
12246     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12247     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12248                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12249                                            DAG.getConstant(X86::COND_B,MVT::i8),
12250                                            N->getOperand(2)),
12251                                DAG.getConstant(1, VT));
12252     return DCI.CombineTo(N, Res1, CarryOut);
12253   }
12254
12255   return SDValue();
12256 }
12257
12258 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12259 //      (add Y, (setne X, 0)) -> sbb -1, Y
12260 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12261 //      (sub (setne X, 0), Y) -> adc -1, Y
12262 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12263   DebugLoc DL = N->getDebugLoc();
12264
12265   // Look through ZExts.
12266   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12267   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12268     return SDValue();
12269
12270   SDValue SetCC = Ext.getOperand(0);
12271   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12272     return SDValue();
12273
12274   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12275   if (CC != X86::COND_E && CC != X86::COND_NE)
12276     return SDValue();
12277
12278   SDValue Cmp = SetCC.getOperand(1);
12279   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12280       !X86::isZeroNode(Cmp.getOperand(1)) ||
12281       !Cmp.getOperand(0).getValueType().isInteger())
12282     return SDValue();
12283
12284   SDValue CmpOp0 = Cmp.getOperand(0);
12285   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12286                                DAG.getConstant(1, CmpOp0.getValueType()));
12287
12288   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12289   if (CC == X86::COND_NE)
12290     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12291                        DL, OtherVal.getValueType(), OtherVal,
12292                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12293   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12294                      DL, OtherVal.getValueType(), OtherVal,
12295                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12296 }
12297
12298 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12299                                              DAGCombinerInfo &DCI) const {
12300   SelectionDAG &DAG = DCI.DAG;
12301   switch (N->getOpcode()) {
12302   default: break;
12303   case ISD::EXTRACT_VECTOR_ELT:
12304     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12305   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12306   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12307   case ISD::ADD:
12308   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12309   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12310   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12311   case ISD::SHL:
12312   case ISD::SRA:
12313   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12314   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12315   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12316   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12317   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12318   case X86ISD::FXOR:
12319   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12320   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12321   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12322   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12323   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12324   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12325   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12326   case X86ISD::SHUFPD:
12327   case X86ISD::PALIGN:
12328   case X86ISD::PUNPCKHBW:
12329   case X86ISD::PUNPCKHWD:
12330   case X86ISD::PUNPCKHDQ:
12331   case X86ISD::PUNPCKHQDQ:
12332   case X86ISD::UNPCKHPS:
12333   case X86ISD::UNPCKHPD:
12334   case X86ISD::PUNPCKLBW:
12335   case X86ISD::PUNPCKLWD:
12336   case X86ISD::PUNPCKLDQ:
12337   case X86ISD::PUNPCKLQDQ:
12338   case X86ISD::UNPCKLPS:
12339   case X86ISD::UNPCKLPD:
12340   case X86ISD::VUNPCKLPS:
12341   case X86ISD::VUNPCKLPD:
12342   case X86ISD::VUNPCKLPSY:
12343   case X86ISD::VUNPCKLPDY:
12344   case X86ISD::MOVHLPS:
12345   case X86ISD::MOVLHPS:
12346   case X86ISD::PSHUFD:
12347   case X86ISD::PSHUFHW:
12348   case X86ISD::PSHUFLW:
12349   case X86ISD::MOVSS:
12350   case X86ISD::MOVSD:
12351   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12352   }
12353
12354   return SDValue();
12355 }
12356
12357 /// isTypeDesirableForOp - Return true if the target has native support for
12358 /// the specified value type and it is 'desirable' to use the type for the
12359 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12360 /// instruction encodings are longer and some i16 instructions are slow.
12361 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12362   if (!isTypeLegal(VT))
12363     return false;
12364   if (VT != MVT::i16)
12365     return true;
12366
12367   switch (Opc) {
12368   default:
12369     return true;
12370   case ISD::LOAD:
12371   case ISD::SIGN_EXTEND:
12372   case ISD::ZERO_EXTEND:
12373   case ISD::ANY_EXTEND:
12374   case ISD::SHL:
12375   case ISD::SRL:
12376   case ISD::SUB:
12377   case ISD::ADD:
12378   case ISD::MUL:
12379   case ISD::AND:
12380   case ISD::OR:
12381   case ISD::XOR:
12382     return false;
12383   }
12384 }
12385
12386 /// IsDesirableToPromoteOp - This method query the target whether it is
12387 /// beneficial for dag combiner to promote the specified node. If true, it
12388 /// should return the desired promotion type by reference.
12389 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12390   EVT VT = Op.getValueType();
12391   if (VT != MVT::i16)
12392     return false;
12393
12394   bool Promote = false;
12395   bool Commute = false;
12396   switch (Op.getOpcode()) {
12397   default: break;
12398   case ISD::LOAD: {
12399     LoadSDNode *LD = cast<LoadSDNode>(Op);
12400     // If the non-extending load has a single use and it's not live out, then it
12401     // might be folded.
12402     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12403                                                      Op.hasOneUse()*/) {
12404       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12405              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12406         // The only case where we'd want to promote LOAD (rather then it being
12407         // promoted as an operand is when it's only use is liveout.
12408         if (UI->getOpcode() != ISD::CopyToReg)
12409           return false;
12410       }
12411     }
12412     Promote = true;
12413     break;
12414   }
12415   case ISD::SIGN_EXTEND:
12416   case ISD::ZERO_EXTEND:
12417   case ISD::ANY_EXTEND:
12418     Promote = true;
12419     break;
12420   case ISD::SHL:
12421   case ISD::SRL: {
12422     SDValue N0 = Op.getOperand(0);
12423     // Look out for (store (shl (load), x)).
12424     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12425       return false;
12426     Promote = true;
12427     break;
12428   }
12429   case ISD::ADD:
12430   case ISD::MUL:
12431   case ISD::AND:
12432   case ISD::OR:
12433   case ISD::XOR:
12434     Commute = true;
12435     // fallthrough
12436   case ISD::SUB: {
12437     SDValue N0 = Op.getOperand(0);
12438     SDValue N1 = Op.getOperand(1);
12439     if (!Commute && MayFoldLoad(N1))
12440       return false;
12441     // Avoid disabling potential load folding opportunities.
12442     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12443       return false;
12444     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12445       return false;
12446     Promote = true;
12447   }
12448   }
12449
12450   PVT = MVT::i32;
12451   return Promote;
12452 }
12453
12454 //===----------------------------------------------------------------------===//
12455 //                           X86 Inline Assembly Support
12456 //===----------------------------------------------------------------------===//
12457
12458 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12459   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12460
12461   std::string AsmStr = IA->getAsmString();
12462
12463   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12464   SmallVector<StringRef, 4> AsmPieces;
12465   SplitString(AsmStr, AsmPieces, ";\n");
12466
12467   switch (AsmPieces.size()) {
12468   default: return false;
12469   case 1:
12470     AsmStr = AsmPieces[0];
12471     AsmPieces.clear();
12472     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12473
12474     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12475     // we will turn this bswap into something that will be lowered to logical ops
12476     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12477     // so don't worry about this.
12478     // bswap $0
12479     if (AsmPieces.size() == 2 &&
12480         (AsmPieces[0] == "bswap" ||
12481          AsmPieces[0] == "bswapq" ||
12482          AsmPieces[0] == "bswapl") &&
12483         (AsmPieces[1] == "$0" ||
12484          AsmPieces[1] == "${0:q}")) {
12485       // No need to check constraints, nothing other than the equivalent of
12486       // "=r,0" would be valid here.
12487       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12488       if (!Ty || Ty->getBitWidth() % 16 != 0)
12489         return false;
12490       return IntrinsicLowering::LowerToByteSwap(CI);
12491     }
12492     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12493     if (CI->getType()->isIntegerTy(16) &&
12494         AsmPieces.size() == 3 &&
12495         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12496         AsmPieces[1] == "$$8," &&
12497         AsmPieces[2] == "${0:w}" &&
12498         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12499       AsmPieces.clear();
12500       const std::string &ConstraintsStr = IA->getConstraintString();
12501       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12502       std::sort(AsmPieces.begin(), AsmPieces.end());
12503       if (AsmPieces.size() == 4 &&
12504           AsmPieces[0] == "~{cc}" &&
12505           AsmPieces[1] == "~{dirflag}" &&
12506           AsmPieces[2] == "~{flags}" &&
12507           AsmPieces[3] == "~{fpsr}") {
12508         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12509         if (!Ty || Ty->getBitWidth() % 16 != 0)
12510           return false;
12511         return IntrinsicLowering::LowerToByteSwap(CI);
12512       }
12513     }
12514     break;
12515   case 3:
12516     if (CI->getType()->isIntegerTy(32) &&
12517         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12518       SmallVector<StringRef, 4> Words;
12519       SplitString(AsmPieces[0], Words, " \t,");
12520       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12521           Words[2] == "${0:w}") {
12522         Words.clear();
12523         SplitString(AsmPieces[1], Words, " \t,");
12524         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12525             Words[2] == "$0") {
12526           Words.clear();
12527           SplitString(AsmPieces[2], Words, " \t,");
12528           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12529               Words[2] == "${0:w}") {
12530             AsmPieces.clear();
12531             const std::string &ConstraintsStr = IA->getConstraintString();
12532             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12533             std::sort(AsmPieces.begin(), AsmPieces.end());
12534             if (AsmPieces.size() == 4 &&
12535                 AsmPieces[0] == "~{cc}" &&
12536                 AsmPieces[1] == "~{dirflag}" &&
12537                 AsmPieces[2] == "~{flags}" &&
12538                 AsmPieces[3] == "~{fpsr}") {
12539               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12540               if (!Ty || Ty->getBitWidth() % 16 != 0)
12541                 return false;
12542               return IntrinsicLowering::LowerToByteSwap(CI);
12543             }
12544           }
12545         }
12546       }
12547     }
12548
12549     if (CI->getType()->isIntegerTy(64)) {
12550       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12551       if (Constraints.size() >= 2 &&
12552           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12553           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12554         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12555         SmallVector<StringRef, 4> Words;
12556         SplitString(AsmPieces[0], Words, " \t");
12557         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12558           Words.clear();
12559           SplitString(AsmPieces[1], Words, " \t");
12560           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12561             Words.clear();
12562             SplitString(AsmPieces[2], Words, " \t,");
12563             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12564                 Words[2] == "%edx") {
12565               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12566               if (!Ty || Ty->getBitWidth() % 16 != 0)
12567                 return false;
12568               return IntrinsicLowering::LowerToByteSwap(CI);
12569             }
12570           }
12571         }
12572       }
12573     }
12574     break;
12575   }
12576   return false;
12577 }
12578
12579
12580
12581 /// getConstraintType - Given a constraint letter, return the type of
12582 /// constraint it is for this target.
12583 X86TargetLowering::ConstraintType
12584 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12585   if (Constraint.size() == 1) {
12586     switch (Constraint[0]) {
12587     case 'R':
12588     case 'q':
12589     case 'Q':
12590     case 'f':
12591     case 't':
12592     case 'u':
12593     case 'y':
12594     case 'x':
12595     case 'Y':
12596       return C_RegisterClass;
12597     case 'a':
12598     case 'b':
12599     case 'c':
12600     case 'd':
12601     case 'S':
12602     case 'D':
12603     case 'A':
12604       return C_Register;
12605     case 'I':
12606     case 'J':
12607     case 'K':
12608     case 'L':
12609     case 'M':
12610     case 'N':
12611     case 'G':
12612     case 'C':
12613     case 'e':
12614     case 'Z':
12615       return C_Other;
12616     default:
12617       break;
12618     }
12619   }
12620   return TargetLowering::getConstraintType(Constraint);
12621 }
12622
12623 /// Examine constraint type and operand type and determine a weight value.
12624 /// This object must already have been set up with the operand type
12625 /// and the current alternative constraint selected.
12626 TargetLowering::ConstraintWeight
12627   X86TargetLowering::getSingleConstraintMatchWeight(
12628     AsmOperandInfo &info, const char *constraint) const {
12629   ConstraintWeight weight = CW_Invalid;
12630   Value *CallOperandVal = info.CallOperandVal;
12631     // If we don't have a value, we can't do a match,
12632     // but allow it at the lowest weight.
12633   if (CallOperandVal == NULL)
12634     return CW_Default;
12635   const Type *type = CallOperandVal->getType();
12636   // Look at the constraint type.
12637   switch (*constraint) {
12638   default:
12639     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12640   case 'R':
12641   case 'q':
12642   case 'Q':
12643   case 'a':
12644   case 'b':
12645   case 'c':
12646   case 'd':
12647   case 'S':
12648   case 'D':
12649   case 'A':
12650     if (CallOperandVal->getType()->isIntegerTy())
12651       weight = CW_SpecificReg;
12652     break;
12653   case 'f':
12654   case 't':
12655   case 'u':
12656       if (type->isFloatingPointTy())
12657         weight = CW_SpecificReg;
12658       break;
12659   case 'y':
12660       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12661         weight = CW_SpecificReg;
12662       break;
12663   case 'x':
12664   case 'Y':
12665     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12666       weight = CW_Register;
12667     break;
12668   case 'I':
12669     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12670       if (C->getZExtValue() <= 31)
12671         weight = CW_Constant;
12672     }
12673     break;
12674   case 'J':
12675     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12676       if (C->getZExtValue() <= 63)
12677         weight = CW_Constant;
12678     }
12679     break;
12680   case 'K':
12681     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12682       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12683         weight = CW_Constant;
12684     }
12685     break;
12686   case 'L':
12687     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12688       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12689         weight = CW_Constant;
12690     }
12691     break;
12692   case 'M':
12693     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12694       if (C->getZExtValue() <= 3)
12695         weight = CW_Constant;
12696     }
12697     break;
12698   case 'N':
12699     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12700       if (C->getZExtValue() <= 0xff)
12701         weight = CW_Constant;
12702     }
12703     break;
12704   case 'G':
12705   case 'C':
12706     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12707       weight = CW_Constant;
12708     }
12709     break;
12710   case 'e':
12711     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12712       if ((C->getSExtValue() >= -0x80000000LL) &&
12713           (C->getSExtValue() <= 0x7fffffffLL))
12714         weight = CW_Constant;
12715     }
12716     break;
12717   case 'Z':
12718     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12719       if (C->getZExtValue() <= 0xffffffff)
12720         weight = CW_Constant;
12721     }
12722     break;
12723   }
12724   return weight;
12725 }
12726
12727 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12728 /// with another that has more specific requirements based on the type of the
12729 /// corresponding operand.
12730 const char *X86TargetLowering::
12731 LowerXConstraint(EVT ConstraintVT) const {
12732   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12733   // 'f' like normal targets.
12734   if (ConstraintVT.isFloatingPoint()) {
12735     if (Subtarget->hasXMMInt())
12736       return "Y";
12737     if (Subtarget->hasXMM())
12738       return "x";
12739   }
12740
12741   return TargetLowering::LowerXConstraint(ConstraintVT);
12742 }
12743
12744 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12745 /// vector.  If it is invalid, don't add anything to Ops.
12746 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12747                                                      std::string &Constraint,
12748                                                      std::vector<SDValue>&Ops,
12749                                                      SelectionDAG &DAG) const {
12750   SDValue Result(0, 0);
12751
12752   // Only support length 1 constraints for now.
12753   if (Constraint.length() > 1) return;
12754
12755   char ConstraintLetter = Constraint[0];
12756   switch (ConstraintLetter) {
12757   default: break;
12758   case 'I':
12759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12760       if (C->getZExtValue() <= 31) {
12761         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12762         break;
12763       }
12764     }
12765     return;
12766   case 'J':
12767     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12768       if (C->getZExtValue() <= 63) {
12769         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12770         break;
12771       }
12772     }
12773     return;
12774   case 'K':
12775     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12776       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12777         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12778         break;
12779       }
12780     }
12781     return;
12782   case 'N':
12783     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12784       if (C->getZExtValue() <= 255) {
12785         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12786         break;
12787       }
12788     }
12789     return;
12790   case 'e': {
12791     // 32-bit signed value
12792     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12793       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12794                                            C->getSExtValue())) {
12795         // Widen to 64 bits here to get it sign extended.
12796         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12797         break;
12798       }
12799     // FIXME gcc accepts some relocatable values here too, but only in certain
12800     // memory models; it's complicated.
12801     }
12802     return;
12803   }
12804   case 'Z': {
12805     // 32-bit unsigned value
12806     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12807       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12808                                            C->getZExtValue())) {
12809         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12810         break;
12811       }
12812     }
12813     // FIXME gcc accepts some relocatable values here too, but only in certain
12814     // memory models; it's complicated.
12815     return;
12816   }
12817   case 'i': {
12818     // Literal immediates are always ok.
12819     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12820       // Widen to 64 bits here to get it sign extended.
12821       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12822       break;
12823     }
12824
12825     // In any sort of PIC mode addresses need to be computed at runtime by
12826     // adding in a register or some sort of table lookup.  These can't
12827     // be used as immediates.
12828     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12829       return;
12830
12831     // If we are in non-pic codegen mode, we allow the address of a global (with
12832     // an optional displacement) to be used with 'i'.
12833     GlobalAddressSDNode *GA = 0;
12834     int64_t Offset = 0;
12835
12836     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12837     while (1) {
12838       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12839         Offset += GA->getOffset();
12840         break;
12841       } else if (Op.getOpcode() == ISD::ADD) {
12842         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12843           Offset += C->getZExtValue();
12844           Op = Op.getOperand(0);
12845           continue;
12846         }
12847       } else if (Op.getOpcode() == ISD::SUB) {
12848         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12849           Offset += -C->getZExtValue();
12850           Op = Op.getOperand(0);
12851           continue;
12852         }
12853       }
12854
12855       // Otherwise, this isn't something we can handle, reject it.
12856       return;
12857     }
12858
12859     const GlobalValue *GV = GA->getGlobal();
12860     // If we require an extra load to get this address, as in PIC mode, we
12861     // can't accept it.
12862     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12863                                                         getTargetMachine())))
12864       return;
12865
12866     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12867                                         GA->getValueType(0), Offset);
12868     break;
12869   }
12870   }
12871
12872   if (Result.getNode()) {
12873     Ops.push_back(Result);
12874     return;
12875   }
12876   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12877 }
12878
12879 std::vector<unsigned> X86TargetLowering::
12880 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12881                                   EVT VT) const {
12882   if (Constraint.size() == 1) {
12883     // FIXME: not handling fp-stack yet!
12884     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12885     default: break;  // Unknown constraint letter
12886     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12887       if (Subtarget->is64Bit()) {
12888         if (VT == MVT::i32)
12889           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12890                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12891                                        X86::R10D,X86::R11D,X86::R12D,
12892                                        X86::R13D,X86::R14D,X86::R15D,
12893                                        X86::EBP, X86::ESP, 0);
12894         else if (VT == MVT::i16)
12895           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12896                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12897                                        X86::R10W,X86::R11W,X86::R12W,
12898                                        X86::R13W,X86::R14W,X86::R15W,
12899                                        X86::BP,  X86::SP, 0);
12900         else if (VT == MVT::i8)
12901           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12902                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12903                                        X86::R10B,X86::R11B,X86::R12B,
12904                                        X86::R13B,X86::R14B,X86::R15B,
12905                                        X86::BPL, X86::SPL, 0);
12906
12907         else if (VT == MVT::i64)
12908           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12909                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12910                                        X86::R10, X86::R11, X86::R12,
12911                                        X86::R13, X86::R14, X86::R15,
12912                                        X86::RBP, X86::RSP, 0);
12913
12914         break;
12915       }
12916       // 32-bit fallthrough
12917     case 'Q':   // Q_REGS
12918       if (VT == MVT::i32)
12919         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12920       else if (VT == MVT::i16)
12921         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12922       else if (VT == MVT::i8)
12923         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12924       else if (VT == MVT::i64)
12925         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12926       break;
12927     }
12928   }
12929
12930   return std::vector<unsigned>();
12931 }
12932
12933 std::pair<unsigned, const TargetRegisterClass*>
12934 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12935                                                 EVT VT) const {
12936   // First, see if this is a constraint that directly corresponds to an LLVM
12937   // register class.
12938   if (Constraint.size() == 1) {
12939     // GCC Constraint Letters
12940     switch (Constraint[0]) {
12941     default: break;
12942     case 'r':   // GENERAL_REGS
12943     case 'l':   // INDEX_REGS
12944       if (VT == MVT::i8)
12945         return std::make_pair(0U, X86::GR8RegisterClass);
12946       if (VT == MVT::i16)
12947         return std::make_pair(0U, X86::GR16RegisterClass);
12948       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12949         return std::make_pair(0U, X86::GR32RegisterClass);
12950       return std::make_pair(0U, X86::GR64RegisterClass);
12951     case 'R':   // LEGACY_REGS
12952       if (VT == MVT::i8)
12953         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12954       if (VT == MVT::i16)
12955         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12956       if (VT == MVT::i32 || !Subtarget->is64Bit())
12957         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12958       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12959     case 'f':  // FP Stack registers.
12960       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12961       // value to the correct fpstack register class.
12962       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12963         return std::make_pair(0U, X86::RFP32RegisterClass);
12964       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12965         return std::make_pair(0U, X86::RFP64RegisterClass);
12966       return std::make_pair(0U, X86::RFP80RegisterClass);
12967     case 'y':   // MMX_REGS if MMX allowed.
12968       if (!Subtarget->hasMMX()) break;
12969       return std::make_pair(0U, X86::VR64RegisterClass);
12970     case 'Y':   // SSE_REGS if SSE2 allowed
12971       if (!Subtarget->hasXMMInt()) break;
12972       // FALL THROUGH.
12973     case 'x':   // SSE_REGS if SSE1 allowed
12974       if (!Subtarget->hasXMM()) break;
12975
12976       switch (VT.getSimpleVT().SimpleTy) {
12977       default: break;
12978       // Scalar SSE types.
12979       case MVT::f32:
12980       case MVT::i32:
12981         return std::make_pair(0U, X86::FR32RegisterClass);
12982       case MVT::f64:
12983       case MVT::i64:
12984         return std::make_pair(0U, X86::FR64RegisterClass);
12985       // Vector types.
12986       case MVT::v16i8:
12987       case MVT::v8i16:
12988       case MVT::v4i32:
12989       case MVT::v2i64:
12990       case MVT::v4f32:
12991       case MVT::v2f64:
12992         return std::make_pair(0U, X86::VR128RegisterClass);
12993       }
12994       break;
12995     }
12996   }
12997
12998   // Use the default implementation in TargetLowering to convert the register
12999   // constraint into a member of a register class.
13000   std::pair<unsigned, const TargetRegisterClass*> Res;
13001   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13002
13003   // Not found as a standard register?
13004   if (Res.second == 0) {
13005     // Map st(0) -> st(7) -> ST0
13006     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13007         tolower(Constraint[1]) == 's' &&
13008         tolower(Constraint[2]) == 't' &&
13009         Constraint[3] == '(' &&
13010         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13011         Constraint[5] == ')' &&
13012         Constraint[6] == '}') {
13013
13014       Res.first = X86::ST0+Constraint[4]-'0';
13015       Res.second = X86::RFP80RegisterClass;
13016       return Res;
13017     }
13018
13019     // GCC allows "st(0)" to be called just plain "st".
13020     if (StringRef("{st}").equals_lower(Constraint)) {
13021       Res.first = X86::ST0;
13022       Res.second = X86::RFP80RegisterClass;
13023       return Res;
13024     }
13025
13026     // flags -> EFLAGS
13027     if (StringRef("{flags}").equals_lower(Constraint)) {
13028       Res.first = X86::EFLAGS;
13029       Res.second = X86::CCRRegisterClass;
13030       return Res;
13031     }
13032
13033     // 'A' means EAX + EDX.
13034     if (Constraint == "A") {
13035       Res.first = X86::EAX;
13036       Res.second = X86::GR32_ADRegisterClass;
13037       return Res;
13038     }
13039     return Res;
13040   }
13041
13042   // Otherwise, check to see if this is a register class of the wrong value
13043   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13044   // turn into {ax},{dx}.
13045   if (Res.second->hasType(VT))
13046     return Res;   // Correct type already, nothing to do.
13047
13048   // All of the single-register GCC register classes map their values onto
13049   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13050   // really want an 8-bit or 32-bit register, map to the appropriate register
13051   // class and return the appropriate register.
13052   if (Res.second == X86::GR16RegisterClass) {
13053     if (VT == MVT::i8) {
13054       unsigned DestReg = 0;
13055       switch (Res.first) {
13056       default: break;
13057       case X86::AX: DestReg = X86::AL; break;
13058       case X86::DX: DestReg = X86::DL; break;
13059       case X86::CX: DestReg = X86::CL; break;
13060       case X86::BX: DestReg = X86::BL; break;
13061       }
13062       if (DestReg) {
13063         Res.first = DestReg;
13064         Res.second = X86::GR8RegisterClass;
13065       }
13066     } else if (VT == MVT::i32) {
13067       unsigned DestReg = 0;
13068       switch (Res.first) {
13069       default: break;
13070       case X86::AX: DestReg = X86::EAX; break;
13071       case X86::DX: DestReg = X86::EDX; break;
13072       case X86::CX: DestReg = X86::ECX; break;
13073       case X86::BX: DestReg = X86::EBX; break;
13074       case X86::SI: DestReg = X86::ESI; break;
13075       case X86::DI: DestReg = X86::EDI; break;
13076       case X86::BP: DestReg = X86::EBP; break;
13077       case X86::SP: DestReg = X86::ESP; break;
13078       }
13079       if (DestReg) {
13080         Res.first = DestReg;
13081         Res.second = X86::GR32RegisterClass;
13082       }
13083     } else if (VT == MVT::i64) {
13084       unsigned DestReg = 0;
13085       switch (Res.first) {
13086       default: break;
13087       case X86::AX: DestReg = X86::RAX; break;
13088       case X86::DX: DestReg = X86::RDX; break;
13089       case X86::CX: DestReg = X86::RCX; break;
13090       case X86::BX: DestReg = X86::RBX; break;
13091       case X86::SI: DestReg = X86::RSI; break;
13092       case X86::DI: DestReg = X86::RDI; break;
13093       case X86::BP: DestReg = X86::RBP; break;
13094       case X86::SP: DestReg = X86::RSP; break;
13095       }
13096       if (DestReg) {
13097         Res.first = DestReg;
13098         Res.second = X86::GR64RegisterClass;
13099       }
13100     }
13101   } else if (Res.second == X86::FR32RegisterClass ||
13102              Res.second == X86::FR64RegisterClass ||
13103              Res.second == X86::VR128RegisterClass) {
13104     // Handle references to XMM physical registers that got mapped into the
13105     // wrong class.  This can happen with constraints like {xmm0} where the
13106     // target independent register mapper will just pick the first match it can
13107     // find, ignoring the required type.
13108     if (VT == MVT::f32)
13109       Res.second = X86::FR32RegisterClass;
13110     else if (VT == MVT::f64)
13111       Res.second = X86::FR64RegisterClass;
13112     else if (X86::VR128RegisterClass->hasType(VT))
13113       Res.second = X86::VR128RegisterClass;
13114   }
13115
13116   return Res;
13117 }